示例#1
0
 /// <summary>
 /// Constructor for the <see cref="CsDelegate"/>
 /// </summary>
 /// <param name="isLoaded">Flag that determines if the model was loaded.</param>
 /// <param name="hasErrors">Flag that determine if errors were found creating the model.</param>
 /// <param name="loadedFromSource">Flag that determines if the model was loaded from source code or from an existing library.</param>
 /// <param name="language">The target language the model was generated from.</param>
 /// <param name="attributes">List of the attributes assigned to this model.</param>
 /// <param name="isGeneric">Flag that determines if the delegate is a generic definition.</param>
 /// <param name="hasStrongTypesInGenerics">Flag that determines if the generics use strong type definitions.</param>
 /// <param name="genericParameters">Generic parameters assigned to the delegate.</param>
 /// <param name="genericTypes">Target types for the generic parameters assigned to the delegate.</param>
 /// <param name="hasDocumentation">Flag that determines if the model has XML documentation assigned to it.</param>
 /// <param name="documentation">The xml documentation assigned to the model.</param>
 /// <param name="lookupPath">The fully qualified model lookup path for this model.</param>
 /// <param name="sourceFiles">List of the fully qualified paths to the source code files this member is defined in.</param>
 /// <param name="name">The name of the model.</param>
 /// <param name="ns">The namespace this delegate is assigned to.</param>
 /// <param name="isVoid">Flag that determines if the return type is void. </param>
 /// <param name="parentPath">THe fully qualified lookup path for the parent model to this one.</param>
 /// <param name="security">The security scope assigned to this model.</param>
 /// <param name="returnType">The type definition for the return type.</param>
 /// <param name="hasParameters">Flag that determines if the delegate had parameters.</param>
 /// <param name="parameters">The parameters assigned to the delegate.</param>
 /// <param name="invokeMethod">The invoke method definition assigned to this delegate.</param>
 /// <param name="beginInvokeMethod">The begin invoke method definition assigned to this delegate.</param>
 /// <param name="endInvokeMethod">The end invoke method definition assigned to this delegate.</param>
 /// <param name="sourceDocument">The source document that was used to build this model. This is optional parameter and can be null.</param>
 /// <param name="modelStore">Optional the lookup storage for models created during the compile or lookup of the model.</param>
 /// <param name="modelErrors">Optional the error that occured while creating the model.</param>
 protected CsDelegate(bool isLoaded, bool hasErrors, bool loadedFromSource, SourceCodeType language,
                      IReadOnlyList <CsAttribute> attributes, bool isGeneric, bool hasStrongTypesInGenerics, IReadOnlyList <CsGenericParameter> genericParameters,
                      IReadOnlyList <CsType> genericTypes, bool hasDocumentation, string documentation, string lookupPath,
                      IReadOnlyList <string> sourceFiles, string name, string ns, bool hasParameters, bool isVoid, string parentPath,
                      CsSecurity security, CsType returnType, IReadOnlyList <CsParameter> parameters, CsMethod invokeMethod,
                      CsMethod beginInvokeMethod, CsMethod endInvokeMethod, string sourceDocument = null, ModelStore <ICsModel> modelStore = null, IReadOnlyList <ModelLoadException> modelErrors = null)
     : base(isLoaded, hasErrors, loadedFromSource, language, CsModelType.Delegate, sourceDocument, modelStore, modelErrors)
 {
     _attributes = attributes ?? ImmutableList <CsAttribute> .Empty;
     _isGeneric  = isGeneric;
     _hasStrongTypesInGenerics = hasStrongTypesInGenerics;
     _genericParameters        = genericParameters ?? ImmutableList <CsGenericParameter> .Empty;
     _genericTypes             = genericTypes ?? ImmutableList <CsType> .Empty;
     _hasDocumentation         = hasDocumentation;
     _documentation            = documentation;
     _lookupPath        = lookupPath;
     _sourceFiles       = sourceFiles ?? ImmutableList <string> .Empty;
     _name              = name;
     _ns                = ns;
     _hasParameters     = hasParameters;
     _isVoid            = isVoid;
     _parentPath        = parentPath;
     _security          = security;
     _returnType        = returnType;
     _parameters        = parameters ?? ImmutableList <CsParameter> .Empty;
     _invokeMethod      = invokeMethod;
     _beginInvokeMethod = beginInvokeMethod;
     _endInvokeMethod   = endInvokeMethod;
 }
 /// <summary>
 /// Constructor for the <see cref="CsContainer"/>
 /// </summary>
 /// <param name="isLoaded">Flag that determines if the model was loaded.</param>
 /// <param name="hasErrors">Flag that determine if errors were found creating the model.</param>
 /// <param name="loadedFromSource">Flag that determines if the model was loaded from source code or from an existing library.</param>
 /// <param name="language">The target language the model was generated from.</param>
 /// <param name="modelType">The type of code model created.</param>
 /// <param name="members">The members assigned to this container.</param>
 /// <param name="sourceDocument">The source document that was used to build this model. This is optional parameter and can be null.</param>
 /// <param name="modelStore">Optional the lookup storage for models created during the compile or lookup of the model.</param>
 /// <param name="modelErrors">Optional the error that occured while creating the model.</param>
 /// <param name="attributes">List of the attributes assigned to this model.</param>
 /// <param name="isGeneric">Flag that determines if the container is a generic definition.</param>
 /// <param name="hasStrongTypesInGenerics">Flag that determines if the generics use strong type definitions.</param>
 /// <param name="genericParameters">Generic parameters assigned to the container.</param>
 /// <param name="genericTypes">Target types for the generic parameters assigned to the container.</param>
 /// <param name="sourceFiles">List of the fully qualified paths to the source code files this model is defined in.</param>
 /// <param name="hasDocumentation">Flag that determines if the model has XML documentation assigned to it.</param>
 /// <param name="documentation">The xml documentation assigned to the model.</param>
 /// <param name="lookupPath">The fully qualified model lookup path for this model.</param>
 /// <param name="name">The name of the model.</param>
 /// <param name="ns">The namespace the container belongs to.</param>
 /// <param name="parentPath">The fully qualified lookup path for the parent model to this one.</param>
 /// <param name="containerType">The type of container this model represents.</param>
 /// <param name="security">The security scope assigned to this model.</param>
 /// <param name="inheritedInterfaces">The interfaces that are inherited by this container.</param>
 protected CsContainer(bool isLoaded, bool hasErrors, bool loadedFromSource, SourceCodeType language, CsModelType modelType,
                       IReadOnlyList <CsAttribute> attributes, bool isGeneric, bool hasStrongTypesInGenerics,
                       IReadOnlyList <CsGenericParameter> genericParameters, IReadOnlyList <CsType> genericTypes,
                       IReadOnlyList <string> sourceFiles, bool hasDocumentation, string documentation, string lookupPath,
                       string name, string ns, string parentPath, CsContainerType containerType, CsSecurity security,
                       IReadOnlyList <CsInterface> inheritedInterfaces, IReadOnlyList <CsMember> members,
                       string sourceDocument = null, ModelStore <ICsModel> modelStore = null, IReadOnlyList <ModelLoadException> modelErrors = null)
     : base(isLoaded, hasErrors, loadedFromSource, language, modelType, sourceDocument, modelStore, modelErrors)
 {
     _attributes = attributes ?? ImmutableList <CsAttribute> .Empty;
     _isGeneric  = isGeneric;
     _hasStrongTypesInGenerics = hasStrongTypesInGenerics;
     _genericParameters        = genericParameters ?? ImmutableList <CsGenericParameter> .Empty;
     _genericTypes             = genericTypes ?? ImmutableList <CsType> .Empty;
     _sourceFiles      = sourceFiles ?? ImmutableList <string> .Empty;
     _hasDocumentation = hasDocumentation;
     _documentation    = documentation;
     _lookupPath       = lookupPath;
     _name             = name;
     _ns                  = ns;
     _parentPath          = parentPath;
     _containerType       = containerType;
     _security            = security;
     _inheritedInterfaces = inheritedInterfaces ?? ImmutableList <CsInterface> .Empty;
     _members             = members ?? ImmutableList <CsMember> .Empty;
 }
示例#3
0
 /// <summary>
 /// Constructor for the <see cref="CsMethod"/>
 /// </summary>
 /// <param name="isLoaded">Flag that determines if the model was loaded.</param>
 /// <param name="hasErrors">Flag that determine if errors were found creating the model.</param>
 /// <param name="loadedFromSource">Flag that determines if the model was loaded from source code or from an existing library.</param>
 /// <param name="language">The target language the model was generated from.</param>
 /// <param name="parameters">The parameters assigned to the method.</param>
 /// <param name="sourceDocument">The source document that was used to build this model. This is optional parameter and can be null.</param>
 /// <param name="modelStore">Optional the lookup storage for models created during the compile or lookup of the model.</param>
 /// <param name="modelErrors">Optional the error that occured while creating the model.</param>
 /// <param name="attributes">List of the attributes assigned to this model.</param>
 /// <param name="sourceFiles">List of the fully qualified paths to the source code files this member is defined in.</param>
 /// <param name="hasDocumentation">Flag that determines if the model has XML documentation assigned to it.</param>
 /// <param name="documentation">The xml documentation assigned to the model.</param>
 /// <param name="lookupPath">The fully qualified model lookup path for this model.</param>
 /// <param name="name">The name of the model.</param>
 /// <param name="parentPath">THe fully qualified lookup path for the parent model to this one.</param>
 /// <param name="security">The security scope assigned to this model.</param>
 /// <param name="isGeneric">Flag that determines if the method is a generic definition.</param>
 /// <param name="hasStrongTypesInGenerics">Flag that determines if the generics use strong type definitions.</param>
 /// <param name="genericParameters">Generic parameters assigned to the method.</param>
 /// <param name="genericTypes">Target types for the generic parameters assigned to the method.</param>
 /// <param name="hasParameters">Flag that determines if the method had parameters.</param>
 /// <param name="isAbstract">Flag that determines if the model is abstract.</param>
 /// <param name="isVirtual">Flag that determines if the model is virtual.</param>
 /// <param name="isSealed">Flag that determines if the model is sealed.</param>
 /// <param name="isOverride">Flag that determines if the model is overridden.</param>
 /// <param name="isStatic">Flag that determines if the model is static.</param>
 /// <param name="isVoid">Flag that determines if the return type is void. </param>
 /// <param name="isAsync">Flag that determines if the method has the async keyword assigned.</param>
 /// <param name="isExtension">Flag that determines if the method is an extension method.</param>
 /// <param name="methodType">The type of method that was implemented.</param>
 /// <param name="returnType">The type definition for the return type.</param>
 protected CsMethod(bool isLoaded, bool hasErrors, bool loadedFromSource, SourceCodeType language,
                    IReadOnlyList <CsAttribute> attributes, IReadOnlyList <string> sourceFiles,
                    bool hasDocumentation, string documentation, string lookupPath, string name, string parentPath,
                    CsSecurity security, bool isGeneric, bool hasStrongTypesInGenerics,
                    IReadOnlyList <CsGenericParameter> genericParameters, IReadOnlyList <CsType> genericTypes,
                    bool hasParameters, bool isAbstract, bool isVirtual, bool isSealed, bool isOverride, bool isStatic,
                    bool isVoid, bool isAsync, bool isExtension, CsMethodType methodType, CsType returnType,
                    IReadOnlyList <CsParameter> parameters, string sourceDocument = null,
                    ModelStore <ICsModel> modelStore = null, IReadOnlyList <ModelLoadException> modelErrors = null)
     : base(isLoaded, hasErrors, loadedFromSource, language, CsModelType.Method,
            attributes, sourceFiles, hasDocumentation, documentation, lookupPath, name, parentPath,
            security, CsMemberType.Method, sourceDocument, modelStore, modelErrors)
 {
     _isGeneric = isGeneric;
     _hasStrongTypesInGenerics = hasStrongTypesInGenerics;
     _genericParameters        = genericParameters ?? ImmutableList <CsGenericParameter> .Empty;
     _genericTypes             = genericTypes ?? ImmutableList <CsType> .Empty;
     _hasParameters            = hasParameters;
     _isAbstract  = isAbstract;
     _isVirtual   = isVirtual;
     _isSealed    = isSealed;
     _isOverride  = isOverride;
     _isStatic    = isStatic;
     _isVoid      = isVoid;
     _isAsync     = isAsync;
     _isExtension = isExtension;
     _methodType  = methodType;
     _returnType  = returnType;
     _parameters  = parameters ?? ImmutableList <CsParameter> .Empty;
 }
示例#4
0
        /// <summary>
        /// Generates the syntax definition of an event in c# syntax.
        /// </summary>
        /// <example>
        /// With Keywords [security] [keywords] event [event handler type] [name];
        /// Without Keywords [security] [keywords] event [event handler type] [name];
        /// </example>
        /// <param name="source">The source <see cref="CsEvent"/> model to generate.</param>
        /// <param name="manager">Namespace manager used to format type names.This is an optional parameter.</param>
        /// <param name="includeSecurity">Includes the security scope which was defined in the model.</param>
        /// <param name="eventSecurity">Optional parameter that sets the target security scope for the event.</param>
        /// <param name="includeKeywords">Optional parameter that determines if it will include all keywords assigned to the source model, default is false.</param>
        /// <param name="includeAbstractKeyword">Optional parameter that determines if it will include the definition for the abstract keyword in the definition if it is defined. default is false.</param>
        /// <param name="requireStaticKeyword">Adds the static keyword to the signature, default is false.</param>
        /// <param name="requireSealedKeyword">Adds the sealed keyword to the signature, default is false.</param>
        /// <param name="requireAbstractKeyword">Adds the abstract keyword to the signature, default is false.</param>
        /// <param name="requireOverrideKeyword">Adds the override keyword to the signature, default is false.</param>
        /// <param name="requireVirtualKeyword">Adds the virtual keyword to the signature, default is false.</param>
        /// <returns>Fully formatted event definition or null if the event data could not be generated.</returns>
        public static string CSharpFormatEventDeclaration(this CsEvent source, NamespaceManager manager = null, bool includeSecurity = true, CsSecurity eventSecurity = CsSecurity.Unknown,
                                                          bool includeKeywords        = true, bool includeAbstractKeyword = false, bool requireStaticKeyword = false, bool requireSealedKeyword = false, bool requireAbstractKeyword = false,
                                                          bool requireOverrideKeyword = false, bool requireVirtualKeyword = false)
        {
            if (source == null)
            {
                return(null);
            }
            if (!source.IsLoaded)
            {
                return(null);
            }

            StringBuilder eventFormatting = new StringBuilder();

            CsSecurity security = eventSecurity == CsSecurity.Unknown
                ? security = source.Security
                : security = eventSecurity;

            if (includeKeywords & source.IsSealed)
            {
                eventFormatting.Append($"{Keywords.Sealed} ");
            }

            if (includeSecurity)
            {
                eventFormatting.Append($"{security.CSharpFormatKeyword()} ");
            }

            if (includeKeywords)
            {
                if (source.IsStatic)
                {
                    eventFormatting.Append($"{Keywords.Static} ");
                }
                if (includeAbstractKeyword & source.IsAbstract)
                {
                    eventFormatting.Append($"{Keywords.Abstract} ");
                }
                if (source.IsOverride)
                {
                    eventFormatting.Append($"{Keywords.Override} ");
                }
                if (source.IsVirtual)
                {
                    eventFormatting.Append($"{Keywords.Virtual} ");
                }
            }

            var signature = source.CSharpFormatEventSignature(manager, includeSecurity, security, includeKeywords,
                                                              includeAbstractKeyword, requireStaticKeyword, requireSealedKeyword, requireAbstractKeyword,
                                                              requireOverrideKeyword, requireVirtualKeyword);

            eventFormatting.Append($"{signature};");

            return(eventFormatting.ToString());
        }
示例#5
0
 /// <summary>
 /// Constructor for the <see cref="CsStructure"/>
 /// </summary>
 /// <param name="isLoaded">Flag that determines if the model was loaded.</param>
 /// <param name="hasErrors">Flag that determine if errors were found creating the model.</param>
 /// <param name="loadedFromSource">Flag that determines if the model was loaded from source code or from an existing library.</param>
 /// <param name="language">The target language the model was generated from.</param>
 /// <param name="members">The members assigned to this container.</param>
 /// <param name="sourceDocument">The source document that was used to build this model. This is optional parameter and can be null.</param>
 /// <param name="modelStore">Optional the lookup storage for models created during the compile or lookup of the model.</param>
 /// <param name="modelErrors">Optional the error that occured while creating the model.</param>
 /// <param name="attributes">List of the attributes assigned to this model.</param>
 /// <param name="isGeneric">Flag that determines if the container is a generic definition.</param>
 /// <param name="hasStrongTypesInGenerics">Flag that determines if the generics use strong type definitions.</param>
 /// <param name="genericParameters">Generic parameters assigned to the container.</param>
 /// <param name="genericTypes">Target types for the generic parameters assigned to the container.</param>
 /// <param name="sourceFiles">List of the fully qualified paths to the source code files this model is defined in.</param>
 /// <param name="hasDocumentation">Flag that determines if the model has XML documentation assigned to it.</param>
 /// <param name="documentation">The xml documentation assigned to the model.</param>
 /// <param name="lookupPath">The fully qualified model lookup path for this model.</param>
 /// <param name="name">The name of the model.</param>
 /// <param name="ns">The namespace the container belongs to.</param>
 /// <param name="parentPath">The fully qualified lookup path for the parent model to this one.</param>
 /// <param name="security">The security scope assigned to this model.</param>
 /// <param name="inheritedInterfaces">The interfaces that are inherited by this container.</param>
 protected CsStructure(bool isLoaded, bool hasErrors, bool loadedFromSource, SourceCodeType language,
                       IReadOnlyList <CsAttribute> attributes, bool isGeneric, bool hasStrongTypesInGenerics,
                       IReadOnlyList <CsGenericParameter> genericParameters, IReadOnlyList <CsType> genericTypes, IReadOnlyList <string> sourceFiles,
                       bool hasDocumentation, string documentation, string lookupPath, string name, string ns, string parentPath,
                       CsSecurity security, IReadOnlyList <CsInterface> inheritedInterfaces, IReadOnlyList <CsMember> members,
                       string sourceDocument = null, ModelStore <ICsModel> modelStore = null, IReadOnlyList <ModelLoadException> modelErrors = null)
     : base(isLoaded, hasErrors, loadedFromSource, language, CsModelType.Structure,
            attributes, isGeneric, hasStrongTypesInGenerics, genericParameters, genericTypes, sourceFiles, hasDocumentation,
            documentation, lookupPath, name, ns, parentPath, CsContainerType.Structure, security, inheritedInterfaces, members,
            sourceDocument, modelStore, modelErrors)
 {
     //Intentionally blank
 }
        /// <summary>
        /// Generates a default property definition with a backing properties. Will determine security modifiers and append to get and set statements when needed.
        /// </summary>
        /// <example>
        /// With Keywords [security] [keywords] [property type] [property name] { [get when used]{return [backingField];} [set when used]{ [backingField] = value;}  }
        /// Without Keywords [security] [property type] [property name] { [get when used]{return [backingField];} [set when used]{ [backingField] = value;}  }
        /// </example>
        /// <param name="source">Property model used for generation.</param>
        /// <param name="backingFieldName">the name of the backing field to be managed by the property.</param>
        /// <param name="manager">Namespace manager used to format type names.</param>
        /// <param name="includeKeyword">Optional parameter that determines if the keywords will be appended. Default is false.</param>
        /// <param name="includeAbstractKeyword">Will include the definition for the abstract keyword in the definition if it is defined. default is false.</param>
        /// <param name="requireStaticKeyword">Adds the static keyword to the signature, default is false.</param>
        /// <param name="requireSealedKeyword">Adds the sealed keyword to the signature, default is false.</param>
        /// <param name="requireAbstractKeyword">Adds the abstract keyword to the signature, default is false.</param>
        /// <param name="requireOverrideKeyword">Adds the override keyword to the signature, default is false.</param>
        /// <param name="requireVirtualKeyword">Adds the virtual keyword to the signature, default is false.</param>
        /// <param name="propertySecurity">Optional parameter that overrides the models property security and sets a new security access level.</param>
        /// <param name="setSecurity">Optional parameter that overrides the models set security level with a new access level. Will also define a set statement even if it is not defined.</param>
        /// <param name="getSecurity">Optional parameter that overrides the models get security level with a new access level. Will also define a get statement even if it is not defined.</param>
        /// <returns>Formatted property or null if model data was missing.</returns>
        public static string CSharpFormatDefaultPropertySignatureWithBackingField(this CsProperty source,
                                                                                  string backingFieldName, NamespaceManager manager = null, bool includeKeyword = false,
                                                                                  bool includeAbstractKeyword = false, bool requireStaticKeyword           = false, bool requireSealedKeyword  = false,
                                                                                  bool requireAbstractKeyword = false, bool requireOverrideKeyword         = false, bool requireVirtualKeyword = false,
                                                                                  CsSecurity propertySecurity = CsSecurity.Unknown, CsSecurity setSecurity = CsSecurity.Unknown,
                                                                                  CsSecurity getSecurity      = CsSecurity.Unknown)
        {
            if (!source.IsLoaded)
            {
                return(null);
            }
            if (string.IsNullOrEmpty(backingFieldName))
            {
                return(null);
            }

            string propertyDeclaration = CSharpFormatPropertyDeclaration(source, manager, true, includeKeyword, includeAbstractKeyword,
                                                                         requireStaticKeyword, requireSealedKeyword, requireAbstractKeyword, requireOverrideKeyword, requireVirtualKeyword, propertySecurity);

            if (string.IsNullOrEmpty(propertyDeclaration))
            {
                return(null);
            }

            StringBuilder propertyDefinition = new StringBuilder($"{propertyDeclaration} {{ ");

            if (source.HasGet | getSecurity != CsSecurity.Unknown)
            {
                var getStatement = source.CSharpFormatGetStatement(propertySecurity, getSecurity);
                if (getStatement == null)
                {
                    return(null);
                }
                propertyDefinition.Append($"{getStatement} {{ return {backingFieldName}; }} ");
            }

            if (source.HasSet | setSecurity != CsSecurity.Unknown)
            {
                var setStatement = source.CSharpFormatSetStatement(propertySecurity, setSecurity);
                if (setStatement == null)
                {
                    return(null);
                }
                propertyDefinition.Append($"{setStatement} {{ {backingFieldName} = value; }}  ");
            }

            propertyDefinition.Append("}");

            return(propertyDefinition.ToString());
        }
示例#7
0
 /// <summary>
 /// Constructor for the <see cref="CsField"/>
 /// </summary>
 /// <param name="isLoaded">Flag that determines if the model was loaded.</param>
 /// <param name="hasErrors">Flag that determine if errors were found creating the model.</param>
 /// <param name="loadedFromSource">Flag that determines if the model was loaded from source code or from an existing library.</param>
 /// <param name="language">The target language the model was generated from.</param>
 /// <param name="dataType">The type definition for the field.</param>
 /// <param name="sourceDocument">The source document that was used to build this model. This is optional parameter and can be null.</param>
 /// <param name="modelStore">Optional the lookup storage for models created during the compile or lookup of the model.</param>
 /// <param name="modelErrors">Optional the error that occured while creating the model.</param>
 /// <param name="attributes">List of the attributes assigned to this model.</param>
 /// <param name="sourceFiles">List of the fully qualified paths to the source code files this member is defined in.</param>
 /// <param name="hasDocumentation">Flag that determines if the model has XML documentation assigned to it.</param>
 /// <param name="documentation">The xml documentation assigned to the model.</param>
 /// <param name="lookupPath">The fully qualified model lookup path for this model.</param>
 /// <param name="name">The name of the model.</param>
 /// <param name="parentPath">THe fully qualified lookup path for the parent model to this one.</param>
 /// <param name="security">The security scope assigned to this model.</param>
 /// <param name="isReadOnly">Flag that determines if the model is read only.</param>
 /// <param name="isStatic">Flag that determines if the model is a static definition.</param>
 /// <param name="isConstant">Flag that determines if the field is a constant definition.</param>
 /// <param name="constantValue">The value assigned to the field if it is a constant definition.</param>
 protected CsField(bool isLoaded, bool hasErrors, bool loadedFromSource, SourceCodeType language,
                   IReadOnlyList <CsAttribute> attributes, IReadOnlyList <string> sourceFiles, bool hasDocumentation, string documentation,
                   string lookupPath, string name, string parentPath, CsSecurity security, bool isReadOnly,
                   bool isStatic, bool isConstant, string constantValue, CsType dataType, string sourceDocument, ModelStore <ICsModel> modelStore = null,
                   IReadOnlyList <ModelLoadException> modelErrors = null)
     : base(isLoaded, hasErrors, loadedFromSource, language, CsModelType.Field, attributes,
            sourceFiles, hasDocumentation, documentation, lookupPath,
            name, parentPath, security, CsMemberType.Field, sourceDocument, modelStore, modelErrors)
 {
     _isReadOnly    = isReadOnly;
     _isStatic      = isStatic;
     _isConstant    = isConstant;
     _constantValue = constantValue;
     _dataType      = dataType;
 }
 /// <summary>
 /// Constructor for the <see cref="CsMember"/>
 /// </summary>
 /// <param name="isLoaded">Flag that determines if the model was loaded.</param>
 /// <param name="hasErrors">Flag that determine if errors were found creating the model.</param>
 /// <param name="loadedFromSource">Flag that determines if the model was loaded from source code or from an existing library.</param>
 /// <param name="language">The target language the model was generated from.</param>
 /// <param name="memberType">The type of member this model represents.</param>
 /// <param name="sourceDocument">The source document that was used to build this model. This is optional parameter and can be null.</param>
 /// <param name="modelStore">Optional the lookup storage for models created during the compile or lookup of the model.</param>
 /// <param name="modelErrors">Optional the error that occured while creating the model.</param>
 /// <param name="modelType">The type of model that represents this member.</param>
 /// <param name="attributes">List of the attributes assigned to this model.</param>
 /// <param name="sourceFiles">List of the fully qualified paths to the source code files this member is defined in.</param>
 /// <param name="hasDocumentation">Flag that determines if the model has XML documentation assigned to it.</param>
 /// <param name="documentation">The xml documentation assigned to the model.</param>
 /// <param name="lookupPath">The fully qualified model lookup path for this model.</param>
 /// <param name="name">The name of the model.</param>
 /// <param name="parentPath">THe fully qualified lookup path for the parent model to this one.</param>
 /// <param name="security">The security scope assigned to this model.</param>
 protected CsMember(bool isLoaded, bool hasErrors, bool loadedFromSource, SourceCodeType language, CsModelType modelType,
                    IReadOnlyList <CsAttribute> attributes, IReadOnlyList <string> sourceFiles, bool hasDocumentation,
                    string documentation, string lookupPath, string name, string parentPath, CsSecurity security,
                    CsMemberType memberType, string sourceDocument = null, ModelStore <ICsModel> modelStore = null, IReadOnlyList <ModelLoadException> modelErrors = null)
     : base(isLoaded, hasErrors, loadedFromSource, language, modelType, sourceDocument, modelStore, modelErrors)
 {
     _attributes       = attributes ?? ImmutableList <CsAttribute> .Empty;
     _sourceFiles      = sourceFiles ?? ImmutableList <string> .Empty;
     _hasDocumentation = hasDocumentation;
     _documentation    = documentation;
     _lookupPath       = lookupPath;
     _name             = name;
     _parentPath       = parentPath;
     _security         = security;
     _memberType       = memberType;
 }
示例#9
0
        /// <summary>
        /// Extension method that formats the set statement of a property definition.
        /// </summary>
        /// <example>
        /// With the same security   [set] will return example: set
        /// With different security [security] [set] will return example: public set
        /// </example>
        /// <param name="source">the source property definition</param>
        /// <param name="propertySecurity">Optional parameter that defined the security used by the implementing property.</param>
        /// <param name="setSecurity">Optional parameter that allows you to set the set security level.</param>
        /// <returns>Will return the formatted set statement or null if the property model is empty or the property does not support set.</returns>
        public static string CSharpFormatSetStatement(this CsProperty source, CsSecurity propertySecurity = CsSecurity.Unknown,
                                                      CsSecurity setSecurity = CsSecurity.Unknown)
        {
            if (!source.IsLoaded)
            {
                return(null);
            }
            if (!source.HasSet & setSecurity == CsSecurity.Unknown)
            {
                return(null);
            }
            CsSecurity security = propertySecurity == CsSecurity.Unknown ? source.Security : propertySecurity;

            CsSecurity accessSecurity = setSecurity == CsSecurity.Unknown ? source.SetSecurity : setSecurity;

            return(security == accessSecurity ? "set" : $"{accessSecurity.CSharpFormatKeyword()} set");
        }
示例#10
0
 /// <summary>
 /// Constructor for the <see cref="CsEvent"/>
 /// </summary>
 /// <param name="isLoaded">Flag that determines if the model was loaded.</param>
 /// <param name="hasErrors">Flag that determine if errors were found creating the model.</param>
 /// <param name="loadedFromSource">Flag that determines if the model was loaded from source code or from an existing library.</param>
 /// <param name="language">The target language the model was generated from.</param>
 /// <param name="eventType">The type definition that supports this event.</param>
 /// <param name="sourceDocument">The source document that was used to build this model. This is optional parameter and can be null.</param>
 /// <param name="modelStore">Optional the lookup storage for models created during the compile or lookup of the model.</param>
 /// <param name="modelErrors">Optional the error that occured while creating the model.</param>
 /// <param name="attributes">List of the attributes assigned to this model.</param>
 /// <param name="sourceFiles">List of the fully qualified paths to the source code files this member is defined in.</param>
 /// <param name="hasDocumentation">Flag that determines if the model has XML documentation assigned to it.</param>
 /// <param name="documentation">The xml documentation assigned to the model.</param>
 /// <param name="lookupPath">The fully qualified model lookup path for this model.</param>
 /// <param name="name">The name of the model.</param>
 /// <param name="parentPath">THe fully qualified lookup path for the parent model to this one.</param>
 /// <param name="security">The security scope assigned to this model.</param>
 /// <param name="isAbstract">Flag that determines if the model is abstract.</param>
 /// <param name="isVirtual">Flag that determines if the model is virtual.</param>
 /// <param name="isSealed">Flag that determines if the model is sealed.</param>
 /// <param name="isOverride">Flag that determines if the model is overridden.</param>
 /// <param name="isStatic">Flag that determines if the model is static.</param>
 /// <param name="eventHandlerDelegate">Delegate model for this event.</param>
 /// <param name="raiseMethod">Model for the raise method for this event.</param>
 /// <param name="addMethod">Model for the add method for this event.</param>
 /// <param name="removeMethod">Model for the remove method for this event.</param>
 protected CsEvent(bool isLoaded, bool hasErrors, bool loadedFromSource, SourceCodeType language,
                   IReadOnlyList <CsAttribute> attributes, IReadOnlyList <string> sourceFiles, bool hasDocumentation, string documentation,
                   string lookupPath, string name, string parentPath, CsSecurity security, bool isAbstract, bool isVirtual, bool isOverride,
                   bool isSealed, bool isStatic, CsDelegate eventHandlerDelegate, CsMethod raiseMethod, CsMethod addMethod, CsMethod removeMethod,
                   CsType eventType, string sourceDocument = null, ModelStore <ICsModel> modelStore = null, IReadOnlyList <ModelLoadException> modelErrors = null) : base(isLoaded, hasErrors, loadedFromSource,
                                                                                                                                                                          language, CsModelType.Event, attributes, sourceFiles, hasDocumentation, documentation,
                                                                                                                                                                          lookupPath, name, parentPath, security, CsMemberType.Event, sourceDocument, modelStore, modelErrors)
 {
     _isAbstract           = isAbstract;
     _isVirtual            = isVirtual;
     _isOverride           = isOverride;
     _isSealed             = isSealed;
     _isStatic             = isStatic;
     _eventHandlerDelegate = eventHandlerDelegate;
     _raiseMethod          = raiseMethod;
     _addMethod            = addMethod;
     _removeMethod         = removeMethod;
     _eventType            = eventType;
 }
        /// <summary>
        /// Generates the syntax definition of field in c# syntax. The default definition with all options turned off will return the filed signature and constants if defined and the default values.
        /// </summary>
        /// <example>
        /// With Keywords [Security] [Keywords] [FieldType] [Name];
        /// With Keywords and a constant [Security] [Keywords] [FieldType] [Name] = [Constant Value];
        /// Without Keywords [Security] [FieldType] [Name];
        /// Without Keywords and a constant [Security] [FieldType] [Name] = [Constant Value];
        /// </example>
        /// <param name="source">The source <see cref="CsField"/> model to generate.</param>
        /// <param name="manager">Namespace manager used to format type names.This is an optional parameter.</param>
        /// <param name="includeKeywords">Optional parameter that will include all keywords assigned to the field from the source model. This is true by default.</param>
        /// <param name="fieldSecurity">Optional parameter to set the target security for the field.</param>
        /// <returns>Fully formatted field definition or null if the field data could not be generated.</returns>
        public static string CSharpFormatFieldDeclaration(this CsField source, NamespaceManager manager = null,
                                                          bool includeKeywords = true, CsSecurity fieldSecurity = CsSecurity.Unknown)

        {
            if (source == null)
            {
                return(null);
            }

            StringBuilder fieldFormatting = new StringBuilder();


            CsSecurity security = fieldSecurity == CsSecurity.Unknown ? source.Security : fieldSecurity;

            fieldFormatting.Append($"{security.CSharpFormatKeyword()} ");

            if (includeKeywords)
            {
                if (source.IsStatic)
                {
                    fieldFormatting.Append($"{Keywords.Static} ");
                }
                if (source.IsReadOnly)
                {
                    fieldFormatting.Append($"{Keywords.Readonly} ");
                }
            }

            if (source.IsConstant)
            {
                fieldFormatting.Append($"{Keywords.Constant} ");
            }
            fieldFormatting.Append($"{source.DataType.CSharpFormatTypeName(manager)} ");
            fieldFormatting.Append($"{source.Name}");
            if (source.IsConstant)
            {
                fieldFormatting.Append($" = {source.DataType.CSharpFormatValueSyntax(source.ConstantValue)}");
            }
            fieldFormatting.Append(";");

            return(fieldFormatting.ToString());
        }
示例#12
0
        /// <summary>
        /// Generates a default property definition with no backing properties. Will determine security modifiers and append to get and set statements when needed.
        /// </summary>
        /// <example>
        /// With Keywords [security] [keywords] [property type] [property name] { [get when used]; [set when used]; }
        /// No Keywords [security] [property type] [property name] { [get when used]; [set when used]; }
        /// </example>
        /// <param name="source">Property model used for generation.</param>
        /// <param name="manager">Namespace manager used to format type names.This is an optional parameter.</param>
        /// <param name="includeKeyword">Optional parameter that determines if the keywords will be appended. Default is false.</param>
        /// <param name="includeAbstractKeyword">Will include the definition for the abstract keyword in the definition if it is defined. default is false.</param>
        /// <param name="propertySecurity">Optional parameter that overrides the models property security and sets a new security access level.</param>
        /// <param name="setSecurity">Optional parameter that overrides the models set security level with a new access level. Will also define a set statement even if it is not defined.</param>
        /// <param name="getSecurity">Optional parameter that overrides the models get security level with a new access level. Will also define a get statement even if it is not defined.</param>
        /// <returns>Formatted property or null if model data was missing.</returns>
        public static string CSharpFormatDefaultPropertySignature(this CsProperty source, NamespaceManager manager = null, bool includeKeyword = false,
                                                                  bool includeAbstractKeyword = false, CsSecurity propertySecurity             = CsSecurity.Unknown, CsSecurity setSecurity = CsSecurity.Unknown,
                                                                  CsSecurity getSecurity      = CsSecurity.Unknown)
        {
            if (!source.IsLoaded)
            {
                return(null);
            }
            string propertyDeclaration = CSharpFormatPropertyDeclaration(source, manager, true, includeKeyword, includeAbstractKeyword,
                                                                         propertySecurity);

            if (string.IsNullOrEmpty(propertyDeclaration))
            {
                return(null);
            }

            StringBuilder propertyDefinition = new StringBuilder($"{propertyDeclaration} {{ ");

            if (source.HasGet | getSecurity != CsSecurity.Unknown)
            {
                var getStatement = source.CSharpFormatGetStatement(propertySecurity, getSecurity);
                if (getStatement == null)
                {
                    return(null);
                }
                propertyDefinition.Append($"{getStatement}; ");
            }

            if (source.HasSet | setSecurity != CsSecurity.Unknown)
            {
                var setStatement = source.CSharpFormatSetStatement(propertySecurity, setSecurity);
                if (setStatement == null)
                {
                    return(null);
                }
                propertyDefinition.Append($"{setStatement}; ");
            }

            propertyDefinition.Append("}");

            return(propertyDefinition.ToString());
        }
 /// <summary>
 /// Constructor for the <see cref="CsProperty"/>
 /// </summary>
 /// <param name="isLoaded">Flag that determines if the model was loaded.</param>
 /// <param name="hasErrors">Flag that determine if errors were found creating the model.</param>
 /// <param name="loadedFromSource">Flag that determines if the model was loaded from source code or from an existing library.</param>
 /// <param name="language">The target language the model was generated from.</param>
 /// <param name="setSecurity">The security access assigned to the setter.</param>
 /// <param name="sourceDocument">The source document that was used to build this model. This is optional parameter and can be null.</param>
 /// <param name="modelStore">Optional the lookup storage for models created during the compile or lookup of the model.</param>
 /// <param name="modelErrors">Optional the error that occured while creating the model.</param>
 /// <param name="attributes">List of the attributes assigned to this model.</param>
 /// <param name="sourceFiles">List of the fully qualified paths to the source code files this member is defined in.</param>
 /// <param name="hasDocumentation">Flag that determines if the model has XML documentation assigned to it.</param>
 /// <param name="documentation">The xml documentation assigned to the model.</param>
 /// <param name="lookupPath">The fully qualified model lookup path for this model.</param>
 /// <param name="name">The name of the model.</param>
 /// <param name="parentPath">THe fully qualified lookup path for the parent model to this one.</param>
 /// <param name="security">The security scope assigned to this model.</param>
 /// <param name="hasGet">Flag that determines if the property implements a getter.</param>
 /// <param name="hasSet">Flag that determines if the property implements a setter.</param>
 /// <param name="isAbstract">Flag that determines if the model is abstract.</param>
 /// <param name="isVirtual">Flag that determines if the model is virtual.</param>
 /// <param name="isSealed">Flag that determines if the model is sealed.</param>
 /// <param name="isOverride">Flag that determines if the model is overridden.</param>
 /// <param name="isStatic">Flag that determines if the model is static.</param>
 /// <param name="propertyType">The type the property supports.</param>
 /// <param name="getSecurity">The security access assigned to the getter.</param>
 protected CsProperty(bool isLoaded, bool hasErrors, bool loadedFromSource, SourceCodeType language,
                      IReadOnlyList <CsAttribute> attributes, IReadOnlyList <string> sourceFiles, bool hasDocumentation, string documentation,
                      string lookupPath, string name, string parentPath, CsSecurity security,
                      bool hasGet, bool hasSet, bool isAbstract, bool isVirtual, bool isSealed, bool isOverride, bool isStatic,
                      CsType propertyType, CsSecurity getSecurity, CsSecurity setSecurity,
                      string sourceDocument = null, ModelStore <ICsModel> modelStore = null, IReadOnlyList <ModelLoadException> modelErrors = null)
     : base(isLoaded, hasErrors, loadedFromSource, language, CsModelType.Property, attributes, sourceFiles,
            hasDocumentation, documentation, lookupPath, name, parentPath, security, CsMemberType.Property, sourceDocument, modelStore, modelErrors)
 {
     _hasGet       = hasGet;
     _hasSet       = hasSet;
     _isAbstract   = isAbstract;
     _isVirtual    = isVirtual;
     _isSealed     = isSealed;
     _isOverride   = isOverride;
     _isStatic     = isStatic;
     _propertyType = propertyType;
     _getSecurity  = getSecurity;
     _setSecurity  = setSecurity;
 }
示例#14
0
        /// <summary>
        /// Gets the security keyword for the C# language.
        /// </summary>
        /// <param name="source">The source security object to get the keyword from.</param>
        /// <returns>The name of the security keyword or null.</returns>
        public static string CSharpFormatKeyword(this CsSecurity source)
        {
            string result;

            switch (source)
            {
            case CsSecurity.Public:
                result = Security.Public;
                break;

            case CsSecurity.Protected:
                result = Security.Protected;
                break;

            case CsSecurity.Internal:
                result = Security.Internal;
                break;

            case CsSecurity.Private:
                result = Security.Private;
                break;

            case CsSecurity.ProtectedInternal:
                result = Security.ProtectedInternal;
                break;

            case CsSecurity.ProtectedOrInternal:
                result = Security.PrivateProtected;
                break;

            case CsSecurity.Unknown:
                result = null;
                break;

            default:
                result = null;
                break;
            }

            return(result);
        }
示例#15
0
        /// <summary>
        /// Generates the source code for a standard property definition. That uses a standard getter and setter.
        /// </summary>
        /// <param name="memberData">property data to be loaded.</param>
        /// <param name="manager">The namespace manager to use for namespace management with type declarations.</param>
        /// <param name="security">The security level to set the source event source code to. Will default to public if not provided.</param>
        /// <param name="getSecurity">Set the security level of the get accessor if defined for the property, will default to unknown</param>
        /// <param name="setSecurity">Set the security level of the set accessor if defined for the property, will default to unknown</param>
        /// <param name="useKeywords">Include the keywords currently assigned to the event model. Default value is to not include them.</param>
        /// <param name="includeAbstractKeyword">Optional parameter that determines if it will include the definition for the abstract keyword in the definition if it is defined. default is false.</param>
        /// <param name="requireStaticKeyword">Adds the static keyword to the signature, default is false.</param>
        /// <param name="requireSealedKeyword">Adds the sealed keyword to the signature, default is false.</param>
        /// <param name="requireAbstractKeyword">Adds the abstract keyword to the signature, default is false.</param>
        /// <param name="requireOverrideKeyword">Adds the override keyword to the signature, default is false.</param>
        /// <param name="requireVirtualKeyword">Adds the virtual keyword to the signature, default is false.</param>
        /// <returns>The fully formatted event source code or null if the member could not be implemented.</returns>
        public static string GenerateStandardPropertySourceCode(CsProperty memberData, NamespaceManager manager,
                                                                bool useKeywords           = false, bool includeAbstractKeyword         = false, bool requireStaticKeyword   = false,
                                                                bool requireSealedKeyword  = false, bool requireAbstractKeyword         = false, bool requireOverrideKeyword = false,
                                                                bool requireVirtualKeyword = false, CsSecurity security                 = CsSecurity.Public,
                                                                CsSecurity getSecurity     = CsSecurity.Unknown, CsSecurity setSecurity = CsSecurity.Unknown)
        {
            //Bounds checking to make sure all data that is needed is provided. If any required data is missing will return null.
            if (memberData == null)
            {
                return(null);
            }
            if (!memberData.IsLoaded)
            {
                return(null);
            }
            if (manager == null)
            {
                return(null);
            }

            //C# helper used to format output syntax.
            var formatter = new CodeFactory.SourceFormatter();

            //Using the formatter helper to generate a default event signature.
            string propertySyntax = memberData.CSharpFormatDefaultPropertySignature(manager, useKeywords,
                                                                                    includeAbstractKeyword, requireStaticKeyword, requireSealedKeyword, requireAbstractKeyword,
                                                                                    requireOverrideKeyword, requireVirtualKeyword, security, setSecurity, getSecurity);

            //If the property syntax was not created return.
            if (string.IsNullOrEmpty(propertySyntax))
            {
                return(null);
            }

            //If the member has document then will build the documentation.
            if (memberData.HasDocumentation)
            {
                //Using a documentation helper that will generate an enumerator that will output all XML documentation for the member.
                foreach (var documentation in memberData.CSharpFormatXmlDocumentationEnumerator())
                {
                    //Appending each xml document line to the being of the member definition.
                    formatter.AppendCodeLine(0, documentation);
                }
            }

            //The member has attributes assigned to it, append the attributes.
            if (memberData.HasAttributes)
            {
                //Using a documentation helper that will generate an enumerator that will output each attribute definition.
                foreach (var attributeSyntax in memberData.Attributes.CSharpFormatAttributeDeclarationEnumerator(manager))
                {
                    //Appending each attribute definition before the member definition.
                    formatter.AppendCodeLine(0, attributeSyntax);
                }
            }

            //Adding the event declaration
            formatter.AppendCodeBlock(0, propertySyntax);

            //Adding a extra line feed at the end of the declaration.
            formatter.AppendCodeLine(0);

            //The source formatter returning the final results.
            return(formatter.ReturnSource());
        }
        /// <summary>
        /// Gets the security keyword for the C# language.
        /// </summary>
        /// <param name="source">The source security object to get the keyword from.</param>
        /// <returns>The name of the security keyword or null.</returns>
        public static string FormatCSharpSyntax(this CsSecurity source)
        {
            var targetSecurity = (DotNetSecurity)(int)source;

            return(targetSecurity.FormatCSharpSyntax());
        }
        /// <summary>
        /// Extension method that generates a the full class declaration syntax based on the provided model.
        /// </summary>
        /// <example>
        /// Format with no generics [security] class [name] [:[base class*], [inherited interfaces*]]
        /// Format with generics [security] class [name] &lt;[generic parameters]&gt; [: [base class*], [inherited interfaces*]] [Generic Where Clauses*]
        /// </example>
        /// <param name="source">The source class model to format.</param>
        /// <param name="security">The security level the class should be implemented as.</param>
        /// <param name="manager">Namespace manager used to format type names.This is an optional parameter.</param>
        /// <param name="className">Optional parameter that allows you to specify a new name for the class.</param>
        /// <returns>The full class declaration or null if model data was missing.</returns>
        public static string CSharpFormatDeclaration(this CsClass source, CsSecurity security, NamespaceManager manager = null,
                                                     string className = null)
        {
            if (source == null)
            {
                return(null);
            }
            if (!source.IsLoaded)
            {
                return(null);
            }
            bool          hasBaseClass = false;
            var           name         = className ?? source.Name;
            StringBuilder classBuilder = new StringBuilder($"{security.CSharpFormatKeyword()} {Keywords.Class} {name}");

            if (source.IsGeneric)
            {
                classBuilder.Append(source.GenericParameters.CSharpFormatGenericParametersSignature(manager));
            }

            if (source.BaseClass != null)
            {
                if (source.BaseClass.Namespace.ToLowerInvariant() == "system" &
                    source.BaseClass.Name.ToLowerInvariant() == "object")
                {
                    hasBaseClass = false;
                }
                else
                {
                    hasBaseClass = true;
                }
            }

            if (hasBaseClass)
            {
                var baseName = source.BaseClass.CSharpFormatBaseTypeName(manager);
                if (string.IsNullOrEmpty(baseName))
                {
                    return(null);
                }
                classBuilder.Append($":{baseName}");
            }

            if (source.InheritedInterfaces.Any())
            {
                var interfaces = source.InheritedInterfaces;

                int totalCount       = interfaces.Count;
                int currentInterface = 0;

                classBuilder.Append(hasBaseClass ? ", " :":");

                foreach (var csInterface in interfaces)
                {
                    currentInterface++;

                    var interfaceType = csInterface.CSharpFormatInheritanceTypeName(manager);

                    if (interfaceType == null)
                    {
                        continue;
                    }

                    classBuilder.Append(interfaceType);
                    if (totalCount > currentInterface)
                    {
                        classBuilder.Append(", ");
                    }
                }
            }

            if (source.IsGeneric)
            {
                classBuilder.Append(" ");

                foreach (var sourceGenericParameter in source.GenericParameters)
                {
                    var whereClause = sourceGenericParameter.CSharpFormatGenericWhereClauseSignature(manager);
                    if (string.IsNullOrEmpty(whereClause))
                    {
                        continue;
                    }

                    classBuilder.Append($"{whereClause} ");
                }
            }

            return(classBuilder.ToString());
        }
示例#18
0
        /// <summary>
        /// Generates the source code for a standard raise event method.
        /// </summary>
        /// <param name="eventData">The target event model to generate the raise method for.</param>
        /// <param name="manager">The namespace manager to manage type naming.</param>
        /// <param name="eventName">the name of implemented event to raise.</param>
        /// <param name="security">The target security level to set the event to.</param>
        /// <param name="eventHandler">Optional field, that provides the name of the direct event handler field to raise.</param>
        /// <param name="methodName">Optional parameter of the custom name of the method. If not set will be On[eventName]</param>
        /// <returns></returns>
        public static string GenerateStandardRaiseEventMethod(CsEvent eventData, NamespaceManager manager,
                                                              string eventName, CsSecurity security, string eventHandler = null, string methodName = null)
        {
            //Bounds checking to make sure all data that is needed is provided. If any required data is missing will return null.
            if (eventData == null)
            {
                return(null);
            }
            if (!eventData.IsLoaded)
            {
                return(null);
            }
            if (manager == null)
            {
                return(null);
            }
            if (string.IsNullOrEmpty(eventName))
            {
                return(null);
            }
            if (security == CsSecurity.Unknown)
            {
                return(null);
            }

            var raiseMethod = eventData.EventHandlerDelegate.InvokeMethod;

            if (raiseMethod == null)
            {
                return(null);
            }
            if (!raiseMethod.IsLoaded)
            {
                return(null);
            }

            var parameters = raiseMethod.Parameters.CSharpFormatParametersSignature(manager, false);

            string raiseHandler = string.IsNullOrEmpty(eventHandler) ? eventName : eventHandler;

            StringBuilder parametersBuilder = new StringBuilder();
            int           parameterCount    = 0;

            foreach (var raiseMethodParameter in raiseMethod.Parameters)
            {
                parameterCount++;
                if (parameterCount > 1)
                {
                    parametersBuilder.Append(", ");
                }

                parametersBuilder.Append(raiseMethodParameter.Name);
            }


            //C# helper used to format output syntax.
            var formatter = new SourceFormatter();


            string raiseMethodName = string.IsNullOrEmpty(methodName) ? $"On{eventName}" : methodName;

            formatter.AppendCodeLine(0, "/// <summary>");
            formatter.AppendCodeLine(0, $"/// Raises the event {eventName} when there are subscribers to the event.");
            formatter.AppendCodeLine(0, "/// </summary>");
            formatter.AppendCodeLine(0, $"{security.CSharpFormatKeyword()} {Keywords.Void} {raiseMethodName}{parameters}");
            formatter.AppendCodeLine(0, "{");
            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(1, $"var raiseEvent = {raiseHandler};");
            formatter.AppendCodeLine(1, $"raiseEvent?.Invoke({parametersBuilder});");
            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(0, "}");
            formatter.AppendCodeLine(0);

            return(formatter.ReturnSource());
        }
示例#19
0
        /// <summary>
        /// Generates the source code for a standard field definition.
        /// </summary>
        /// <param name="memberData">Event data to be loaded.</param>
        /// <param name="manager">The namespace manager to use for namespace management with type declarations.</param>
        /// <param name="fieldSecurity">Parameter to set the target security for the field.</param>
        /// <param name="includeKeywords">Optional parameter that will include all keywords assigned to the field from the source model. This is true by default.</param>
        /// <param name="implementConstant">Determines if the filed is implemented as constant is should be returned as a constant, default is true.</param>
        /// <param name="requireStaticKeyword">Adds the static keyword to the signature, default is false.</param>
        /// <param name="requireReadOnlyKeyword">Adds the readonly keyword to the signature, default is false.</param>
        /// <param name="requireConstant">Implements the field as a constant, default is false.</param>
        /// <param name="requireConstantValue">The value to set the constant to if required.</param>
        /// <returns>The fully formatted event source code or null if the member could not be implemented.</returns>
        public static string GenerateStandardFieldSourceCode(CsField memberData, NamespaceManager manager,
                                                             CsSecurity fieldSecurity, bool includeKeywords = true, bool implementConstant = true,
                                                             bool requireStaticKeyword   = false, bool requireReadOnlyKeyword = false, bool requireConstant = false,
                                                             string requireConstantValue = null)
        {
            //Bounds checking to make sure all data that is needed is provided. If any required data is missing will return null.
            if (memberData == null)
            {
                return(null);
            }
            if (!memberData.IsLoaded)
            {
                return(null);
            }
            if (manager == null)
            {
                return(null);
            }

            //C# helper used to format output syntax.
            var formatter = new CodeFactory.SourceFormatter();

            //Using the formatter helper to generate a default event signature.
            string fieldSyntax = memberData.CSharpFormatFieldDeclaration(manager, includeKeywords, fieldSecurity,
                                                                         implementConstant, requireStaticKeyword, requireReadOnlyKeyword, requireConstant, requireConstantValue);

            //If the property syntax was not created return.
            if (string.IsNullOrEmpty(fieldSyntax))
            {
                return(null);
            }

            //If the member has document then will build the documentation.
            if (memberData.HasDocumentation)
            {
                //Using a documentation helper that will generate an enumerator that will output all XML documentation for the member.
                foreach (var documentation in memberData.CSharpFormatXmlDocumentationEnumerator())
                {
                    //Appending each xml document line to the being of the member definition.
                    formatter.AppendCodeLine(0, documentation);
                }
            }

            //The member has attributes assigned to it, append the attributes.
            if (memberData.HasAttributes)
            {
                //Using a documentation helper that will generate an enumerator that will output each attribute definition.
                foreach (var attributeSyntax in memberData.Attributes.CSharpFormatAttributeDeclarationEnumerator(manager))
                {
                    //Appending each attribute definition before the member definition.
                    formatter.AppendCodeLine(0, attributeSyntax);
                }
            }

            //Adding the event declaration
            formatter.AppendCodeBlock(0, fieldSyntax);

            //Adding a extra line feed at the end of the declaration.
            formatter.AppendCodeLine(0);

            //The source formatter returning the final results.
            return(formatter.ReturnSource());
        }
示例#20
0
        /// <summary>
        /// Generates the syntax definition of field in c# syntax. The default definition with all options turned off will return the filed signature and constants if defined and the default values.
        /// </summary>
        /// <example>
        /// With Keywords [Security] [Keywords] [FieldType] [Name];
        /// With Keywords and a constant [Security] [Keywords] [FieldType] [Name] = [Constant Value];
        /// Without Keywords [Security] [FieldType] [Name];
        /// Without Keywords and a constant [Security] [FieldType] [Name] = [Constant Value];
        /// </example>
        /// <param name="source">The source <see cref="CsField"/> model to generate.</param>
        /// <param name="manager">Namespace manager used to format type names.This is an optional parameter.</param>
        /// <param name="includeKeywords">Optional parameter that will include all keywords assigned to the field from the source model. This is true by default.</param>
        /// <param name="fieldSecurity">Optional parameter to set the target security for the field.</param>
        /// <param name="implementConstant">Determines if the filed is implemented as constant is should be returned as a constant, default is true.</param>
        /// <param name="requireStaticKeyword">Adds the static keyword to the signature, default is false.</param>
        /// <param name="requireReadOnlyKeyword">Adds the readonly keyword to the signature, default is false.</param>
        /// <param name="requireConstant">Implements the field as a constant, default is false.</param>
        /// <param name="requireConstantValue">The value to set the constant to if required.</param>
        /// <returns>Fully formatted field definition or null if the field data could not be generated.</returns>
        public static string CSharpFormatFieldDeclaration(this CsField source, NamespaceManager manager = null,
                                                          bool includeKeywords        = true, CsSecurity fieldSecurity     = CsSecurity.Unknown, bool implementConstant = true,
                                                          bool requireStaticKeyword   = false, bool requireReadOnlyKeyword = false, bool requireConstant                = false,
                                                          string requireConstantValue = null)
        {
            if (source == null)
            {
                return(null);
            }

            StringBuilder fieldFormatting = new StringBuilder();


            CsSecurity security = fieldSecurity == CsSecurity.Unknown ? source.Security : fieldSecurity;

            fieldFormatting.Append($"{security.CSharpFormatKeyword()} ");

            string constantValue = null;

            bool staticKeyword   = false;
            bool readOnlyKeyword = false;
            bool constantKeyword = false;

            if (includeKeywords)
            {
                if (source.IsStatic)
                {
                    staticKeyword = true;
                }
                if (source.IsReadOnly)
                {
                    readOnlyKeyword = true;
                }
            }

            if (source.IsConstant & implementConstant)
            {
                constantKeyword = true;
                constantValue   = source.ConstantValue;
            }

            if (!staticKeyword)
            {
                staticKeyword = requireStaticKeyword;
            }
            if (!readOnlyKeyword)
            {
                readOnlyKeyword = requireReadOnlyKeyword;
            }
            if (!constantKeyword)
            {
                constantKeyword = requireConstant;
            }

            if (constantKeyword & string.IsNullOrEmpty(constantValue))
            {
                constantValue = requireConstantValue;
            }


            if (staticKeyword)
            {
                fieldFormatting.Append($"{Keywords.Static} ");
            }
            if (readOnlyKeyword)
            {
                fieldFormatting.Append($"{Keywords.Readonly} ");
            }
            if (constantKeyword)
            {
                fieldFormatting.Append($"{Keywords.Constant} ");
            }

            fieldFormatting.Append($"{source.DataType.CSharpFormatTypeName(manager)} ");
            fieldFormatting.Append($"{source.Name}");
            if (constantKeyword)
            {
                fieldFormatting.Append($" = {source.DataType.CSharpFormatValueSyntax(constantValue)}");
            }
            fieldFormatting.Append(";");

            return(fieldFormatting.ToString());
        }
        /// <summary>
        /// Extension method that generates a the full interface declaration syntax based on the provided model.
        /// </summary>
        /// <example>
        /// Format with no generics [security] interface [name] [:[inherited interfaces*]]
        /// Format with generics [security] interface [name] &lt;[generic parameters]&gt; [: [base class*], [inherited interfaces*]] [Generic Where Clauses*]
        /// </example>
        /// <param name="source">The source interface model to format.</param>
        /// <param name="security">The security level the interface should be implemented as.</param>
        /// <param name="manager">Namespace manager used to format type names.This is an optional parameter.</param>
        /// <param name="interfaceName">Optional parameter that allows you to specify a new name for the interface.</param>
        /// <returns>The full interface declaration or null if model data was missing.</returns>
        public static string CSharpFormatDeclaration(this CsInterface source, CsSecurity security, NamespaceManager manager = null,
                                                     string interfaceName = null)
        {
            if (source == null)
            {
                return(null);
            }
            if (!source.IsLoaded)
            {
                return(null);
            }

            var           name             = interfaceName ?? source.Name;
            StringBuilder interfaceBuilder = new StringBuilder($"{security.CSharpFormatKeyword()} {Keywords.Interface} {name}");

            if (source.IsGeneric)
            {
                interfaceBuilder.Append(source.GenericParameters.CSharpFormatGenericParametersSignature(manager));
            }


            if (source.InheritedInterfaces.Any())
            {
                var interfaces = source.InheritedInterfaces;

                int totalCount       = interfaces.Count;
                int currentInterface = 0;

                interfaceBuilder.Append(": ");
                foreach (var csInterface in interfaces)
                {
                    currentInterface++;

                    var interfaceType = csInterface.CSharpFormatInheritanceTypeName(manager);

                    if (interfaceType == null)
                    {
                        continue;
                    }

                    interfaceBuilder.Append(interfaceType);
                    if (totalCount > currentInterface)
                    {
                        interfaceBuilder.Append(", ");
                    }
                }
            }

            if (source.IsGeneric)
            {
                interfaceBuilder.Append(" ");

                foreach (var sourceGenericParameter in source.GenericParameters)
                {
                    var whereClause = sourceGenericParameter.CSharpFormatGenericWhereClauseSignature(manager);
                    if (string.IsNullOrEmpty(whereClause))
                    {
                        continue;
                    }

                    interfaceBuilder.Append($"{whereClause} ");
                }
            }

            return(interfaceBuilder.ToString());
        }
示例#22
0
        /// <summary>
        /// Generates the source code for an event that supports add remove, does not generate the field definition.
        /// </summary>
        /// <param name="memberData">Event data to be loaded.</param>
        /// <param name="manager">The namespace manager to use for namespace management with type declarations.</param>
        /// <param name="fieldCamelCase">Flag that determines if the field will be set to camel case or left in proper case.</param>
        /// <param name="security">The security level to set the source event source code to. Will default to public if not provided.</param>
        /// <param name="useKeywords">Include the keywords currently assigned to the event model. Default value is to not include them.</param>
        /// <param name="includeAbstractKeyword">Optional parameter that determines if it will include the definition for the abstract keyword in the definition if it is defined. default is false.</param>
        /// <param name="requireStaticKeyword">Adds the static keyword to the signature, default is false.</param>
        /// <param name="requireSealedKeyword">Adds the sealed keyword to the signature, default is false.</param>
        /// <param name="requireAbstractKeyword">Adds the abstract keyword to the signature, default is false.</param>
        /// <param name="requireOverrideKeyword">Adds the override keyword to the signature, default is false.</param>
        /// <param name="requireVirtualKeyword">Adds the virtual keyword to the signature, default is false.</param>
        /// <param name="fieldNamePrefix">Optional parameter that determines the prefix to add to the field name that backs the event.</param>
        /// <param name="fieldSuffix">Parameter that determines what the suffix of the event name field is. Default is handler.</param>
        /// <returns>The fully formatted event source code or null if the member could not be implemented.</returns>
        public static string GenerateAddRemoveEvent(CsEvent memberData, NamespaceManager manager = null, CsSecurity security = CsSecurity.Public, string fieldNamePrefix = null, string fieldSuffix = "Handler", bool fieldCamelCase = true,
                                                    bool useKeywords            = false, bool includeAbstractKeyword = false, bool requireStaticKeyword  = false, bool requireSealedKeyword = false,
                                                    bool requireAbstractKeyword = false, bool requireOverrideKeyword = false, bool requireVirtualKeyword = false)
        {
            //Bounds checking to make sure all data that is needed is provided. If any required data is missing will return null.
            if (memberData == null)
            {
                return(null);
            }
            if (!memberData.IsLoaded)
            {
                return(null);
            }
            if (manager == null)
            {
                return(null);
            }

            //C# helper used to format output syntax.
            var formatter = new CodeFactory.SourceFormatter();

            //If the member has document then will build the documentation.
            if (memberData.HasDocumentation)
            {
                //Using a documentation helper that will generate an enumerator that will output all XML documentation for the member.
                foreach (var documentation in memberData.CSharpFormatXmlDocumentationEnumerator())
                {
                    //Appending each xml document line to the being of the member definition.
                    formatter.AppendCodeLine(0, documentation);
                }
            }

            //The member has attributes assigned to it, append the attributes.
            if (memberData.HasAttributes)
            {
                //Using a documentation helper that will generate an enumerator that will output each attribute definition.
                foreach (var attributeSyntax in memberData.Attributes.CSharpFormatAttributeDeclarationEnumerator(manager))
                {
                    //Appending each attribute definition before the member definition.
                    formatter.AppendCodeLine(0, attributeSyntax);
                }
            }


            var eventSignature = memberData.CSharpFormatEventSignature(manager, true, security, useKeywords,
                                                                       includeAbstractKeyword, requireStaticKeyword, requireSealedKeyword, requireAbstractKeyword,
                                                                       requireOverrideKeyword, requireVirtualKeyword);

            if (string.IsNullOrEmpty(eventSignature))
            {
                return(null);
            }

            bool hasFieldPrefix = fieldNamePrefix != null;

            bool hasFieldSuffix = fieldSuffix != null;

            StringBuilder fieldNameBuilder = new StringBuilder();

            if (hasFieldPrefix)
            {
                fieldNameBuilder.Append(fieldNamePrefix);
            }

            var fieldNameData = hasFieldSuffix ? $"{memberData.Name}{fieldSuffix}": memberData.Name;

            fieldNameBuilder.Append(fieldCamelCase ? fieldNameData.ConvertToCamelCase() : fieldNameData);

            var fieldName = fieldNameBuilder.ToString();

            //Adding the event declaration
            formatter.AppendCodeLine(0, eventSignature);

            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(0, "{");
            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(1, "add");
            formatter.AppendCodeLine(1, "{");
            formatter.AppendCodeLine(2, $"{fieldName} += value;");
            formatter.AppendCodeLine(1, "}");
            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(1, "remove");
            formatter.AppendCodeLine(1, "{");
            formatter.AppendCodeLine(2, $"if({fieldName} !=null) {fieldName} -= value;");
            formatter.AppendCodeLine(1, "}");
            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(0, "}");
            formatter.AppendCodeLine(0);

            //The source formatter returning the final results.
            return(formatter.ReturnSource());
        }
示例#23
0
        /// <summary>
        /// Generates the source code for a method that supports a standard type catch block, and bounds checking as well as the ability to support Microsoft extensions logging.
        /// </summary>
        /// <param name="memberData">Method data to be generated.</param>
        /// <param name="manager">The namespace manager to use for namespace management with type declarations.</param>
        /// <param name="includeBoundsCheck">Flag that determines if string and nullable type bounds checking should be included in a method implementation.</param>
        /// <param name="supportAsyncKeyword">Flag that determines if methods should be implemented with the async keyword when supported by the method implementation.</param>
        /// <param name="security">The security level to add to the generated source code. Will default to public if not provided</param>
        /// <param name="includeLogging">Determines if logging will be added to the method. This will be set to a default of true.</param>
        /// <param name="loggerName">Sets the name of the logger to be used in the method. Will default to _logger if not provided.</param>
        /// <param name="includeKeywords">Determines if the models current keywords should be added to the source code, default if false.</param>
        /// <param name="includeAbstraction">If keywords are to be included, determines if the abstract keyword should be used or ignored, default is false.</param>
        /// <param name="requireStaticKeyword">Adds the static keyword to the signature, default is false.</param>
        /// <param name="requireSealedKeyword">Adds the sealed keyword to the signature, default is false.</param>
        /// <param name="requireAbstractKeyword">Adds the abstract keyword to the signature, default is false.</param>
        /// <param name="requireOverrideKeyword">Adds the override keyword to the signature, default is false.</param>
        /// <param name="requireVirtualKeyword">Adds the virtual keyword to the signature, default is false.</param>
        /// <returns>The fully formatted method source code or null if the member could not be implemented.</returns>
        public static string GenerateStandardMethodSourceCode(CsMethod memberData, NamespaceManager manager, bool includeBoundsCheck, bool supportAsyncKeyword,
                                                              CsSecurity security         = CsSecurity.Public, bool includeLogging = true, string loggerName          = null, bool includeKeywords = false,
                                                              bool includeAbstraction     = false, bool requireStaticKeyword       = false, bool requireSealedKeyword = false, bool requireAbstractKeyword = false,
                                                              bool requireOverrideKeyword = false, bool requireVirtualKeyword      = false)
        {
            //Bounds checking to make sure all data that is needed is provided. If any required data is missing will return null.
            if (memberData == null)
            {
                return(null);
            }
            if (!memberData.IsLoaded)
            {
                return(null);
            }
            if (manager == null)
            {
                return(null);
            }

            string logger = null;

            if (includeLogging)
            {
                logger = string.IsNullOrEmpty(loggerName) ? NetConstants.DefaultClassLoggerName : loggerName;
            }

            //C# helper used to format output syntax.
            var formatter = new CodeFactory.SourceFormatter();

            //Using the formatter helper to generate a method signature.
            string methodSyntax = supportAsyncKeyword
                ? memberData.CSharpFormatMethodSignature(manager, true, true, security, includeKeywords,
                                                         includeAbstraction, requireStaticKeyword, requireSealedKeyword, requireAbstractKeyword,
                                                         requireOverrideKeyword, requireVirtualKeyword)
                : memberData.CSharpFormatMethodSignature(manager, false, true, security, includeKeywords,
                                                         includeAbstraction, requireStaticKeyword, requireSealedKeyword,
                                                         requireAbstractKeyword, requireOverrideKeyword, requireVirtualKeyword);

            //If the method syntax was not created return.
            if (string.IsNullOrEmpty(methodSyntax))
            {
                return(null);
            }

            //If the member has document then will build the documentation.
            if (memberData.HasDocumentation)
            {
                //Using a documentation helper that will generate an enumerator that will output all XML documentation for the member.
                foreach (var documentation in memberData.CSharpFormatXmlDocumentationEnumerator())
                {
                    //Appending each xml document line to the being of the member definition.
                    formatter.AppendCodeLine(0, documentation);
                }
            }

            //The member has attributes assigned to it, append the attributes.
            if (memberData.HasAttributes)
            {
                //Using a documentation helper that will generate an enumerator that will output each attribute definition.
                foreach (var attributeSyntax in memberData.Attributes.CSharpFormatAttributeDeclarationEnumerator(manager))
                {
                    //Appending each attribute definition before the member definition.
                    formatter.AppendCodeLine(0, attributeSyntax);
                }
            }

            //Adding the method declaration
            formatter.AppendCodeLine(0, methodSyntax);
            formatter.AppendCodeLine(0, "{");

            //Adding enter logging if logging is enabled.
            if (includeLogging)
            {
                formatter.AppendCodeLine(1, $"{logger}.LogInformation(\"Entering\");");
                formatter.AppendCodeLine(0);
            }

            //Processing each parameter for bounds checking if bounds checking is enabled.
            if (includeBoundsCheck & memberData.HasParameters)
            {
                foreach (ICsParameter paramData in memberData.Parameters)
                {
                    //If the parameter has a default value then continue will not bounds check parameters with a default value.
                    if (paramData.HasDefaultValue)
                    {
                        continue;
                    }

                    //If the parameter is a string type add the following bounds check
                    if (paramData.ParameterType.WellKnownType == CsKnownLanguageType.String)
                    {
                        //Adding an if check
                        formatter.AppendCodeLine(1, $"if(string.IsNullOrEmpty({paramData.Name}))");
                        formatter.AppendCodeLine(1, "{");

                        //If logging was included add error logging and exit logging
                        if (includeLogging)
                        {
                            formatter.AppendCodeLine(2,
                                                     $"{logger}.LogError($\"The parameter {{nameof({paramData.Name})}} was not provided. Will raise an argument exception\");");
                            formatter.AppendCodeLine(2, $"{logger}.LogInformation(\"Exiting\");");
                        }
                        //Adding a throw of an argument null exception
                        formatter.AppendCodeLine(2, $"throw new ArgumentNullException(nameof({paramData.Name}));");
                        formatter.AppendCodeLine(1, "}");
                        formatter.AppendCodeLine(0);
                    }

                    // Check to is if the parameter is not a value type or a well know type if not then go ahead and perform a null bounds check.
                    if (!paramData.ParameterType.IsValueType & !paramData.ParameterType.IsWellKnownType)
                    {
                        //Adding an if check
                        formatter.AppendCodeLine(1, $"if({paramData.Name} == null)");
                        formatter.AppendCodeLine(1, "{");

                        //If logging was included add error logging and exit logging
                        if (includeLogging)
                        {
                            formatter.AppendCodeLine(2,
                                                     $"{logger}.LogError($\"The parameter {{nameof({paramData.Name})}} was not provided. Will raise an argument exception\");");
                            formatter.AppendCodeLine(2, $"{logger}.LogInformation(\"Exiting\");");
                        }

                        //Adding a throw of an argument null exception
                        formatter.AppendCodeLine(2, $"throw new ArgumentNullException(nameof({paramData.Name}));");
                        formatter.AppendCodeLine(1, "}");
                        formatter.AppendCodeLine(0);
                    }
                }
            }

            //Formatting standard try block for method
            formatter.AppendCodeLine(1, "try");
            formatter.AppendCodeLine(1, "{");
            formatter.AppendCodeLine(2, "//TODO: add execution logic here");
            formatter.AppendCodeLine(1, "}");

            //Formatting standard catch block for method
            formatter.AppendCodeLine(1, "catch (Exception unhandledException)");
            formatter.AppendCodeLine(1, "{");

            //If logging is supported capture the exception and log it as an error. Notify that an error has occured and log it . then log exiting the method and throw a scrubbed exception.
            if (includeLogging)
            {
                formatter.AppendCodeLine(2, $"{logger}.LogError(unhandledException, \"An unhandled exception occured, see the exception for details.Will throw a UnhandledLogicException\");");
                formatter.AppendCodeLine(2, $"{logger}.LogInformation(\"Exiting\");");
                formatter.AppendCodeLine(2, "throw new Exception(\"An unhandled error occured, check the logs for details.\");");
            }
            else
            {
                formatter.AppendCodeLine(2, "//TODO: Add exception handling for unhandledException");
            }


            formatter.AppendCodeLine(1, "}");
            formatter.AppendCodeLine(0);

            //If logging add a logging exit statement.
            if (includeLogging)
            {
                formatter.AppendCodeLine(1, $"{logger}.LogInformation(\"Exiting\");");
            }

            //Add an exception for not implemented until the developer updates the logic.
            formatter.AppendCodeLine(1, "throw new NotImplementedException();");
            formatter.AppendCodeLine(0);

            //if the return type is not void then add a to do message for the developer to add return logic.
            if (!memberData.IsVoid)
            {
                formatter.AppendCodeLine(1, "//TODO: add return logic here");
            }
            formatter.AppendCodeLine(0, "}");
            formatter.AppendCodeLine(0);

            //Returning the fully formatted method.
            return(formatter.ReturnSource());
        }
        /// <summary>
        /// Generates the initial definition portion of a property.
        /// </summary>
        /// <example>
        /// Format with Keywords [Security] [Keywords*] [ReturnType] [PropertyName] = public static string FirstName
        /// Format without Keywords [Security] [ReturnType] [PropertyName] = public string FirstName
        /// </example>
        /// <param name="manager">Namespace manager used to format type names.</param>
        /// <param name="source">The source property to use for formatting.</param>
        /// <param name="includeSecurity">Optional flag that determines if the security scope will be applied to the property definition. Default is true.</param>
        /// <param name="includeKeyWords">Optional flag that determines if keywords assigned to the property should be included in the signature. Default is false.</param>
        /// <param name="includeAbstractKeyword">Will include the definition for the abstract keyword in the definition if it is defined. default is false.</param>
        /// <param name="requireStaticKeyword">Adds the static keyword to the signature, default is false.</param>
        /// <param name="requireSealedKeyword">Adds the sealed keyword to the signature, default is false.</param>
        /// <param name="requireAbstractKeyword">Adds the abstract keyword to the signature, default is false.</param>
        /// <param name="requireOverrideKeyword">Adds the override keyword to the signature, default is false.</param>
        /// <param name="requireVirtualKeyword">Adds the virtual keyword to the signature, default is false.</param>
        /// <param name="propertySecurity">Optional parameter to override the models security and set your own security.</param>
        /// <returns>The formatted signature or null if the model data was not loaded.</returns>
        public static string CSharpFormatPropertyDeclaration(this CsProperty source, NamespaceManager manager = null, bool includeSecurity = true, bool includeKeyWords = false,
                                                             bool includeAbstractKeyword = false, bool requireStaticKeyword   = false, bool requireSealedKeyword        = false, bool requireAbstractKeyword = false, bool requireOverrideKeyword = false,
                                                             bool requireVirtualKeyword  = false, CsSecurity propertySecurity = CsSecurity.Unknown)
        {
            if (!source.IsLoaded)
            {
                return(null);
            }

            StringBuilder propertyBuilder = new StringBuilder();

            if (includeKeyWords & source.IsSealed)
            {
                propertyBuilder.Append($"{Keywords.Sealed} ");
            }

            if (includeSecurity)
            {
                propertyBuilder.Append(propertySecurity == CsSecurity.Unknown
                    ? source.Security.CSharpFormatKeyword()
                    : propertySecurity.CSharpFormatKeyword());
            }

            bool staticKeyword   = false;
            bool sealedKeyword   = false;
            bool abstractKeyword = false;
            bool overrideKeyword = false;
            bool virtualKeyword  = false;

            if (includeKeyWords)
            {
                if (source.IsStatic)
                {
                    staticKeyword = true;
                }
                if (source.IsSealed)
                {
                    sealedKeyword = true;
                }
                if (includeAbstractKeyword & source.IsAbstract)
                {
                    abstractKeyword = true;
                }
                if (source.IsOverride)
                {
                    overrideKeyword = true;
                }
                if (source.IsVirtual)
                {
                    virtualKeyword = true;
                }
            }

            if (!staticKeyword)
            {
                staticKeyword = requireStaticKeyword;
            }
            if (!sealedKeyword)
            {
                sealedKeyword = requireSealedKeyword;
            }
            if (!abstractKeyword)
            {
                abstractKeyword = requireAbstractKeyword;
            }
            if (!overrideKeyword)
            {
                overrideKeyword = requireOverrideKeyword;
            }
            if (!virtualKeyword)
            {
                virtualKeyword = requireVirtualKeyword;
            }

            if (staticKeyword)
            {
                propertyBuilder.Append($"{Keywords.Static} ");
            }
            if (sealedKeyword)
            {
                propertyBuilder.Append($"{Keywords.Sealed} ");
            }
            if (abstractKeyword)
            {
                propertyBuilder.Append($"{Keywords.Abstract} ");
            }
            if (overrideKeyword)
            {
                propertyBuilder.Append($"{Keywords.Override} ");
            }
            if (virtualKeyword)
            {
                propertyBuilder.Append($"{Keywords.Virtual} ");
            }


            propertyBuilder.Append($" {source.PropertyType.CSharpFormatTypeName(manager)}");
            propertyBuilder.Append($" {source.Name}");

            return(propertyBuilder.ToString());
        }
示例#25
0
        /// <summary>
        /// Generates a C# method signature from model data. This provides a fully customizable method for generating the signature.
        /// </summary>
        /// <param name="source">The source method data to generate the signature from.</param>
        /// <param name="includeAsyncKeyword">Include the async keyword if the return type is Task</param>
        /// <param name="includeSecurity">Includes the security scope which was defined in the model.</param>
        /// <param name="methodSecurity">Optional parameter that allows you to set the security scope for the method.</param>
        /// <param name="includeKeywords">Includes all keywords assigned to the source model.</param>
        /// <param name="includeAbstractKeyword">Will include the definition for the abstract keyword in the definition if it is defined. default is false.</param>
        /// <param name="manager">Optional parameter that contains all the using statements from the source code, when used will replace namespaces on type definition in code.</param>
        /// <returns>Fully formatted method deceleration or null if the method data was missing.</returns>
        public static string CSharpFormatMethodSignature(this CsMethod source, NamespaceManager manager = null, bool includeAsyncKeyword = true,
                                                         bool includeSecurity = true, CsSecurity methodSecurity = CsSecurity.Unknown, bool includeKeywords = true, bool includeAbstractKeyword = false)
        {
            if (source == null)
            {
                return(null);
            }


            StringBuilder methodFormatting = new StringBuilder();

            if (includeSecurity)
            {
                var formattedSecurity = methodSecurity == CsSecurity.Unknown
                    ? source.Security.CSharpFormatKeyword()
                    : methodSecurity.CSharpFormatKeyword();
                methodFormatting.Append($"{formattedSecurity} ");
            }

            if (includeKeywords)
            {
                if (source.IsStatic)
                {
                    methodFormatting.Append($"{Keywords.Static} ");
                }
                if (source.IsSealed)
                {
                    methodFormatting.Append($"{Keywords.Sealed} ");
                }
                if (includeAbstractKeyword & source.IsAbstract)
                {
                    methodFormatting.Append($"{Keywords.Abstract} ");
                }
                if (source.IsOverride)
                {
                    methodFormatting.Append($"{Keywords.Override} ");
                }
                if (source.IsVirtual)
                {
                    methodFormatting.Append($"{Keywords.Virtual} ");
                }
            }

            if (includeAsyncKeyword)
            {
                //Bug fix for issue #14
                if (source.ReturnType != null)
                {
                    if (source.ReturnType.Name == "Task" & source.ReturnType.Namespace == "System.Threading.Tasks")
                    {
                        methodFormatting.Append("async ");
                    }
                }
            }

            methodFormatting.Append(source.IsVoid ? $"{Keywords.Void} {source.Name}" : $"{source.ReturnType.CSharpFormatTypeName(manager)} {source.Name}");
            if (source.IsGeneric)
            {
                methodFormatting.Append($"{source.GenericParameters.CSharpFormatGenericParametersSignature(manager)}");
            }

            methodFormatting.Append(source.HasParameters
                ? source.Parameters.CSharpFormatParametersSignature(manager)
                : $"{Symbols.ParametersDefinitionStart}{Symbols.ParametersDefinitionEnd}");

            if (!source.IsGeneric)
            {
                return(methodFormatting.ToString());
            }

            foreach (var sourceGenericParameter in source.GenericParameters)
            {
                var whereClause = sourceGenericParameter.CSharpFormatGenericWhereClauseSignature(manager);

                if (!string.IsNullOrEmpty(whereClause))
                {
                    methodFormatting.Append($" {whereClause}");
                }
            }

            return(methodFormatting.ToString());
        }
示例#26
0
        /// <summary>
        /// Generates the initial definition portion of a property.
        /// </summary>
        /// <example>
        /// Format with Keywords [Security] [Keywords*] [ReturnType] [PropertyName] = public static string FirstName
        /// Format without Keywords [Security] [ReturnType] [PropertyName] = public string FirstName
        /// </example>
        /// <param name="manager">Namespace manager used to format type names.</param>
        /// <param name="source">The source property to use for formatting.</param>
        /// <param name="includeSecurity">Optional flag that determines if the security scope will be applied to the property definition. Default is true.</param>
        /// <param name="includeKeyWords">Optional flag that determines if keywords assigned to the property should be included in the signature. Default is false.</param>
        /// <param name="includeAbstractKeyword">Will include the definition for the abstract keyword in the definition if it is defined. default is false.</param>
        /// <param name="propertySecurity">Optional parameter to override the models security and set your own security.</param>
        /// <returns>The formatted signature or null if the model data was not loaded.</returns>
        public static string CSharpFormatPropertyDeclaration(this CsProperty source, NamespaceManager manager = null, bool includeSecurity = true, bool includeKeyWords = false,
                                                             bool includeAbstractKeyword = false, CsSecurity propertySecurity = CsSecurity.Unknown)
        {
            if (!source.IsLoaded)
            {
                return(null);
            }

            StringBuilder propertyBuilder = new StringBuilder();

            if (includeKeyWords & source.IsSealed)
            {
                propertyBuilder.Append($"{Keywords.Sealed} ");
            }

            if (includeSecurity)
            {
                propertyBuilder.Append(propertySecurity == CsSecurity.Unknown
                    ? source.Security.CSharpFormatKeyword()
                    : propertySecurity.CSharpFormatKeyword());
            }

            if (includeKeyWords)
            {
                if (source.IsStatic)
                {
                    propertyBuilder.Append($" {Keywords.Static}");
                }
                if (source.IsOverride)
                {
                    propertyBuilder.Append($" {Keywords.Override}");
                }
                if (source.IsAbstract & !source.IsOverride & includeAbstractKeyword)
                {
                    propertyBuilder.Append($" {Keywords.Abstract}");
                }
                if (source.IsVirtual & !source.IsOverride)
                {
                    propertyBuilder.Append($" {Keywords.Virtual}");
                }
            }

            propertyBuilder.Append($" {source.PropertyType.CSharpFormatTypeName(manager)}");
            propertyBuilder.Append($" {source.Name}");

            return(propertyBuilder.ToString());
        }
示例#27
0
        /// <summary>
        /// Generates the signature of an event in c# syntax.
        /// </summary>
        /// <example>
        /// With Keywords [security] [keywords] event [event handler type] [name]
        /// Without Keywords [security] [keywords] event [event handler type] [name]
        /// </example>
        /// <param name="source">The source <see cref="CsEvent"/> model to generate.</param>
        /// <param name="manager">Namespace manager used to format type names.This is an optional parameter.</param>
        /// <param name="includeSecurity">Includes the security scope which was defined in the model.</param>
        /// <param name="eventSecurity">Optional parameter that sets the target security scope for the event.</param>
        /// <param name="includeKeywords">Optional parameter that determines if it will include all keywords assigned to the source model, default is false.</param>
        /// <param name="includeAbstractKeyword">Optional parameter that determines if it will include the definition for the abstract keyword in the definition if it is defined. default is false.</param>
        /// <param name="requireStaticKeyword">Adds the static keyword to the signature, default is false.</param>
        /// <param name="requireSealedKeyword">Adds the sealed keyword to the signature, default is false.</param>
        /// <param name="requireAbstractKeyword">Adds the abstract keyword to the signature, default is false.</param>
        /// <param name="requireOverrideKeyword">Adds the override keyword to the signature, default is false.</param>
        /// <param name="requireVirtualKeyword">Adds the virtual keyword to the signature, default is false.</param>
        /// <returns>Fully formatted event definition or null if the event data could not be generated.</returns>
        public static string CSharpFormatEventSignature(this CsEvent source, NamespaceManager manager = null, bool includeSecurity = true, CsSecurity eventSecurity = CsSecurity.Unknown,
                                                        bool includeKeywords       = true, bool includeAbstractKeyword = false, bool requireStaticKeyword = false, bool requireSealedKeyword = false, bool requireAbstractKeyword = false, bool requireOverrideKeyword = false,
                                                        bool requireVirtualKeyword = false)
        {
            if (source == null)
            {
                return(null);
            }
            if (!source.IsLoaded)
            {
                return(null);
            }

            StringBuilder eventFormatting = new StringBuilder();

            CsSecurity security = eventSecurity == CsSecurity.Unknown
                ? security = source.Security
                : security = eventSecurity;

            if (includeKeywords & source.IsSealed)
            {
                eventFormatting.Append($"{Keywords.Sealed} ");
            }

            if (includeSecurity)
            {
                eventFormatting.Append($"{security.CSharpFormatKeyword()} ");
            }

            bool staticKeyword   = false;
            bool sealedKeyword   = false;
            bool abstractKeyword = false;
            bool overrideKeyword = false;
            bool virtualKeyword  = false;

            if (includeKeywords)
            {
                if (source.IsStatic)
                {
                    staticKeyword = true;
                }
                if (source.IsSealed)
                {
                    sealedKeyword = true;
                }
                if (includeAbstractKeyword & source.IsAbstract)
                {
                    abstractKeyword = true;
                }
                if (source.IsOverride)
                {
                    overrideKeyword = true;
                }
                if (source.IsVirtual)
                {
                    virtualKeyword = true;
                }
            }

            if (!staticKeyword)
            {
                staticKeyword = requireStaticKeyword;
            }
            if (!sealedKeyword)
            {
                sealedKeyword = requireSealedKeyword;
            }
            if (!abstractKeyword)
            {
                abstractKeyword = requireAbstractKeyword;
            }
            if (!overrideKeyword)
            {
                overrideKeyword = requireOverrideKeyword;
            }
            if (!virtualKeyword)
            {
                virtualKeyword = requireVirtualKeyword;
            }

            if (staticKeyword)
            {
                eventFormatting.Append($"{Keywords.Static} ");
            }
            if (sealedKeyword)
            {
                eventFormatting.Append($"{Keywords.Sealed} ");
            }
            if (abstractKeyword)
            {
                eventFormatting.Append($"{Keywords.Abstract} ");
            }
            if (overrideKeyword)
            {
                eventFormatting.Append($"{Keywords.Override} ");
            }
            if (virtualKeyword)
            {
                eventFormatting.Append($"{Keywords.Virtual} ");
            }

            eventFormatting.Append($"{Keywords.Event} {source.EventType.CSharpFormatTypeName(manager)} {source.Name}");

            return(eventFormatting.ToString());
        }