protected override void AddTemplateParameters(IDictionary <string, object> templateParameters)
        {
            base.AddTemplateParameters(templateParameters);
            CodeType      codeType = base.Model.ModelType.CodeType;
            ModelMetadata codeModelModelMetadatum = new CodeModelModelMetadata(codeType);

            if ((int)codeModelModelMetadatum.PrimaryKeys.Length == 0)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "The entity type '{0}' has no key defined. Define a key for this entity type.", codeType.Name));
            }
            templateParameters.Add("ModelMetadata", codeModelModelMetadatum);
            List <CodeType> codeTypes = new List <CodeType>()
            {
                codeType
            };

            templateParameters.Add("RequiredNamespaces", base.GetRequiredNamespaces(codeTypes));
            templateParameters.Add("ModelTypeNamespace", (codeType.Namespace != null ? codeType.Namespace.FullName : string.Empty));
            templateParameters.Add("ModelTypeName", codeType.Name);
            templateParameters.Add("UseAsync", base.Model.IsAsyncSelected);
            IEntityFrameworkService service = base.Context.ServiceProvider.GetService <IEntityFrameworkService>();
            string pluralizedWord           = service.GetPluralizedWord(codeType.Name, CultureInfo.InvariantCulture);

            templateParameters.Add("EntitySetName", pluralizedWord);
            CodeDomProvider codeDomProvider = ValidationUtil.GenerateCodeDomProvider(ProjectExtensions.GetCodeLanguage(base.Model.ActiveProject));
            string          str             = codeDomProvider.CreateEscapedIdentifier(codeType.Name.ToLowerInvariantFirstChar());
            string          str1            = codeDomProvider.CreateEscapedIdentifier(pluralizedWord.ToLowerInvariantFirstChar());

            templateParameters.Add("ModelVariable", str);
            templateParameters.Add("EntitySetVariable", str1);
            templateParameters.Add("ODataModificationMessage", "The WebApiConfig class may require additional changes to add a route for this controller. Merge these statements into the Register method of the WebApiConfig class as applicable. Note that OData URLs are case sensitive.");

            templateParameters.Add("IsLegacyOdataVersion", base.Framework.IsODataLegacy(base.Context));
        }
예제 #2
0
        /// <summary>
        /// Converts to a valid identifier, or throws an exception if
        /// that is not possible
        /// </summary>
        /// <param name="value">The value to convert</param>
        /// <returns>A valid C# identifier</returns>
        /// <exception cref="ArgumentException">The value cannot be converted to a valid identifier</exception>
        public static string ConvertToValidIdentifier(string value)
        {
            string identifier = codeDomProvider.CreateEscapedIdentifier((string)value);

            if (!codeDomProvider.IsValidIdentifier(identifier))
            {
                throw new ArgumentException(Properties.Resources.InvalidIdentifiedArgumentException, "value");
            }

            return(identifier);
        }
예제 #3
0
        protected virtual IDictionary <string, object> AddTemplateParameters(
            CodeType dbContextType,
            ModelMetadata modelMetadata)
        {
            if (dbContextType == null)
            {
                throw new ArgumentNullException("dbContextType");
            }

            if (modelMetadata == null)
            {
                throw new ArgumentNullException("modelMetadata");
            }

            if (String.IsNullOrEmpty(Model.ControllerName))
            {
                throw new InvalidOperationException(Resources.InvalidControllerName);
            }

            IDictionary <string, object> templateParameters = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);
            CodeType modelType = Model.ModelType.CodeType;

            templateParameters.Add("ModelMetadata", modelMetadata);

            string modelTypeNamespace = modelType.Namespace != null ? modelType.Namespace.FullName : String.Empty;

            templateParameters.Add("ModelTypeNamespace", modelTypeNamespace);

            HashSet <string> requiredNamespaces = GetRequiredNamespaces(new List <CodeType>()
            {
                modelType, dbContextType
            });

            templateParameters.Add("RequiredNamespaces", requiredNamespaces);
            templateParameters.Add("ModelTypeName", modelType.Name);
            templateParameters.Add("ContextTypeName", dbContextType.Name);
            templateParameters.Add("UseAsync", Model.IsAsyncSelected);

            CodeDomProvider provider      = ValidationUtil.GenerateCodeDomProvider(Model.ActiveProject.GetCodeLanguage());
            string          modelVariable = provider.CreateEscapedIdentifier(Model.ModelType.ShortTypeName.ToLowerInvariantFirstChar());

            templateParameters.Add("ModelVariable", modelVariable);

            templateParameters.Add("EntitySetVariable", modelMetadata.EntitySetName.ToLowerInvariantFirstChar());

            // Overposting protection is only for MVC - and only when the model doesn't already have [Bind]
            if (Model.IsViewGenerationSupported)
            {
                bool isOverpostingProtectionRequired = OverpostingProtection.IsOverpostingProtectionRequired(modelType);
                templateParameters.Add("IsOverpostingProtectionRequired", isOverpostingProtectionRequired);

                if (isOverpostingProtectionRequired)
                {
                    templateParameters.Add("OverpostingWarningMessage", OverpostingProtection.WarningMessage);
                    templateParameters.Add("BindAttributeIncludeText", OverpostingProtection.GetBindAttributeIncludeText(modelMetadata));
                }
            }

            return(templateParameters);
        }
예제 #4
0
        //UNDONE: switch to using CodeDom csharp.GetTypeOutput after they fix the VSWhidbey bug #202199	CodeDom: does not esacpes full names properly

        /*
         * internal static string GetTypeName(string name, CodeDomProvider codeProvider) {
         *  return codeProvider.GetTypeOutput(new CodeTypeReference(name));
         * }
         */

        private static void EscapeKeywords(string identifier, CodeDomProvider codeProvider, StringBuilder sb)
        {
            if (identifier == null || identifier.Length == 0)
            {
                return;
            }
            string originalIdentifier = identifier;
            int    arrayCount         = 0;

            while (identifier.EndsWith("[]", StringComparison.Ordinal))
            {
                arrayCount++;
                identifier = identifier.Substring(0, identifier.Length - 2);
            }
            if (identifier.Length > 0)
            {
                CheckValidIdentifier(identifier);
                identifier = codeProvider.CreateEscapedIdentifier(identifier);
                sb.Append(identifier);
            }
            for (int i = 0; i < arrayCount; i++)
            {
                sb.Append("[]");
            }
        }
        public static string VerifyConfigKey(string key, CodeDomProvider provider)
        {
            if (String.IsNullOrEmpty(key))
            {
                return(key);
            }
            var sb = new StringBuilder();

            foreach (char c in key)
            {
                if (sb.Length == 0)
                {
                    if (Char.IsLetter(c) || c == '_')
                    {
                        sb.Append(c);
                    }
                }
                else
                {
                    if (Char.IsLetter(c) || Char.IsNumber(c) || c == '_')
                    {
                        sb.Append(c);
                    }
                }
            }
            return(provider.CreateEscapedIdentifier(sb.ToString()));
        }
예제 #6
0
        internal static ValidationError ValidateNameProperty(string propName, IServiceProvider context, string identifier)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            ValidationError error = null;

            if (identifier == null || identifier.Length == 0)
            {
                error = new ValidationError(SR.GetString(SR.Error_PropertyNotSet, propName), ErrorNumbers.Error_PropertyNotSet);
            }
            else
            {
                SupportedLanguages language = CompilerHelpers.GetSupportedLanguage(context);
                CodeDomProvider    provider = CompilerHelpers.GetCodeDomProvider(language);

                if (language == SupportedLanguages.CSharp && identifier.StartsWith("@", StringComparison.Ordinal) ||
                    language == SupportedLanguages.VB && identifier.StartsWith("[", StringComparison.Ordinal) && identifier.EndsWith("]", StringComparison.Ordinal) ||
                    !provider.IsValidIdentifier(provider.CreateEscapedIdentifier(identifier)))
                {
                    error = new ValidationError(SR.GetString(SR.Error_InvalidIdentifier, propName, SR.GetString(SR.Error_InvalidLanguageIdentifier, identifier)), ErrorNumbers.Error_InvalidIdentifier);
                }
            }
            if (error != null)
            {
                error.PropertyName = propName;
            }
            return(error);
        }
        private static string [] GetStaticClassDefinitionPath(CodeDomProvider codeDomProvider, CodeTypeDeclaration type)
        {
            var isStatic = type.Attributes.HasBitMask(MemberAttributes.Static);
            var isClass  = type.IsClass && (type.TypeAttributes & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Class;

            if (!isStatic || !isClass)
            {
                return(null);
            }

            RemoveConstructors(type);

            var path = new List <string> ( );

            switch (type.TypeAttributes & TypeAttributes.VisibilityMask)
            {
            case TypeAttributes.Public:
            case TypeAttributes.NestedPublic:
                path.Add("public ");
                break;

            case TypeAttributes.NestedPrivate:
                path.Add("private ");
                break;

            case TypeAttributes.NestedFamily:
                path.Add("protected ");
                break;

            case TypeAttributes.NotPublic:
            case TypeAttributes.NestedAssembly:
            case TypeAttributes.NestedFamANDAssem:
                path.Add("internal ");
                break;

            case TypeAttributes.NestedFamORAssem:
                path.Add("protected internal ");
                break;
            }

            if (type.TypeAttributes.HasBitMask(TypeAttributes.Sealed))
            {
                path.Add("sealed ");
            }
            if (type.TypeAttributes.HasBitMask(TypeAttributes.Abstract))
            {
                path.Add("abstract ");
            }
            if (type.IsPartial)
            {
                path.Add("partial ");
            }

            path.Add("class ");

            path.Add(codeDomProvider.CreateEscapedIdentifier(type.Name));

            return(path.ToArray( ));
        }
예제 #8
0
        static void GenerateAction(CodeTypeReference exportAtt, CodeTypeDeclaration type, IBAction action,
                                   CodeDomProvider provider, CodeGeneratorOptions generatorOptions)
        {
            if (provider is Microsoft.CSharp.CSharpCodeProvider)
            {
                type.Members.Add(new CodeSnippetTypeMember("[" + exportAtt.BaseType + "(\"" + action.GetObjcFullName() + "\")]"));

                var sb = new System.Text.StringBuilder();
                sb.Append("partial void ");
                sb.Append(provider.CreateEscapedIdentifier(action.CliName));
                sb.Append(" (");
                if (action.Parameters != null)
                {
                    bool isFirst = true;
                    foreach (var p in action.Parameters)
                    {
                        if (!isFirst)
                        {
                            sb.Append(", ");
                        }
                        else
                        {
                            isFirst = false;
                        }
                        sb.Append(p.CliType);
                        sb.Append(" ");
                        sb.Append(provider.CreateEscapedIdentifier(p.Name));
                    }
                }
                sb.Append(");");

                type.Members.Add(new CodeSnippetTypeMember(sb.ToString()));
                return;
            }

            var m = CreateEventMethod(exportAtt, action);

            type.Members.Add(m);

            if (provider.FileExtension == "pas")
            {
                m.UserData ["OxygenePartial"] = "YES";
                m.UserData ["OxygeneEmpty"]   = "YES";
            }
        }
예제 #9
0
        protected override void AddTemplateParameters(IDictionary <string, object> templateParameters)
        {
            base.AddTemplateParameters(templateParameters);

            CodeType      codeType = Model.ModelType.CodeType;
            ModelMetadata metadata = new CodeModelModelMetadata(codeType);

            if (metadata.PrimaryKeys.Length == 0)
            {
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.NoKeyDefinedError, codeType.Name));
            }
            templateParameters.Add("ModelMetadata", metadata);

            HashSet <string> requiredNamespaces = GetRequiredNamespaces(new List <CodeType>()
            {
                codeType
            });

            templateParameters.Add("RequiredNamespaces", requiredNamespaces);

            string modelTypeNamespace = codeType.Namespace != null ? codeType.Namespace.FullName : String.Empty;

            templateParameters.Add("ModelTypeNamespace", modelTypeNamespace);
            templateParameters.Add("ModelTypeName", codeType.Name);
            templateParameters.Add("UseAsync", Model.IsAsyncSelected);

            IEntityFrameworkService efService = Context.ServiceProvider.GetService <IEntityFrameworkService>();
            string entitySetName = efService.GetPluralizedWord(codeType.Name, CultureInfo.InvariantCulture);

            templateParameters.Add("EntitySetName", entitySetName);

            CodeDomProvider provider          = ValidationUtil.GenerateCodeDomProvider(Model.ActiveProject.GetCodeLanguage());
            string          modelVariable     = provider.CreateEscapedIdentifier(codeType.Name.ToLowerInvariantFirstChar());
            string          entitySetVariable = provider.CreateEscapedIdentifier(entitySetName.ToLowerInvariantFirstChar());

            templateParameters.Add("ModelVariable", modelVariable);
            templateParameters.Add("EntitySetVariable", entitySetVariable);

            templateParameters.Add("ODataModificationMessage", Resources.ScaffoldODataModificationMessage);
            templateParameters.Add("IsLegacyOdataVersion", Framework.IsODataLegacy(Context));
        }
예제 #10
0
        string SanitizeResourceName(CodeDomProvider provider, string name)
        {
            if (provider.IsValidIdentifier(name))
            {
                return(provider.CreateEscapedIdentifier(name));
            }

            var  sb = new StringBuilder();
            char ch = name [0];

            if (is_identifier_start_character(ch))
            {
                sb.Append(ch);
            }
            else
            {
                sb.Append('_');
                if (ch >= '0' && ch <= '9')
                {
                    sb.Append(ch);
                }
            }

            for (int i = 1; i < name.Length; i++)
            {
                ch = name [i];
                if (is_identifier_part_character(ch))
                {
                    sb.Append(ch);
                }
                else
                {
                    sb.Append('_');
                }
            }

            return(provider.CreateEscapedIdentifier(sb.ToString()));
        }
        private static string [] GetStaticEventDefinitionPath(CodeDomProvider codeDomProvider, CodeMemberEvent @event)
        {
            var isStatic = @event.Attributes.HasBitMask(MemberAttributes.Static) &&
                           @event.PrivateImplementationType == null;

            if (!isStatic)
            {
                return(null);
            }

            var path = new List <string> ( );

            switch (@event.Attributes & MemberAttributes.AccessMask)
            {
            case MemberAttributes.Assembly:
                path.Add("internal ");
                break;

            case MemberAttributes.FamilyAndAssembly:
                path.Add("internal ");
                break;

            case MemberAttributes.Family:
                path.Add("protected ");
                break;

            case MemberAttributes.FamilyOrAssembly:
                path.Add("protected internal ");
                break;

            case MemberAttributes.Private:
                path.Add("private ");
                break;

            case MemberAttributes.Public:
                path.Add("public ");
                break;
            }

            path.Add("event ");
            path.Add(codeDomProvider.GetTypeOutput(@event.Type));
            path.Add(" ");
            path.Add(codeDomProvider.CreateEscapedIdentifier(@event.Name));

            return(path.ToArray( ));
        }
        protected virtual IDictionary <string, object> AddTemplateParameters(CodeType dbContextType, ModelMetadata modelMetadata)
        {
            if (dbContextType == null)
            {
                throw new ArgumentNullException("dbContextType");
            }
            if (modelMetadata == null)
            {
                throw new ArgumentNullException("modelMetadata");
            }
            if (string.IsNullOrEmpty(base.Model.ControllerName))
            {
                throw new InvalidOperationException("The controller name is invalid.");
            }
            IDictionary <string, object> strs = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);
            CodeType codeType = base.Model.ModelType.CodeType;

            strs.Add("ModelMetadata", modelMetadata);
            strs.Add("ModelTypeNamespace", (codeType.Namespace != null ? codeType.Namespace.FullName : string.Empty));
            List <CodeType> codeTypes = new List <CodeType>()
            {
                codeType,
                dbContextType
            };

            strs.Add("RequiredNamespaces", base.GetRequiredNamespaces(codeTypes));
            strs.Add("ModelTypeName", codeType.Name);
            strs.Add("ContextTypeName", dbContextType.Name);
            strs.Add("UseAsync", base.Model.IsAsyncSelected);
            CodeDomProvider codeDomProvider = ValidationUtil.GenerateCodeDomProvider(ProjectExtensions.GetCodeLanguage(base.Model.ActiveProject));
            string          str             = codeDomProvider.CreateEscapedIdentifier(base.Model.ModelType.ShortTypeName.ToLowerInvariantFirstChar());

            strs.Add("ModelVariable", str);
            strs.Add("EntitySetVariable", modelMetadata.EntitySetName.ToLowerInvariantFirstChar());
            if (base.Model.IsViewGenerationSupported)
            {
                bool flag = OverpostingProtection.IsOverpostingProtectionRequired(codeType);
                strs.Add("IsOverpostingProtectionRequired", flag);
                if (flag)
                {
                    strs.Add("OverpostingWarningMessage", OverpostingProtection.WarningMessage);
                    strs.Add("BindAttributeIncludeText", OverpostingProtection.GetBindAttributeIncludeText(modelMetadata));
                }
            }
            return(strs);
        }
예제 #13
0
        private static string ToIdentifierCatchEdgeCases(this string str, string enclosingType)
        {
            const string emptyIdentifierReplacement = "_";

            if (str == string.Empty)
            {
                str = emptyIdentifierReplacement;
            }

            if (str == enclosingType)
            {
                str = emptyIdentifierReplacement + str;
            }

            CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");

            str = provider.CreateEscapedIdentifier(str);
            provider.Dispose();

            return(str);
        }
 private static void EscapeKeywords(string identifier, CodeDomProvider codeProvider, StringBuilder sb)
 {
     if ((identifier != null) && (identifier.Length != 0))
     {
         int num = 0;
         while (identifier.EndsWith("[]", StringComparison.Ordinal))
         {
             num++;
             identifier = identifier.Substring(0, identifier.Length - 2);
         }
         if (identifier.Length > 0)
         {
             CheckValidIdentifier(identifier);
             identifier = codeProvider.CreateEscapedIdentifier(identifier);
             sb.Append(identifier);
         }
         for (int i = 0; i < num; i++)
         {
             sb.Append("[]");
         }
     }
 }
        protected virtual CodeTypeDeclaration AddTypeDeclaration(CodeNamespace classNamespace, ContentType contentType)
        {
            // One last check that the name is good, e.g. not a reserved word or begins with a number
            var typeName = _codeProvider.CreateEscapedIdentifier(contentType.Name);

            var typeDeclaration = new CodeTypeDeclaration(typeName);

            classNamespace.Types.Add(typeDeclaration);

            // Add base type
            string baseTypeName;

            switch (contentType.ContentTypeCategory)
            {
            case ContentTypeCategory.Page:
                baseTypeName = _options.PageBaseClass;
                break;

            case ContentTypeCategory.Block:
                baseTypeName = _options.BlockBaseClass;
                break;

            case ContentTypeCategory.Undefined:
            case ContentTypeCategory.BlockFolder:
            default:
                baseTypeName = null;
                break;
            }

            if (!string.IsNullOrEmpty(baseTypeName))
            {
                typeDeclaration.BaseTypes.Add(new CodeTypeReference(SimplifyTypeName(baseTypeName)));
            }

            return(typeDeclaration);
        }
        public static CodeCompileUnit Create(IEnumerable <KeyValuePair <string, string> > settings, string baseName, string generatedCodeNamespace, CodeDomProvider codeProvider, bool internalClass)
        {
            generatedCodeNamespace = codeProvider.CreateEscapedIdentifier(generatedCodeNamespace);
            baseName = codeProvider.CreateEscapedIdentifier(baseName);

            var kTypeParam = new CodeTypeParameter("TKey");
            var vTypeParam = new CodeTypeParameter("TValue");
            var tTypeParam = new CodeTypeParameter("T");

            var tType                    = new CodeTypeReference(tTypeParam);
            var objectType               = new CodeTypeReference(typeof(Object));
            var stringType               = new CodeTypeReference(typeof(String));
            var propertyInfoType         = new CodeTypeReference(typeof(PropertyInfo));
            var stringIndexerType        = new CodeTypeReference("IIndexer", stringType, stringType);
            var configIndexerType        = new CodeTypeReference("ConfigIndexer", new CodeTypeReference(new CodeTypeParameter(baseName)));
            var configGenericIndexerType = new CodeTypeReference("ConfigIndexer", new CodeTypeReference(tTypeParam));

            var bindingFlags   = new CodeTypeReferenceExpression(typeof(BindingFlags));
            var configManager  = new CodeTypeReferenceExpression(typeof(ConfigurationManager));
            var environment    = new CodeTypeReferenceExpression(typeof(Environment));
            var thisProperties = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_properties");
            var index          = new CodeVariableReferenceExpression("index");
            var props          = new CodeVariableReferenceExpression("props");
            var prop           = new CodeVariableReferenceExpression("prop");
            var result         = new CodeVariableReferenceExpression("result");
            var key            = new CodeArgumentReferenceExpression("key");

            var indexerInterface = new CodeTypeDeclaration("IIndexer")
            {
                TypeAttributes = TypeAttributes.Public | TypeAttributes.Interface,
                TypeParameters = { kTypeParam, vTypeParam },
                Members        =
                {
                    new CodeMemberProperty {
                        Name       = "Item",
                        Type       = new CodeTypeReference(vTypeParam),
                        HasGet     = true,
                        Parameters =       { new CodeParameterDeclarationExpression(new CodeTypeReference(kTypeParam),"key") }
                    }
                }
            };

            var configIndexerConstructor = new CodeConstructor {
                Attributes = MemberAttributes.Assembly,
                Statements =
                {
                    new CodeVariableDeclarationStatement(
                        typeof(PropertyInfo[]),
                        "props",
                        new CodeMethodInvokeExpression(
                            new CodeTypeOfExpression(tType),
                            "GetProperties",
                            new CodeBinaryOperatorExpression(
                                new CodeFieldReferenceExpression(bindingFlags,        "Public"),
                                CodeBinaryOperatorType.BitwiseOr,
                                new CodeFieldReferenceExpression(bindingFlags,        "Static")
                                )
                            )
                        ),
                    new CodeIterationStatement(
                        new CodeVariableDeclarationStatement(typeof(int),             "index",                    new CodePrimitiveExpression(0)),
                        new CodeBinaryOperatorExpression(
                            index,
                            CodeBinaryOperatorType.LessThan,
                            new CodeFieldReferenceExpression(props,                   "Length")
                            ),
                        new CodeAssignStatement(
                            index,
                            new CodeBinaryOperatorExpression(index,                   CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))
                            )
                        )
                    {
                        Statements =
                        {
                            new CodeVariableDeclarationStatement(typeof(PropertyInfo), "prop",           new CodeArrayIndexerExpression(props,                          index)),
                            new CodeMethodInvokeExpression(thisProperties,             "Add",            new CodePropertyReferenceExpression(prop,                      "Name"), prop)
                        }
                    }
                }
            };

            var normalizePropertyName = new CodeMemberMethod {
                Attributes = MemberAttributes.Static | MemberAttributes.Private,
                Name       = "NormalizePropertyName",
                ReturnType = stringType,
                Parameters = { new CodeParameterDeclarationExpression(stringType, "key") },
                Statements =
                {
                    new CodeConditionStatement(
                        new CodeMethodInvokeExpression(
                            new CodeTypeReferenceExpression(typeof(String)),
                            "IsNullOrEmpty",
                            key
                            ),
                        new CodeMethodReturnStatement(key)
                        ),
                    new CodeVariableDeclarationStatement(
                        typeof(StringBuilder),
                        "sb",
                        new CodeObjectCreateExpression(typeof(StringBuilder))
                        ),
                    new CodeIterationStatement(
                        new CodeVariableDeclarationStatement(typeof(int),                                     index.VariableName,new CodePrimitiveExpression(0)),
                        new CodeBinaryOperatorExpression(
                            index,
                            CodeBinaryOperatorType.LessThan,
                            new CodePropertyReferenceExpression(key,                                          "Length")
                            ),
                        new CodeAssignStatement(
                            index,
                            new CodeBinaryOperatorExpression(
                                index,
                                CodeBinaryOperatorType.Add,
                                new CodePrimitiveExpression(1)
                                )
                            ),
                        new CodeVariableDeclarationStatement(
                            typeof(char),
                            "c",
                            new CodeArrayIndexerExpression(key,                                               index)
                            ),
                        new CodeConditionStatement(
                            new CodeBinaryOperatorExpression(
                                new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("sb"),"Length"),
                                CodeBinaryOperatorType.ValueEquality,
                                new CodePrimitiveExpression(0)
                                ),
                            trueStatements: new CodeStatement[] {
                        new CodeConditionStatement(
                            new CodeBinaryOperatorExpression(
                                new CodeMethodInvokeExpression(
                                    new CodeTypeReferenceExpression(typeof(Char)),
                                    "IsLetter",
                                    new CodeVariableReferenceExpression("c")
                                    ),
                                CodeBinaryOperatorType.BooleanOr,
                                new CodeBinaryOperatorExpression(
                                    new CodeVariableReferenceExpression("c"),
                                    CodeBinaryOperatorType.ValueEquality,
                                    new CodePrimitiveExpression('_')
                                    )
                                ),
                            new CodeExpressionStatement(
                                new CodeMethodInvokeExpression(
                                    new CodeVariableReferenceExpression("sb"),
                                    "Append",
                                    new CodeVariableReferenceExpression("c")
                                    )
                                )
                            )
                    },
                            falseStatements: new CodeStatement[] {
                        new CodeConditionStatement(
                            new CodeBinaryOperatorExpression(
                                new CodeMethodInvokeExpression(
                                    new CodeTypeReferenceExpression(typeof(Char)),
                                    "IsLetter",
                                    new CodeVariableReferenceExpression("c")
                                    ),
                                CodeBinaryOperatorType.BooleanOr,
                                new CodeBinaryOperatorExpression(
                                    new CodeMethodInvokeExpression(
                                        new CodeTypeReferenceExpression(typeof(Char)),
                                        "IsNumber",
                                        new CodeVariableReferenceExpression("c")
                                        ),
                                    CodeBinaryOperatorType.BooleanOr,
                                    new CodeBinaryOperatorExpression(
                                        new CodeVariableReferenceExpression("c"),
                                        CodeBinaryOperatorType.ValueEquality,
                                        new CodePrimitiveExpression('_')
                                        )
                                    )
                                ),
                            new CodeExpressionStatement(
                                new CodeMethodInvokeExpression(
                                    new CodeVariableReferenceExpression("sb"),
                                    "Append",
                                    new CodeVariableReferenceExpression("c")
                                    )
                                )
                            )
                    }
                            )
                        ),
                    new CodeMethodReturnStatement(
                        new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("sb"),             "ToString")
                        )
                }
            };

            var configIndexerClass = new CodeTypeDeclaration("ConfigIndexer")
            {
                TypeAttributes = TypeAttributes.NestedPrivate,
                TypeParameters = { tTypeParam },
                BaseTypes      = { objectType, stringIndexerType },
                Members        =
                {
                    configIndexerConstructor,
                    normalizePropertyName,
                    new CodeMemberField(typeof(IDictionary <string,                               PropertyInfo>),             "_properties")
                    {
                        Attributes     = MemberAttributes.Private,
                        InitExpression = new CodeObjectCreateExpression(typeof(Dictionary <string,PropertyInfo>))
                    },
                    new CodeMemberProperty {
                        Attributes          = MemberAttributes.Public | MemberAttributes.Final,
                        ImplementationTypes = { stringIndexerType },
                        Name          = "Item",
                        Type          = stringType,
                        Parameters    = { new CodeParameterDeclarationExpression(stringType,      "key") },
                        GetStatements =
                        {
                            new CodeVariableDeclarationStatement(
                                stringType,
                                result.VariableName,
                                new CodeMethodInvokeExpression(
                                    new CodeMethodReferenceExpression(environment,                "GetEnvironmentVariable"),
                                    new CodeArgumentReferenceExpression("key")
                                    )
                                ),
                            new CodeConditionStatement(
                                new CodeBinaryOperatorExpression(
                                    result,
                                    CodeBinaryOperatorType.IdentityInequality,
                                    new CodePrimitiveExpression(null)
                                    ),
                                new CodeMethodReturnStatement(result)
                                ),
                            new CodeAssignStatement(
                                new CodeVariableReferenceExpression(result.VariableName),
                                new CodeIndexerExpression(
                                    new CodePropertyReferenceExpression(configManager,            "AppSettings"),
                                    new CodeArgumentReferenceExpression("key")
                                    )
                                ),
                            new CodeConditionStatement(
                                new CodeBinaryOperatorExpression(
                                    result,
                                    CodeBinaryOperatorType.IdentityInequality,
                                    new CodePrimitiveExpression(null)
                                    ),
                                new CodeMethodReturnStatement(result)
                                ),
                            new CodeVariableDeclarationStatement(propertyInfoType,                "prop"),
                            new CodeConditionStatement(
                                new CodeMethodInvokeExpression(
                                    thisProperties,
                                    "TryGetValue",
                                    new CodeMethodInvokeExpression(
                                        new CodeTypeReferenceExpression(configGenericIndexerType),
                                        normalizePropertyName.Name,
                                        key
                                        ),
                                    new CodeDirectionExpression(FieldDirection.Out,               prop)
                                    ),
                                new CodeMethodReturnStatement(
                                    new CodeMethodInvokeExpression(
                                        new CodeMethodInvokeExpression(prop,                      "GetValue",                               new CodeTypeOfExpression(tType)),
                                        "ToString"
                                        )
                                    )
                                ),
                            new CodeMethodReturnStatement(new CodePrimitiveExpression(null))
                        }
                    }
                }
            };

            var members = settings
                          .Select(
                setting => new CodeMemberProperty {
                Attributes    = MemberAttributes.Public | MemberAttributes.Static,
                Type          = stringType,
                Name          = VerifyConfigKey(setting.Key, codeProvider),
                GetStatements =
                {
                    new CodeVariableDeclarationStatement(
                        stringType,
                        result.VariableName,
                        new CodeMethodInvokeExpression(
                            new CodeMethodReferenceExpression(environment,           "GetEnvironmentVariable"),
                            new CodePrimitiveExpression(setting.Key)
                            )
                        ),
                    new CodeConditionStatement(
                        new CodeBinaryOperatorExpression(
                            new CodeVariableReferenceExpression(result.VariableName),
                            CodeBinaryOperatorType.IdentityInequality,
                            new CodePrimitiveExpression(null)
                            ),
                        new CodeMethodReturnStatement(result)
                        ),
                    new CodeAssignStatement(
                        new CodeVariableReferenceExpression(result.VariableName),
                        new CodeIndexerExpression(
                            new CodePropertyReferenceExpression(configManager,       "AppSettings"),
                            new CodePrimitiveExpression(setting.Key)
                            )
                        ),
                    new CodeConditionStatement(
                        new CodeBinaryOperatorExpression(
                            new CodeVariableReferenceExpression(result.VariableName),
                            CodeBinaryOperatorType.IdentityInequality,
                            new CodePrimitiveExpression(null)
                            ),
                        new CodeMethodReturnStatement(result)
                        ),
                    new CodeMethodReturnStatement(new CodePrimitiveExpression(setting.Value))
                }
            }
                )
                          .Cast <CodeTypeMember>()
                          .ToArray();

            var configClass = new CodeTypeDeclaration(baseName)
            {
                TypeAttributes   = (internalClass ? TypeAttributes.NestedAssembly : TypeAttributes.Public) | TypeAttributes.Sealed,
                CustomAttributes =
                {
                    new CodeAttributeDeclaration(
                        new CodeTypeReference(typeof(GeneratedCodeAttribute),                                            CodeTypeReferenceOptions.GlobalReference),
                        new CodeAttributeArgument(new CodePrimitiveExpression(StronglyTypedConfigBuilderType.FullName)),
                        new CodeAttributeArgument(new CodePrimitiveExpression(StronglyTypedConfigBuilderType.Assembly.GetName().Version.ToString()))
                        ),
                    new CodeAttributeDeclaration(
                        new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute),                                      CodeTypeReferenceOptions.GlobalReference)
                        ),
                    new CodeAttributeDeclaration(
                        new CodeTypeReference(typeof(CompilerGeneratedAttribute),                                        CodeTypeReferenceOptions.GlobalReference)
                        )
                },
                Members =
                {
                    new CodeConstructor    {
                        Attributes = MemberAttributes.Private
                    },
                    new CodeMemberField    {
                        Attributes     = MemberAttributes.Private | MemberAttributes.Static,
                        Name           = "_items",
                        Type           = stringIndexerType,
                        InitExpression = new CodeObjectCreateExpression(configIndexerType)
                    },
                    new CodeMemberProperty {
                        Attributes    = MemberAttributes.Public | MemberAttributes.Static,
                        Name          = "Items",
                        Type          = stringIndexerType,
                        GetStatements =
                        {
                            new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, "_items"))
                        }
                    },
                    indexerInterface,
                    configIndexerClass,
                }
            };

            configClass.Members.AddRange(members);

            var configNamespace = new CodeNamespace(generatedCodeNamespace);

            configNamespace.Types.Add(configClass);

            var compileUnit = new CodeCompileUnit();

            compileUnit.Namespaces.Add(configNamespace);

            return(compileUnit);
        }
예제 #17
0
        protected virtual void AddTemplateParameters(IDictionary <string, object> templateParameters)
        {
            if (templateParameters == null)
            {
                throw new ArgumentNullException("templateParameters");
            }

            if (String.IsNullOrEmpty(Model.ControllerName))
            {
                throw new InvalidOperationException(Resources.InvalidControllerName);
            }

            templateParameters.Add("ControllerName", Model.ControllerName);
            templateParameters.Add("ControllerNamespace", Model.ControllerNamespace);
            templateParameters.Add("AreaName", Model.AreaName ?? String.Empty);
            templateParameters.Add("ServiceName", Model.ServiceType.ShortTypeName);
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\b([_\d\w]*)$");
            string viewModelShortName = regex.Match(Model.ViewModelTypeName).Result("$1");

            templateParameters.Add("ViewModelPropertys", Model.ViewModelPropertys.Where(p => p.Checked).ToList());

            CodeType modelCodeType = Context.ServiceProvider.GetService <ICodeTypeService>().GetCodeType(Context.ActiveProject, Model.ModelType.TypeName);

            CodeModelModelMetadata modelMetadata = new CodeModelModelMetadata(modelCodeType);

            CodeType modelType = Model.ModelType.CodeType;

            templateParameters.Add("ModelMetadata", modelMetadata);

            string modelTypeNamespace = modelType.Namespace != null ? modelType.Namespace.FullName : String.Empty;

            templateParameters.Add("ModelTypeNamespace", modelTypeNamespace);

            string viewModelNamespace = Model.ActiveProject.Name + "." + CommonFolderNames.Models;

            templateParameters.Add("ViewModelNamespace", viewModelNamespace);

            string validatorNamespace = Model.ActiveProject.Name + "." + CommonFolderNames.Validator;

            templateParameters.Add("ValidatorNamespace", validatorNamespace);

            string serviceNamespace = Model.ServiceProject.GetDefaultNamespace();

            templateParameters.Add("ServiceNamespace", serviceNamespace);

            string serviceShortTypeName = Model.ServiceType.ShortTypeName;

            templateParameters.Add("ServiceShortTypeName", serviceShortTypeName);

            string viewModelShortTypeName = Model.ViewModelType.ShortTypeName;

            templateParameters.Add("ViewModelShortTypeName", viewModelShortName);

            HashSet <string> requiredNamespaces = GetRequiredNamespaces(new List <CodeType>()
            {
                modelType
            });

            templateParameters.Add("RequiredNamespaces", requiredNamespaces);
            string modelTypeName = modelType.Name;

            templateParameters.Add("ModelTypeName", modelTypeName);
            templateParameters.Add("UseAsync", Model.IsAsyncSelected);

            CodeDomProvider provider      = ValidationUtil.GenerateCodeDomProvider(Model.ActiveProject.GetCodeLanguage());
            string          modelVariable = provider.CreateEscapedIdentifier(Model.ModelType.ShortTypeName.ToLowerInvariantFirstChar());

            templateParameters.Add("ModelVariable", modelVariable);
        }
        internal static ValidationError ValidateNameProperty(string propName, IServiceProvider context, string identifier)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            ValidationError error = null;

            if ((identifier == null) || (identifier.Length == 0))
            {
                error = new ValidationError(SR.GetString("Error_PropertyNotSet", new object[] { propName }), 0x116);
            }
            else
            {
                System.Workflow.Activities.Common.SupportedLanguages supportedLanguage = System.Workflow.Activities.Common.CompilerHelpers.GetSupportedLanguage(context);
                CodeDomProvider codeDomProvider = System.Workflow.Activities.Common.CompilerHelpers.GetCodeDomProvider(supportedLanguage);
                if ((((supportedLanguage == System.Workflow.Activities.Common.SupportedLanguages.CSharp) && identifier.StartsWith("@", StringComparison.Ordinal)) || (((supportedLanguage == System.Workflow.Activities.Common.SupportedLanguages.VB) && identifier.StartsWith("[", StringComparison.Ordinal)) && identifier.EndsWith("]", StringComparison.Ordinal))) || !codeDomProvider.IsValidIdentifier(codeDomProvider.CreateEscapedIdentifier(identifier)))
                {
                    error = new ValidationError(SR.GetString("Error_InvalidIdentifier", new object[] { propName, SR.GetString("Error_InvalidLanguageIdentifier", new object[] { identifier }) }), 0x119);
                }
            }
            if (error != null)
            {
                error.PropertyName = propName;
            }
            return(error);
        }
예제 #19
0
        /*
        internal static string GetTypeName(string name, CodeDomProvider codeProvider) {
            return codeProvider.GetTypeOutput(new CodeTypeReference(name));
        }
        */

        private static void EscapeKeywords(string identifier, CodeDomProvider codeProvider, StringBuilder sb)
        {
            if (identifier == null || identifier.Length == 0)
                return;
            int arrayCount = 0;
            while (identifier.EndsWith("[]", StringComparison.Ordinal))
            {
                arrayCount++;
                identifier = identifier.Substring(0, identifier.Length - 2);
            }
            if (identifier.Length > 0)
            {
                CheckValidIdentifier(identifier);
                identifier = codeProvider.CreateEscapedIdentifier(identifier);
                sb.Append(identifier);
            }
            for (int i = 0; i < arrayCount; i++)
            {
                sb.Append("[]");
            }
        }
예제 #20
0
 public string CreateEscapedIdentifier(string value)
 {
     return(provider.CreateEscapedIdentifier(value));
 }