Ejemplo n.º 1
0
        public virtual void Execute(XmlNode node)
        {
            var reportNodes = node.SelectNodes("./Report");

            foreach (XmlNode reportNode in reportNodes)
            {
                var name = reportNode.Attributes["Name"].Value;

                var path = reportNode.SelectSingleNode("./Path")?.InnerXml;
                path = path ?? $"{NamingConvention.Apply(name)}.rdl";
                if (!Path.IsPathRooted(path))
                {
                    path = Path.Combine(RootPath ?? string.Empty, path);
                }

                var description = reportNode.SelectSingleNode("./Description")?.InnerXml;
                var hidden      = bool.Parse(reportNode.Attributes["Hidden"]?.Value ?? bool.FalseString);

                reportService.Create(name, ParentPath, path, description, hidden, Root?.DataSources, Root?.SharedDatasets);

                foreach (var childParser in ChildrenParsers)
                {
                    childParser.ParentPath = $"{ParentPath}/{name}";
                    childParser.Execute(reportNode);
                }
            }
        }
        private ScriptableObjectBinder(Type type, JSBindingOptions options, NamingConvention namingConvention)
        {
            if (type == null) throw new ArgumentNullException("type");

            if (!type.IsClass && !type.IsInterface) throw new ArgumentException("The type must be a class or interface.");

            this.type = type;

            var attr = GetJSObjectAttribute(this.type);
            if (attr != null)
            {
                if (options == JSBindingContext.DefaultOptions)
                {
                    this.options = attr.Options;
                }
            }
            else
            {
                this.options = options;
            }

            this.namingConvention = namingConvention;

            this.Create();

            Debug.Assert(this.dispatchTable != null);
            Debug.Assert(this.propertyDispatchTable != null);

            if ((this.options & JSBindingOptions.LazyCompile) == 0)
            {
                this.Compile();
            }
        }
        public bool IsNamingConventionType(NamingConvention namingConvention, string value)
        {
            switch (namingConvention)
            {
            case NamingConvention.CamelCase:
                return(!value.Contains(" ") &&
                       !value.Contains("-") &&
                       char.IsLower(value.First()));

            case NamingConvention.PascalCase:
                return(!value.Contains(" ") &&
                       !value.Contains("-") &&
                       char.IsUpper(value.First()));

            case NamingConvention.TitleCase:
                return(!value.Contains("-") &&
                       char.IsUpper(value.First()));

            case NamingConvention.SnakeCase:
                return(!value.Contains(" ") &&
                       !value.Any(c => char.IsUpper(c)));
            }

            throw new NotImplementedException();
        }
Ejemplo n.º 4
0
 private static Boolean KawigiEdit_RunTest(int testNum, string p0, Boolean hasAnswer, string p1)
 {
     Console.Write("Test " + testNum + ": [" + "\"" + p0 + "\"");
     Console.WriteLine("]");
     NamingConvention obj;
     string answer;
     obj = new NamingConvention();
     DateTime startTime = DateTime.Now;
     answer = obj.toCamelCase(p0);
     DateTime endTime = DateTime.Now;
     Boolean res;
     res = true;
     Console.WriteLine("Time: " + (endTime - startTime).TotalSeconds + " seconds");
     if (hasAnswer) {
         Console.WriteLine("Desired answer:");
         Console.WriteLine("\t" + "\"" + p1 + "\"");
     }
     Console.WriteLine("Your answer:");
     Console.WriteLine("\t" + "\"" + answer + "\"");
     if (hasAnswer) {
         res = answer == p1;
     }
     if (!res) {
         Console.WriteLine("DOESN'T MATCH!!!!");
     } else if ((endTime - startTime).TotalSeconds >= 2) {
         Console.WriteLine("FAIL the timeout");
         res = false;
     } else if (hasAnswer) {
         Console.WriteLine("Match :-)");
     } else {
         Console.WriteLine("OK, but is it right?");
     }
     Console.WriteLine("");
     return res;
 }
        public void TestConvert()
        {
            string name1 = "_DFC.EntityType__Root_SUFFIX_term10";
            string name2 = "_DFC_ENTITY_Type_Root_SUFFIX_TERM10";
            string name3 = "_Dfc_Entity_type_RootSuffix_term10";

            NamingConvention c      = new NamingConvention(NamingStyle.LowerCase);
            string           nameLC = "_dfc_entity_type_root_suffix_term10";

            Assert.AreEqual(nameLC, c.Convert(name1));
            Assert.AreEqual(nameLC, c.Convert(name2));
            Assert.AreEqual(nameLC, c.Convert(name3));

            c = new NamingConvention(NamingStyle.UpperCase);
            string nameUC = "_DFC_ENTITY_TYPE_ROOT_SUFFIX_TERM10";

            Assert.AreEqual(nameUC, c.Convert(name1));
            Assert.AreEqual(nameUC, c.Convert(name2));
            Assert.AreEqual(nameUC, c.Convert(name3));

            c = new NamingConvention(NamingStyle.CamelCase);
            string nameCC = "DfcEntityTypeRootSuffixTerm10";

            Assert.AreEqual(nameCC, c.Convert(name1));
            Assert.AreEqual(nameCC, c.Convert(name2));
            Assert.AreEqual(nameCC, c.Convert(name3));
        }
Ejemplo n.º 6
0
        public async Task <Document> ScaffoldAsync(SyntaxNode syntax, NamingConvention naming)
        {
            var name = syntax.DescendantNodes().OfType <ClassDeclarationSyntax>()
                       .Select(x => x.Identifier.ToString())
                       .FirstOrDefault() ?? "Avatar";

            var document = project.AddDocument(nameof(AvatarScaffold),
                                               // NOTE: if we don't force re-parsing in the context of our own
                                               // project, nested types can't be resolved, for some reason :/
                                               syntax.NormalizeWhitespace().ToFullString(),
                                               folders: naming.RootNamespace.Split('.'),
                                               filePath: name);

            foreach (var refactoring in refactorings)
            {
                document = await document.ApplyCodeActionAsync(refactoring, cancellationToken : context.CancellationToken);
            }

            foreach (var codeFix in codeFixes)
            {
                document = await document.ApplyCodeFixAsync(codeFix, cancellationToken : context.CancellationToken);
            }

            return(document);
        }
Ejemplo n.º 7
0
        public JsonDeserializer(NamingConvention namingConvention = NamingConvention.CamelHump)
        {
            _jsonSettings = new JsonSerializerSettings();

            NamingStrategy selectedNamingStrategy;

            switch (namingConvention)
            {
            case NamingConvention.CamelHump:
                selectedNamingStrategy = new CamelCaseNamingStrategy(true, false);
                break;

            case NamingConvention.SnakeCase:
                selectedNamingStrategy = new SnakeCaseNamingStrategy(true, false);
                break;

            default:
                selectedNamingStrategy = new DefaultNamingStrategy();
                break;
            }

            _jsonSettings.ContractResolver = new PrivateSetterContractResolver
            {
                NamingStrategy = selectedNamingStrategy
            };
        }
Ejemplo n.º 8
0
        public virtual Database LinkTables()
        {
            foreach (var table in Tables)
            {
                foreach (var column in table.Columns)
                {
                    if (table.PrimaryKey?.Key.Count == 1 && table.PrimaryKey.Key.Contains(column.Name))
                    {
                        continue;
                    }

                    foreach (var parentTable in Tables)
                    {
                        if (table.FullName == parentTable.FullName)
                        {
                            continue;
                        }

                        if (parentTable.PrimaryKey != null && parentTable.PrimaryKey.Key.Contains(column.Name))
                        {
                            table.ForeignKeys.Add(new ForeignKey(column.Name)
                            {
                                ConstraintName = NamingConvention.GetForeignKeyConstraintName(table, new string[] { column.Name }, parentTable),
                                References     = string.Format("{0}.{1}", Name, parentTable.FullName),
                                Child          = table.FullName
                            });
                        }
                    }
                }
            }

            return(this);
        }
Ejemplo n.º 9
0
    public LoadDriver(IDockerNetwork network, NamingConvention namingConvention, TestConfig testConfig)
    {
        _network = network ?? throw new ArgumentNullException(nameof(network));
        if (namingConvention == null)
        {
            throw new ArgumentNullException(nameof(namingConvention));
        }
        if (testConfig == null)
        {
            throw new ArgumentNullException(nameof(testConfig));
        }

        _logStream    = File.Create(Path.Combine(namingConvention.ContainerLogs, "k6.txt"));
        _resultStream = File.Create(Path.Combine(namingConvention.AgentResults, K6ResultsFile));

        _hostScriptPath = Path.Combine(Directory.GetCurrentDirectory(), "K6", "basic.js");
        _container      = new TestcontainersBuilder <TestcontainersContainer>()
                          .WithImage(LoadDriveImageName)
                          .WithName($"{OverheadTest.Prefix}-k6-load")
                          .WithNetwork(_network)
                          .WithCommand("run",
                                       "-u", testConfig.ConcurrentConnections.ToString(),
                                       "-e", $"ESHOP_HOSTNAME={EshopApp.ContainerName}",
                                       "-i", testConfig.Iterations.ToString(),
                                       "--rps", testConfig.MaxRequestRate.ToString(),
                                       ContainerScriptPath,
                                       "--summary-export", ContainerResultsPath)
                          .WithBindMount(_hostScriptPath, ContainerScriptPath)
                          .WithOutputConsumer(Consume.RedirectStdoutAndStderrToStream(_logStream, _logStream))
                          .Build();
    }
Ejemplo n.º 10
0
        public static SerializerBuilder WithNamingConvention(this SerializerBuilder serializerBuilder,
                                                             NamingConvention namingConvention)
        {
            var target = GetNamingConvention(namingConvention);

            return(serializerBuilder.WithNamingConvention(target));
        }
Ejemplo n.º 11
0
        public void Can_create_configuration_report()
        {
            var sut = ConfigurationReporter.CreateDefault();

            new ConfigurationBuilder(ConfigurationKeys("key1", "key2"), None)
            .WithConfigurationSource(new ConfigurationSourceStub(
                                         ("KEY2", "value")
                                         ))
            .WithConfigurations(new Dictionary <string, string>
            {
                { "key3", "value" }
            })
            .WithNamingConventions(NamingConvention.Default, NamingConvention.UseCustom(x => x.ToUpper()))
            .WithConfigurationReporter(sut)
            .Build();

            var report = sut.Report();

            _output.WriteLine(report);

            Assert.Equal(expected:
                         $"{NL}" +
                         $"key  source                  value   keys{NL}" +
                         $"-----------------------------------------------{NL}" +
                         $"key3 MANUAL                  value   {NL}" +
                         $"key1 ConfigurationSourceStub MISSING key1, KEY1{NL}" +
                         $"key2 ConfigurationSourceStub value   KEY2{NL}",
                         report);
        }
Ejemplo n.º 12
0
        private static INamingConvention GetNamingConvention(NamingConvention namingConvention)
        {
            INamingConvention target;

            switch (namingConvention)
            {
            case NamingConvention.Camel:
                target = new CamelCaseNamingConvention();
                break;

            case NamingConvention.Hyphenated:
                target = new HyphenatedNamingConvention();
                break;

            case NamingConvention.Pascal:
                target = new PascalCaseNamingConvention();
                break;

            case NamingConvention.Underscored:
                target = new UnderscoredNamingConvention();
                break;

            case NamingConvention.Null:
                target = new NullNamingConvention();
                break;

            default:
                throw new NotImplementedException(namingConvention.ToString());
            }

            return(target);
        }
        public void SetConsumerName_Works(Type eventType,
                                          Type consumerType,
                                          bool useFullTypeNames,
                                          string prefix,
                                          bool suffixEventName,
                                          ConsumerNameSource consumerNameSource,
                                          NamingConvention namingConvention,
                                          string expected)
        {
            var environment = new FakeHostEnvironment("app1");
            var options     = new EventBusOptions {
            };

            options.Naming.Convention         = namingConvention;
            options.Naming.UseFullTypeNames   = useFullTypeNames;
            options.Naming.ConsumerNameSource = consumerNameSource;
            options.Naming.ConsumerNamePrefix = prefix;
            options.Naming.SuffixConsumerName = suffixEventName;

            var registration = new EventRegistration(eventType);

            registration.Consumers.Add(new EventConsumerRegistration(consumerType));

            var creg = Assert.Single(registration.Consumers);

            registration.SetEventName(options.Naming)
            .SetConsumerNames(options.Naming, environment);
            Assert.Equal(expected, creg.ConsumerName);
        }
Ejemplo n.º 14
0
            public override SyntaxNode CreateSyntax(NamingConvention naming, INamedTypeSymbol[] symbols)
            {
                var name    = naming.GetName(symbols);
                var imports = new HashSet <string>();

                var(baseType, implementedInterfaces) = symbols.ValidateGeneratorTypes();

                if (baseType != null)
                {
                    AddImports(imports, baseType);
                }

                foreach (var iface in implementedInterfaces)
                {
                    AddImports(imports, iface);
                }

                return(CompilationUnit()
                       .WithUsings(
                           List(
                               imports.Select(ns => UsingDirective(ParseName(ns)))))
                       .WithMembers(
                           SingletonList <MemberDeclarationSyntax>(
                               NamespaceDeclaration(ParseName(naming.GetNamespace(symbols)))
                               .WithMembers(
                                   SingletonList <MemberDeclarationSyntax>(
                                       ClassDeclaration(name)
                                       .WithModifiers(TokenList(Token(SyntaxKind.PartialKeyword)))
                                       .WithBaseList(
                                           BaseList(
                                               SeparatedList <BaseTypeSyntax>(
                                                   symbols.Select(AsTypeSyntax).Select(t => SimpleBaseType(t))))))))));
            }
Ejemplo n.º 15
0
        /// <summary>Converts this object to a convention.</summary>
        /// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception>
        /// <exception cref="ArgumentException">    Thrown when one or more arguments have unsupported or
        ///  illegal values.</exception>
        /// <param name="name">                  The value.</param>
        /// <param name="path">                  Full pathname of the file.</param>
        /// <param name="convention">            The convention.</param>
        /// <param name="concatenatePath">       (Optional) True to concatenate path.</param>
        /// <param name="concatenationDelimiter">(Optional) The concatenation delimiter.</param>
        /// <returns>The given data converted to a string.</returns>
        public static string ToConvention(
            string name,
            string path,
            NamingConvention convention,
            bool concatenatePath          = false,
            string concatenationDelimiter = "")
        {
            string value = name;

            if (concatenatePath && (!string.IsNullOrEmpty(path)))
            {
                value = path;
            }

            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentNullException(nameof(name));
            }

            switch (convention)
            {
            case NamingConvention.FhirDotNotation:
                return(value);

            case NamingConvention.PascalDotNotation:
            {
                string[] components = ToPascal(value.Split('.'));
                return(string.Join(".", components));
            }

            case NamingConvention.PascalCase:
            {
                string[] components = ToPascal(value.Split('.'));
                return(string.Join(concatenationDelimiter, components));
            }

            case NamingConvention.CamelCase:
            {
                string[] components = ToCamel(value.Split('.'));
                return(string.Join(concatenationDelimiter, components));
            }

            case NamingConvention.UpperCase:
            {
                string[] components = ToUpperInvariant(value.Split('.'));
                return(string.Join(concatenationDelimiter, components));
            }

            case NamingConvention.LowerCase:
            {
                string[] components = ToLowerInvariant(value.Split('.'));
                return(string.Join(concatenationDelimiter, components));
            }

            case NamingConvention.None:
            default:
                throw new ArgumentException($"Invalid Naming Convention: {convention}");
            }
        }
Ejemplo n.º 16
0
 protected SqlServerBase(NamingConvention namingConvention)
 {
     if (namingConvention == null)
     {
         throw new ArgumentNullException(nameof(namingConvention));
     }
     Stream = File.Create(Path.Combine(namingConvention.ContainerLogs, "sqlserver.txt"));
 }
        protected override NamingConvention CreateNamingConvention()
        {
            var namingConvension = new NamingConvention {
                LetterCasePolicy = LetterCasePolicy.Default
            };

            return(namingConvension);
        }
Ejemplo n.º 18
0
        public IActionResult Index([FromQuery] NamingConvention conv)
        {
            ViewData["conv"] = Helper.NamingConventionList(conv);
            ViewData["root"] = Helper.Notes[conv];
            ViewData["type"] = Helper.ChordTypeList;

            return(View());
        }
Ejemplo n.º 19
0
        public void Can_use_environment_style_naming_convention_with_prefix()
        {
            var sut = NamingConvention.UseEnvironmentStyle("DEFAULT_KAFKA");

            var result = sut.GetKey("group.id");

            Assert.Equal("DEFAULT_KAFKA_GROUP_ID", result);
        }
Ejemplo n.º 20
0
        public void Can_use_environment_style_naming_convention()
        {
            var sut = NamingConvention.UseEnvironmentStyle();

            var result = sut.GetKey("group.id");

            Assert.Equal("GROUP_ID", result);
        }
Ejemplo n.º 21
0
        public void Can_use_custom_naming()
        {
            var sut = NamingConvention.UseCustom(s => s.ToUpper());

            var result = sut.GetKey("group.id");

            Assert.Equal("GROUP.ID", result);
        }
Ejemplo n.º 22
0
        public void Using_custom_toupper_with_turkish_culture_will_fail()
        {
            var sut = NamingConvention.UseCustom(s => s.ToUpper());

            var result = sut.GetKey("group.id");

            Assert.NotEqual("GROUP.ID", result);
        }
        protected override NamingConvention CreateNamingConvention()
        {
            var namingConvention = new NamingConvention {
                LetterCasePolicy = LetterCasePolicy.Lowercase
            };

            return(namingConvention);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Converts the value of a type specified by a generic type parameter into a YAML-formatted array of UTF-8
        /// encoded bytes.
        /// </summary>
        /// <param name="value">The object to parse to YAML.</param>
        /// <param name="compressionType">The type of compression to use.</param>
        /// <param name="namingConvention">The naming convention to use.</param>
        /// <returns>A YAML-formatted UTF-8 encoded array of bytes, parsed from the given object.</returns>
        public static async Task <byte[]> GetBytesAsync(object value, NamingConvention namingConvention, CompressionType compressionType)
        {
            var bytes = await GetBytesAsync(namingConvention).ConfigureAwait(false);

            return(compressionType == CompressionType.None
                ? bytes
                : await Utility.CompressHelperAsync(bytes, compressionType).ConfigureAwait(false));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Converts the value of a type specified by a generic type parameter into a JSON-formatted array of UTF-8
        /// encoded bytes.
        /// </summary>
        /// <param name="value">The object to parse to JSON.</param>
        /// <param name="namingConvention">The naming convention to write in.</param>
        /// <returns>A JSON-formatted UTF-8 encoded array of bytes, parsed from the given object.</returns>
        public static MemoryStream GetStream(object value, NamingConvention namingConvention)
        {
            var stream = new MemoryStream();

            Serialise_Internal(stream, value, namingConvention);

            return(stream);
        }
Ejemplo n.º 26
0
        private void CheckNaming(SyntaxToken currentIdentifier, string memberType, NamingConvention convention, SyntaxNodeAnalysisContext context)
        {
            var conventionedIdentifier = currentIdentifier.WithConvention(convention);

            if (conventionedIdentifier.Text != currentIdentifier.Text)
            {
                context.ReportDiagnostic(Diagnostic.Create(Rule, currentIdentifier.GetLocation(), memberType, currentIdentifier.Text, conventionedIdentifier.Text));
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Converts the element to a native configuration object it corresponds to -
        /// i.e. to a <see cref="DomainConfiguration"/> object.
        /// </summary>
        /// <returns>The result of conversion.</returns>
        public DomainConfiguration ToNative()
        {
            var config = new DomainConfiguration {
                Name                            = Name,
                ConnectionInfo                  = ConnectionInfoParser.GetConnectionInfo(CurrentConfiguration, ConnectionUrl, Provider, ConnectionString),
                NamingConvention                = NamingConvention.ToNative(),
                KeyCacheSize                    = KeyCacheSize,
                KeyGeneratorCacheSize           = KeyGeneratorCacheSize,
                QueryCacheSize                  = QueryCacheSize,
                RecordSetMappingCacheSize       = RecordSetMappingCacheSize,
                DefaultSchema                   = DefaultSchema,
                DefaultDatabase                 = DefaultDatabase,
                UpgradeMode                     = ParseEnum <DomainUpgradeMode>(UpgradeMode),
                ForeignKeyMode                  = ParseEnum <ForeignKeyMode>(ForeignKeyMode),
                SchemaSyncExceptionFormat       = ParseEnum <SchemaSyncExceptionFormat>(SchemaSyncExceptionFormat),
                Options                         = ParseEnum <DomainOptions>(Options),
                ServiceContainerType            = ServiceContainerType.IsNullOrEmpty() ? null : Type.GetType(ServiceContainerType),
                IncludeSqlInExceptions          = IncludeSqlInExceptions,
                BuildInParallel                 = BuildInParallel,
                AllowCyclicDatabaseDependencies = AllowCyclicDatabaseDependencies,
                ForcedServerVersion             = ForcedServerVersion,
                Collation                       = Collation,
                ConnectionInitializationSql     = ConnectionInitializationSql,
                MultidatabaseKeys               = MultidatabaseKeys,
                ShareStorageSchemaOverNodes     = ShareStorageSchemaOverNodes,
                EnsureConnectionIsAlive         = EnsureConnectionIsAlive,
                FullTextChangeTrackingMode      = ParseEnum <FullTextChangeTrackingMode>(FullTextChangeTrackingMode),
                VersioningConvention            = VersioningConvention.ToNative()
            };

            foreach (var element in Types)
            {
                config.Types.Register(element.ToNative());
            }
            foreach (var element in Sessions)
            {
                config.Sessions.Add(element.ToNative());
            }
            foreach (var element in MappingRules)
            {
                config.MappingRules.Add(element.ToNative());
            }
            foreach (var element in Databases)
            {
                config.Databases.Add(element.ToNative());
            }
            foreach (var element in KeyGenerators)
            {
                config.KeyGenerators.Add(element.ToNative());
            }
            foreach (var element in IgnoreRules)
            {
                config.IgnoreRules.Add(element.ToNative());
            }

            return(config);
        }
Ejemplo n.º 28
0
            public void ReturnsRightResultForConventionWithSingleConstantWithoutViewPostfix()
            {
                string viewName   = "ExampleVW";
                string convention = string.Format("ViewModels.{0}ViewModel", NamingConvention.ViewName);

                string result = NamingConvention.ResolveViewModelByViewName("MyProject.MyAssembly", viewName, convention);

                Assert.AreEqual("ViewModels.ExampleVWViewModel", result);
            }
Ejemplo n.º 29
0
            public void ReturnsRightResultForConventionWithMultipleConstants()
            {
                string viewName   = "ExampleView";
                string convention = string.Format("{0}.ViewModels.{1}ViewModel", NamingConvention.Assembly, NamingConvention.ViewName);

                string result = NamingConvention.ResolveViewModelByViewName("MyProject.MyAssembly", viewName, convention);

                Assert.AreEqual("MyProject.MyAssembly.ViewModels.ExampleViewModel", result);
            }
Ejemplo n.º 30
0
            public void ReturnsRightResultForConventionWithSingleConstant()
            {
                string viewModelName = "ExampleViewModel";
                string convention    = string.Format("/Views/{0}View.xaml", NamingConvention.ViewModelName);

                string result = NamingConvention.ResolveViewByViewModelName("MyProject.MyAssembly", viewModelName, convention);

                Assert.AreEqual("/Views/ExampleView.xaml", result);
            }
Ejemplo n.º 31
0
            public void ReturnsRightResultForConventionWithoutConstant()
            {
                string viewName   = "ExampleView";
                string convention = "ViewModels.TestViewModel";

                string result = NamingConvention.ResolveViewModelByViewName("MyProject.MyAssembly", viewName, convention);

                Assert.AreEqual("ViewModels.TestViewModel", result);
            }
Ejemplo n.º 32
0
 public void TestCamelCase()
 {
     Assert.True(NamingConvention.GetCamelCase("FOO") == "foo");
     Assert.True(NamingConvention.GetCamelCase("Bar") == "bar");
     Assert.True(NamingConvention.GetCamelCase("zaz") == "zaz");
     Assert.True(NamingConvention.GetCamelCase("FooBarZaz") == "fooBarZaz");
     Assert.True(NamingConvention.GetCamelCase("foo bar zaz") == "fooBarZaz");
     Assert.True(NamingConvention.GetCamelCase("foo_bar_zaz") == "fooBarZaz");
 }
Ejemplo n.º 33
0
        private JSObjectBinder(Type type, JSBindingOptions options, NamingConvention namingConvention)
        {
            if (type == null) throw new ArgumentNullException("type");
            if (!type.IsInterface) throw new ArgumentException("Only interface type allowed.", "type");

            this.type = type;
            this.options = options;
            this.namingConvention = namingConvention;

            this.proxyType = JSObjectTypeBuilder.Create(type, options, namingConvention);
        }
Ejemplo n.º 34
0
        public static string ConvertIdentifier(string name, NamingConvention namingConvention)
        {
            // TODO: complete this...

            if (namingConvention == NamingConvention.None) return name;

            if (char.IsUpper(name[0]))
            {
                return char.ToLowerInvariant(name[0]) + name.Substring(1);
            }
            return name;
        }
Ejemplo n.º 35
0
        public static string ConvertMemberName(string name, NamingConvention namingConvention)
        {
            // it allow names like Some.Member.Access
            // TODO: check for incorrect symbols

            if (!name.Contains('.')) return ConvertIdentifier(name, namingConvention);

            var parts = name.Split('.');

            for (var i = 0; i < parts.Length; i++)
            {
                if (string.IsNullOrEmpty(parts[i])) throw new ArgumentException("name");
                parts[i] = ConvertIdentifier(parts[i], namingConvention);
            }

            return string.Join(".", parts);
        }
Ejemplo n.º 36
0
        public static INamingConvention Create(NamingConvention convention)
        {
            var formatter = new Formatter(DefaultFormatter);

            switch (convention) {
                case NamingConvention.None:
                    break;
                case NamingConvention.PascalCased:
                    formatter = Inflector.Pascalize;
                    break;
                case NamingConvention.CamelCased:
                    formatter = Inflector.Camelize;
                    break;
                case NamingConvention.Underscored:
                    formatter = Inflector.Underscore;
                    break;
            }

            return new InflectorNamingConvention(formatter);
        }
Ejemplo n.º 37
0
        public static Type Create(Type targetType, JSBindingOptions options, NamingConvention namingConvention)
        {
            Initialize();

            // create the type
            TypeBuilder type = module.DefineType(
                string.Format("{0}.{1}Proxy", namespaceName, targetType.FullName),
                TypeAttributes.Public | TypeAttributes.Sealed,
                typeof(JSObjectBase),
                new Type[] { targetType }
                );

            // TODO: properties

            // create members
            foreach (var method in targetType.GetMethods())
            {
                // explicit interface implementation
                MethodBuilder mb = type.DefineMethod(
                        targetType.Name + "." + method.Name,
                        MethodAttributes.Private | MethodAttributes.HideBySig |
                        MethodAttributes.NewSlot | MethodAttributes.Virtual |
                        MethodAttributes.Final,
                        method.ReturnType,
                        method.GetParameters().Select(_ => _.ParameterType).ToArray()
                        );
                type.DefineMethodOverride(mb, method);

                var emit = new EmitHelper(mb.GetILGenerator());
                emit.LdArg(1)
                    .Ret()
                    ;
            }

            return type.CreateType();
        }
 private static string FormatName(string name, NamingConvention naming)
 {
     switch (naming)
     {
         case NamingConvention.Pascal:
             return char.ToUpper(name[0], CultureInfo.InvariantCulture) + name.Substring(1);
         case NamingConvention.Camel:
             return char.ToLower(name[0], CultureInfo.InvariantCulture) + name.Substring(1);
         case NamingConvention.Upper:
             return name.ToUpper(CultureInfo.InvariantCulture);
         case NamingConvention.Lower:
             return name.ToLower(CultureInfo.InvariantCulture);
         default:
             return name;
     }
 }
        internal static SyntaxToken WithConvention(this SyntaxToken identifier, NamingConvention namingConvention)
        {
            // int @class = 5;
            if (identifier.IsVerbatimIdentifier())
            {
                return identifier;
            }

            // int cl\u0061ss = 5;
            if (identifier.Text.Contains("\\"))
            {
                return identifier;
            }

            var originalValue = identifier.ValueText;
            string newValue;

            switch (namingConvention)
            {
                case NamingConvention.LowerCamelCase:
                    newValue = GetLowerCamelCaseIdentifier(originalValue);
                    break;
                case NamingConvention.UpperCamelCase:
                    newValue = GetUpperCamelCaseIdentifier(originalValue);
                    break;
                case NamingConvention.UnderscoreLowerCamelCase:
                    newValue = GetUnderscoreLowerCamelCaseIdentifier(originalValue);
                    break;
                case NamingConvention.InterfacePrefixUpperCamelCase:
                    newValue = GetInterfacePrefixUpperCamelCaseIdentifier(originalValue);
                    break;
                default:
                    throw new ArgumentException(nameof(namingConvention));
            }

            return SyntaxFactory.Identifier(identifier.LeadingTrivia, newValue, identifier.TrailingTrivia);
        }
 public JsonMemberNamingConventionAttribute(NamingConvention convention)
     : this(convention, UnderscoreConvention.None)
 {
 }
Ejemplo n.º 41
0
 internal static NamingStrategy GetStrategy(NamingConvention convention)
 {
     switch (convention) {
         case NamingConvention.Default: return Default;
         case NamingConvention.LowerCase: return LowerCase;
         case NamingConvention.CamelCase: return CamelCase;
         case NamingConvention.UpperCase: return UpperCase;
         default: throw new NotSupportedException ("NamingConvention " + convention.ToString () + " is not supported.");
     }
 }
 public JsonMemberNamingConventionAttribute(NamingConvention convention)
 {
     _convention = convention;
 }
 /// <summary>
 /// Specify options as enum.
 /// </summary>
 /// <param name="namingConvention"></param>
 /// <param name="compareMethod"></param>
 public NotifyAttribute(NamingConvention namingConvention = default(NamingConvention), CompareMethod compareMethod = default(CompareMethod)) { }
 public JsonMemberNamingConventionAttribute(NamingConvention naming, UnderscoreConvention underscores)
 {
     _convention = naming;
     _underscores = underscores;
 }
Ejemplo n.º 45
0
 public JSBindAttribute(NamingConvention namingConvention)
     : this(true, namingConvention)
 {
 }
 private static void TestNamingCase(string baseName, NamingConvention testCase, string expected) 
 {
     JsonMemberNamingConventionAttribute attribute = new JsonMemberNamingConventionAttribute(testCase);
     TestPropertyDescriptor property = CreateTestProperty(baseName);
     IPropertyDescriptorCustomization customization = attribute;
     
     customization.Apply(property);
     
     Assert.AreEqual(expected, property.CustomizedName);
 }
Ejemplo n.º 47
0
 public JSBindAttribute(bool visible, NamingConvention namingConvention)
 {
     this.visible = visible;
     this.namingConvention = namingConvention;
 }
Ejemplo n.º 48
0
 public void Render(object data, TextWriter writer, TemplateLocator templateLocator,
     NamingConvention namingConvention)
 {
     Render(data, writer, templateLocator,
         NamingConventionFactory.Create(namingConvention));
 }
 private void CheckNaming(SyntaxToken currentIdentifier, string memberType, NamingConvention convention, SyntaxNodeAnalysisContext context)
 {
     var conventionedIdentifier = currentIdentifier.WithConvention(convention);
     if (conventionedIdentifier.Text != currentIdentifier.Text)
     {
         context.ReportDiagnostic(Diagnostic.Create(Rule, currentIdentifier.GetLocation(), memberType, currentIdentifier.Text, conventionedIdentifier.Text));
     }
 }