Beispiel #1
0
        public void WriteWithNullJsonTextWriter()
        {
            JsonTextWriter writer         = null;
            ResourceSchema resourceSchema = new ResourceSchema();

            Assert.Throws <ArgumentNullException>(() => { ResourceSchemaWriter.Write(writer, resourceSchema); });
        }
        private static async Task GetResourceSchema(string customerName, string resourceName, Uri serverUrl)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = serverUrl;
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                authManager.credService.AddEncryptedCredentialsToClient(client, authManager.UserName, authManager.EncryptedPassword, authManager.ClientKey);

                HttpResponseMessage response = await client.GetAsync("_/" + customerName + "/" + resourceName);

                if (response.IsSuccessStatusCode)
                {
                    ResourceSchema schema = await response.Content.ReadAsAsync <ResourceSchema>();

                    string json = JsonConvert.SerializeObject(schema, Formatting.Indented);
                    Console.WriteLine(json);
                    Console.WriteLine("Get Schema successful");
                }
                else
                {
                    Console.WriteLine("Get Schema failed");
                }
            }
        }
 public void WriteWithEmptyResourceSchema()
 {
     StringWriter stringWriter = new StringWriter();
     JsonTextWriter writer = new JsonTextWriter(stringWriter);
     ResourceSchema resourceSchema = new ResourceSchema();
     ResourceSchemaWriter.Write(writer, resourceSchema);
     Assert.Equal("{}", stringWriter.ToString());
 }
Beispiel #4
0
        public void WriteWithJsonTextWriterAndNullResourceSchema()
        {
            StringWriter   stringWriter   = new StringWriter();
            JsonTextWriter writer         = new JsonTextWriter(stringWriter);
            ResourceSchema resourceSchema = null;

            Assert.Throws <ArgumentNullException>(() => { ResourceSchemaWriter.Write(writer, resourceSchema); });
        }
Beispiel #5
0
        public void WriteWithEmptyResourceSchema()
        {
            StringWriter   stringWriter   = new StringWriter();
            JsonTextWriter writer         = new JsonTextWriter(stringWriter);
            ResourceSchema resourceSchema = new ResourceSchema();

            ResourceSchemaWriter.Write(writer, resourceSchema);
            Assert.Equal("{}", stringWriter.ToString());
        }
Beispiel #6
0
        public void ParseWithCodeModelWithCreateResourceMethod()
        {
            CodeModel codeModel = New <CodeModel>();

            codeModel.ApiVersion = "2016-01-01";

            Parameter body = New <Parameter>(new
            {
                Location = ParameterLocation.Body,
                Type     = New <CompositeType>(),
            });

            CompositeType responseBody = New <CompositeType>();

            responseBody.Extensions.Add("x-ms-azure-resource", true);

            const string url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Mock.Provider/mockResourceNames/{mockResourceName}";

            Method method = New <Method>(new
            {
                HttpMethod = HttpMethod.Put,
                ReturnType = new Response(responseBody, null),
                Url        = url,
            });

            method.Add(body);

            codeModel.Add(method);

            var schemas = ResourceSchemaParser.Parse(codeModel, codeModel.ApiVersion, false);

            Assert.NotNull(schemas);
            Assert.Equal(1, schemas.Count);

            ResourceSchema schema = schemas["Mock.Provider"];

            Assert.Equal("https://schema.management.azure.com/schemas/2016-01-01/Mock.Provider.json#", schema.Id);
            Assert.Equal("http://json-schema.org/draft-04/schema#", schema.Schema);
            Assert.Equal("Mock.Provider", schema.Title);
            Assert.Equal("Mock Provider Resource Types", schema.Description);
            Assert.Equal(1, schema.ResourceDefinitions.Count);
            Assert.Equal("mockResourceNames", schema.ResourceDefinitions.Keys.Single());
            Assert.Equal(
                new JsonSchema()
            {
                JsonType    = "object",
                Description = "Mock.Provider/mockResourceNames"
            }
                .AddProperty("type", JsonSchema.CreateSingleValuedEnum("Mock.Provider/mockResourceNames"), true)
                .AddProperty("apiVersion", JsonSchema.CreateSingleValuedEnum("2016-01-01"), true),
                schema.ResourceDefinitions["mockResourceNames"].Schema);
            Assert.NotNull(schema.Definitions);
            Assert.Equal(0, schema.Definitions.Count);
        }
        public void ParseWithServiceClientWithCreateResourceMethod()
        {
            ServiceClient serviceClient = new ServiceClient();

            serviceClient.ApiVersion = "2016-01-01";

            Parameter body = new Parameter()
            {
                Location = ParameterLocation.Body,
                Type     = new CompositeType(),
            };

            CompositeType responseBody = new CompositeType();

            responseBody.Extensions.Add("x-ms-azure-resource", true);

            const string url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Mock.Provider/mockResourceNames/{mockResourceName}";

            Method method = new Method()
            {
                HttpMethod = HttpMethod.Put,
                ReturnType = new Response(responseBody, null),
                Url        = url,
            };

            method.Parameters.Add(body);

            serviceClient.Methods.Add(method);

            IDictionary <string, ResourceSchema> schemas = ResourceSchemaParser.Parse(serviceClient);

            Assert.NotNull(schemas);
            Assert.Equal(1, schemas.Count);

            ResourceSchema schema = schemas["Mock.Provider"];

            Assert.Equal("http://schema.management.azure.com/schemas/2016-01-01/Mock.Provider.json#", schema.Id);
            Assert.Equal("http://json-schema.org/draft-04/schema#", schema.Schema);
            Assert.Equal("Mock.Provider", schema.Title);
            Assert.Equal("Mock Provider Resource Types", schema.Description);
            Assert.Equal(1, schema.ResourceDefinitions.Count);
            Assert.Equal("mockResourceNames", schema.ResourceDefinitions.Keys.Single());
            Assert.Equal(
                new JsonSchema()
            {
                JsonType    = "object",
                Description = "Mock.Provider/mockResourceNames"
            }
                .AddProperty("type", JsonSchema.CreateStringEnum("Mock.Provider/mockResourceNames"), true)
                .AddProperty("apiVersion", JsonSchema.CreateStringEnum("2016-01-01"), true),
                schema.ResourceDefinitions["mockResourceNames"]);
            Assert.NotNull(schema.Definitions);
            Assert.Equal(0, schema.Definitions.Count);
        }
        public void WriteWithId()
        {
            StringWriter stringWriter = new StringWriter();
            JsonTextWriter writer = new JsonTextWriter(stringWriter);
            writer.QuoteChar = '\'';

            ResourceSchema resourceSchema = new ResourceSchema();
            resourceSchema.Id = "MockId";

            ResourceSchemaWriter.Write(writer, resourceSchema);
            Assert.Equal("{'id':'MockId'}", stringWriter.ToString());
        }
        public void WriteWithTitle()
        {
            StringWriter stringWriter = new StringWriter();
            JsonTextWriter writer = new JsonTextWriter(stringWriter);
            writer.QuoteChar = '\'';

            ResourceSchema resourceSchema = new ResourceSchema();
            resourceSchema.Schema = "MockSchema";
            resourceSchema.Title = "MockTitle";

            ResourceSchemaWriter.Write(writer, resourceSchema);
            Assert.Equal("{'$schema':'MockSchema','title':'MockTitle'}", stringWriter.ToString());
        }
Beispiel #10
0
        public void WriteWithId()
        {
            StringWriter   stringWriter = new StringWriter();
            JsonTextWriter writer       = new JsonTextWriter(stringWriter);

            writer.QuoteChar = '\'';

            ResourceSchema resourceSchema = new ResourceSchema();

            resourceSchema.Id = "MockId";

            ResourceSchemaWriter.Write(writer, resourceSchema);
            Assert.Equal("{'id':'MockId'}", stringWriter.ToString());
        }
Beispiel #11
0
        public void ParseWithServiceClientWithCreateResourceMethod()
        {
            ServiceClient serviceClient = new ServiceClient();

            Parameter body = new Parameter()
            {
                Location = ParameterLocation.Body,
                Type     = new CompositeType(),
            };

            CompositeType responseBody = new CompositeType();

            responseBody.Extensions.Add("x-ms-azure-resource", true);

            const string url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Mock.Provider/mockResourceNames/{mockResourceName}";

            Method method = CreateMethod(body: body, responseBody: responseBody, url: url);

            serviceClient.Methods.Add(method);

            IDictionary <string, ResourceSchema> schemas = ResourceSchemaParser.Parse(serviceClient);

            Assert.NotNull(schemas);
            Assert.Equal(1, schemas.Count);

            ResourceSchema schema = schemas["Mock.Provider"];

            Assert.Null(schema.Id);
            Assert.Equal("http://json-schema.org/draft-04/schema#", schema.Schema);
            Assert.Equal("Mock.Provider", schema.Title);
            Assert.Equal("Mock Provider Resource Types", schema.Description);
            Assert.Equal(1, schema.ResourceDefinitions.Count);
            Assert.Equal("mockResourceNames", schema.ResourceDefinitions.Keys.Single());
            Assert.Equal(
                new JsonSchema()
            {
                JsonType    = "object",
                Description = "Mock.Provider/mockResourceNames"
            }
                .AddProperty("type", new JsonSchema()
            {
                JsonType = "string"
            }
                             .AddEnum("Mock.Provider/mockResourceNames"),
                             true),
                schema.ResourceDefinitions["mockResourceNames"]);
            Assert.NotNull(schema.Definitions);
            Assert.Equal(0, schema.Definitions.Count);
        }
Beispiel #12
0
        public void WriteWithDescription()
        {
            StringWriter   stringWriter = new StringWriter();
            JsonTextWriter writer       = new JsonTextWriter(stringWriter);

            writer.QuoteChar = '\'';

            ResourceSchema resourceSchema = new ResourceSchema();

            resourceSchema.Title       = "MockTitle";
            resourceSchema.Description = "MockDescription";

            ResourceSchemaWriter.Write(writer, resourceSchema);
            Assert.Equal("{'title':'MockTitle','description':'MockDescription'}", stringWriter.ToString());
        }
Beispiel #13
0
        public void WriteWithOneDefinition()
        {
            StringWriter   stringWriter = new StringWriter();
            JsonTextWriter writer       = new JsonTextWriter(stringWriter);

            writer.QuoteChar = '\'';

            ResourceSchema resourceSchema = new ResourceSchema();

            resourceSchema.AddResourceDefinition("mockResource", new JsonSchema());
            resourceSchema.AddDefinition("mockDefinition", new JsonSchema());

            ResourceSchemaWriter.Write(writer, resourceSchema);
            Assert.Equal("{'resourceDefinitions':{'mockResource':{}},'definitions':{'mockDefinition':{}}}", stringWriter.ToString());
        }
Beispiel #14
0
        public void WriteWithTitle()
        {
            StringWriter   stringWriter = new StringWriter();
            JsonTextWriter writer       = new JsonTextWriter(stringWriter);

            writer.QuoteChar = '\'';

            ResourceSchema resourceSchema = new ResourceSchema();

            resourceSchema.Schema = "MockSchema";
            resourceSchema.Title  = "MockTitle";

            ResourceSchemaWriter.Write(writer, resourceSchema);
            Assert.Equal("{'$schema':'MockSchema','title':'MockTitle'}", stringWriter.ToString());
        }
Beispiel #15
0
        private Dictionary <string, ScriptBlock> GetDslKeywordDefinitions(ResourceSchema resourceSchema)
        {
            if (resourceSchema.Discriminator is null)
            {
                return(resourceSchema.KeywordDefinitions);
            }

            if (!_dynamicParameters.TryGetValue(resourceSchema.Discriminator, out RuntimeDefinedParameter discriminatorParameter))
            {
                // This should be impossible since the parameter is mandatory, but nevertheless...
                var exception = new ArgumentException($"The '{resourceSchema.Discriminator}' parameter must be provided");
                this.ThrowTerminatingError(exception, "DiscriminatorParameterMissing", ErrorCategory.InvalidArgument, target: this);
                return(null);
            }

            string discriminatorValue;

            try
            {
                discriminatorValue = ((IArmString)discriminatorParameter.Value).CoerceToString();
            }
            catch (Exception e)
            {
                this.ThrowTerminatingError(e, "InvalidDiscriminatorType", ErrorCategory.InvalidArgument, target: discriminatorParameter);
                return(null);
            }

            if (!resourceSchema.DiscriminatedKeywords.TryGetValue(discriminatorValue, out Dictionary <string, ScriptBlock> discriminatedKeywords))
            {
                // This shouldn't be possible due to the ValidateSet attribute, but we handle it anyway
                this.ThrowTerminatingError(
                    new KeyNotFoundException($"'{discriminatorValue}' is not a valid value for parameter '{resourceSchema.Discriminator}'"),
                    "InvalidDiscriminatorValue",
                    ErrorCategory.InvalidArgument,
                    target: discriminatorValue);
                return(null);
            }

            var keywords = new Dictionary <string, ScriptBlock>(resourceSchema.KeywordDefinitions, StringComparer.OrdinalIgnoreCase);

            foreach (KeyValuePair <string, ScriptBlock> keywordDefinition in discriminatedKeywords)
            {
                keywords[keywordDefinition.Key] = keywordDefinition.Value;
            }

            return(keywords);
        }
        private static void CreatePublicFacingTables(string connectionString, int timeout, int maxDegreeOfParallelism, Pipelines pipelineOptions)
        {
            {
                // resources...
                var schema = new ResourceSchema(connectionString, timeout, maxDegreeOfParallelism, pipelineOptions);
                schema.CreateTables();
            }

            {
                // attendance...
                var schema = new AttendanceSchema(connectionString, timeout, maxDegreeOfParallelism, pipelineOptions);
                schema.CreateTables();
            }

            {
                // bookings...
                var schema = new BookingSchema(connectionString, timeout, maxDegreeOfParallelism, pipelineOptions);
                schema.CreateTables();
            }

            {
                // events...
                var schema = new EventSchema(connectionString, timeout, maxDegreeOfParallelism, pipelineOptions);
                schema.CreateTables();
            }

            {
                // exams...
                var schema = new ExamSchema(connectionString, timeout, maxDegreeOfParallelism, pipelineOptions);
                schema.CreateTables();
            }

            {
                // membership...
                var schema = new MembershipSchema(connectionString, timeout, maxDegreeOfParallelism, pipelineOptions);
                schema.CreateTables();
            }

            {
                // misc...
                var schema = new MiscSchema(connectionString, timeout, maxDegreeOfParallelism, pipelineOptions);
                schema.CreateTables();
            }
        }
        private static async Task PutResourceSchema(string company, string resource, ResourceSchema schema, Uri serverUrl)
        {
            using (var client = new HttpClient()) {
                client.BaseAddress = serverUrl;
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                authManager.credService.AddEncryptedCredentialsToClient(client, authManager.UserName, authManager.EncryptedPassword, authManager.ClientKey);

                HttpResponseMessage response = await client.PutAsJsonAsync("_/" + company + "/" + resource, schema);

                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Schema load successful");
                }
                else
                {
                    Console.WriteLine("Schema load failed");
                }
            }
        }
Beispiel #18
0
        private bool TryGetResourceSchema(out ResourceSchema resourceSchema)
        {
            if (_resourceSchema is not null)
            {
                resourceSchema = _resourceSchema;
                return(true);
            }

            if (ResourceIndex.SharedInstance.TryGetResourceSchema(
                    Namespace?.CoerceToString(),
                    Type?.CoerceToString(),
                    ApiVersion?.CoerceToString(),
                    out resourceSchema))
            {
                _resourceSchema = resourceSchema;
                return(true);
            }

            return(false);
        }
        public void WriteWithDescription()
        {
            StringWriter stringWriter = new StringWriter();
            JsonTextWriter writer = new JsonTextWriter(stringWriter);
            writer.QuoteChar = '\'';

            ResourceSchema resourceSchema = new ResourceSchema();
            resourceSchema.Title = "MockTitle";
            resourceSchema.Description = "MockDescription";

            ResourceSchemaWriter.Write(writer, resourceSchema);
            Assert.Equal("{'title':'MockTitle','description':'MockDescription'}", stringWriter.ToString());
        }
        public void WriteWithOneResourceDefinition()
        {
            StringWriter stringWriter = new StringWriter();
            JsonTextWriter writer = new JsonTextWriter(stringWriter);
            writer.QuoteChar = '\'';

            ResourceSchema resourceSchema = new ResourceSchema();
            resourceSchema.Description = "MockDescription";
            resourceSchema.AddResourceDefinition("mockResource", new JsonSchema());

            ResourceSchemaWriter.Write(writer, resourceSchema);
            Assert.Equal("{'description':'MockDescription','resourceDefinitions':{'mockResource':{}}}", stringWriter.ToString());
        }
Beispiel #21
0
        public static IServiceCollection AddJsonApi(this IServiceCollection services, IMvcBuilder mvcBuilder,
                                                    ContainerBuilder containerBuilder, IConfiguration configuration,
                                                    Action <IMapperConfigurationExpression> configure)
        {
            // setup auto mapper
            var    siteOptions = configuration.GetOptions <SiteOptions>();
            string siteKey     = siteOptions.Id;

            services.AddAutoMapper(mapConfig =>
            {
                mapConfig.ValidateInlineMaps = false;
                mapConfig.AddProfile(new XFMapperProfile(siteKey));
                configure(mapConfig);
            }, new Assembly[0]);

            JsonApiOptions.ResourceNameFormatter = new XFResourceNameFormatter();
            var graphBuilder = new XFResourceGraphBuilder();
            // find all resources
            var assemblies = new[] { Assembly.GetEntryAssembly(), Assembly.GetExecutingAssembly() };

            ResourceDescriptor[] resourceDescriptors = assemblies
                                                       .SelectMany(a => ResourceTypeLocator.GetIdentifableTypes(a)).ToArray();
            foreach (ResourceDescriptor resourceDescriptor in resourceDescriptors)
            {
                // add resource to graph
                string resourceName = JsonApiOptions.ResourceNameFormatter.FormatResourceName(
                    resourceDescriptor.ResourceType);
                graphBuilder.AddResource(resourceDescriptor.ResourceType, resourceDescriptor.IdType, resourceName);

                // register resource service
                Type   serviceInterfaceType = typeof(IResourceService <,>);
                Type[] genericArguments     = new[] { resourceDescriptor.ResourceType, resourceDescriptor.IdType };
                Type   serviceType          = ResourceTypeLocator.GetGenericInterfaceImplementation(
                    resourceDescriptor.ResourceType.Assembly, serviceInterfaceType, genericArguments);
                if (serviceType != null)
                {
                    RegisterResourceService(containerBuilder, serviceType);
                }
            }

            var jsonApiOptions = new JsonApiOptions
            {
                Namespace               = XForgeConstants.JsonApiNamespace,
                ResourceGraph           = graphBuilder.Build(),
                AllowClientGeneratedIds = true,
                IncludeTotalRecordCount = true
            };

            jsonApiOptions.SerializerSettings.ContractResolver = new JsonApiContractResolver();
            jsonApiOptions.SerializerSettings.Converters.Add(new StringEnumConverter());

            mvcBuilder.AddMvcOptions(options =>
            {
                options.Filters.Add(typeof(JsonApiExceptionFilter));
                options.Filters.Add(typeof(TypeMatchFilter));
                SerializeAsJsonApi(options, jsonApiOptions);
            });

            services.AddJsonApiInternals(jsonApiOptions);
            services.AddScoped <IDocumentBuilder, XFDocumentBuilder>();

            // generate resource schema
            var schema = ResourceSchema.Build(jsonApiOptions.ResourceGraph, resourceDescriptors);

            services.AddSingleton(schema);

            return(services);
        }
 public SchemaController(ResourceSchema schema)
 {
     _schema = schema;
 }
Beispiel #23
0
 protected ResourceKeywordCache(ResourceSchema resource)
 {
     Resource = resource;
 }
 public ObjectResourceKeywordCache(ResourceSchema resource)
     : base(resource)
 {
     _keywordsLazy = new Lazy <IReadOnlyDictionary <string, DslKeywordSchema> >(GetKeywordTableFromResource);
 }
        private static void CreateResource(string schema, string customer, string resource, Uri serverUrl)
        {
            // map datatypes from the source DB into the allowed data types
            // Boolean, DateTime, Integer, Float and String are the only supported datatypes.
            // To use a different source DB, you may need to add datatype mappings to this section

            // The AdventureWorks2012 DB Person schema contains a 'geography' sql type which does not map to a supported datatype
            // In order to use this schema, a column with this data type was dropped:
            //      'ALTER table Person.Address drop column SpatialLocation'

            Dictionary <string, ColumnSchemaType> sqlToColumnTypes;

            sqlToColumnTypes = new Dictionary <string, ColumnSchemaType>();
            sqlToColumnTypes.Add("bit", ColumnSchemaType.Boolean);
            sqlToColumnTypes.Add("datetime", ColumnSchemaType.DateTime);
            sqlToColumnTypes.Add("int", ColumnSchemaType.Integer);
            sqlToColumnTypes.Add("bigint", ColumnSchemaType.Integer);
            sqlToColumnTypes.Add("float", ColumnSchemaType.Float);
            sqlToColumnTypes.Add("nchar", ColumnSchemaType.String);
            sqlToColumnTypes.Add("nvarchar", ColumnSchemaType.String);
            sqlToColumnTypes.Add("varchar", ColumnSchemaType.String);
            sqlToColumnTypes.Add("xml", ColumnSchemaType.String);
            sqlToColumnTypes.Add("uniqueidentifier", ColumnSchemaType.String);

            using (var conn = new SqlConnection(DBConectionString))
            {
                conn.Open();

                ResourceSchema      resourceSchema        = new ResourceSchema();     // the schema used to initialize the Resource
                List <TableSchema>  parsedTableSchemaList = new List <TableSchema>(); // schemas created for each of the tables
                TableSchema         parsedTableSchema;                                // table schema created for a single table in the DB
                List <ColumnSchema> parsedColumnSchemaList;                           // column schema created for a single table in the DB
                ColumnSchema        parsedColumnSchema;                               // schema created for a single column
                DataTable           sourceColumns;                                    // columns in a single table in the source DB

                // Get the schema of the source DB into a DataTable for parsing
                DataTable sourceSchema = conn.GetSchema("Tables", new string[] { null, schema, null, "BASE TABLE" });

                // each sourceTable represents a table in the source DB
                foreach (DataRow sourceTable in sourceSchema.Rows)
                {
#if DEBUG
                    Console.WriteLine("Table Name ==========================");
                    Console.WriteLine(sourceTable["TABLE_NAME"]);
#endif
                    parsedTableSchema = new TableSchema()
                    {
                        Name = sourceTable["TABLE_NAME"].ToString()
                    };
                    parsedColumnSchemaList = new List <ColumnSchema>();
                    sourceColumns          = conn.GetSchema("Columns", new string[] { null, schema, sourceTable["TABLE_NAME"].ToString() });

                    // Get a list of the source DB table's Primary Key columns
                    List <string> primayKeyColumnNames = GetPrimaryKeyColumns(conn, sourceTable["TABLE_NAME"].ToString());

                    // Create a schema for each column in the table containing the name, data type and primary key flag
#if DEBUG
                    Console.WriteLine("Columns ===============================");
#endif
                    foreach (DataRow r in sourceColumns.Rows)
                    {
#if DEBUG
                        Console.WriteLine("{0}: {1}", r["COLUMN_NAME"], r["DATA_TYPE"]);
#endif
                        try {
                            parsedColumnSchema = new ColumnSchema()
                            {
                                Name = r["COLUMN_NAME"].ToString(), Type = sqlToColumnTypes[r["DATA_TYPE"].ToString()]
                            };
                        } catch (Exception) {
                            Console.WriteLine("\n\nSchema Load Failed.");
                            Console.WriteLine("There is no mapping for Datatype: '{0}'; found in Table: '{1}', Column: '{2}' ",
                                              r["DATA_TYPE"], sourceTable["TABLE_NAME"], r["COLUMN_NAME"]);
                            Console.WriteLine("Please add a mapping in the 'sqlToColumnTypes' Dictionary.");
                            return;
                        }
                        // mark Primary key columns
                        if (primayKeyColumnNames.Contains(r["COLUMN_NAME"].ToString()))
                        {
                            parsedColumnSchema.Key = true;
#if DEBUG
                            Console.WriteLine("{0} is a Primary Key", r["COLUMN_NAME"]);
#endif
                        }
                        // Add created schema for column
                        parsedColumnSchemaList.Add(parsedColumnSchema);
                    }

                    // Add the list of column schemas to the table schema
                    parsedTableSchema.Columns = parsedColumnSchemaList;

                    // Add the created table schema to the list of tables
                    parsedTableSchemaList.Add(parsedTableSchema);
                }
                // Use the created list of tables schemas as the schema for the Resource to be created
                resourceSchema.Tables = parsedTableSchemaList;

                // Send the Resource as JSON to the MiCo Server to create the Resource
#if DEBUG
                var json = JsonConvert.SerializeObject(resourceSchema, Newtonsoft.Json.Formatting.Indented);
                Console.WriteLine(json);
#endif
                Console.WriteLine("Sending 'Put Schema' request to server...");
                PutResourceSchema(customer, resource, resourceSchema, serverUrl).Wait();;
            }
        }
 public void WriteWithNullJsonTextWriter()
 {
     JsonTextWriter writer = null;
     ResourceSchema resourceSchema = new ResourceSchema();
     Assert.Throws<ArgumentNullException>(() => { ResourceSchemaWriter.Write(writer, resourceSchema); });
 }
        private static void CreateResource(string company, string resource, Uri serverUrl)
        {
            // Map datatypes from the source DB into the allowed data types
            // Boolean, DateTime, Integer, Float and String are the only supported datatypes for MiCo Replication Server Resources.
            // These data types were included to import the Oracle Sample 'HR' database
            // To use a different source DB, you may need to add datatype mappings to this section

            Dictionary <string, ColumnSchemaType> sqlToColumnTypes;

            sqlToColumnTypes = new Dictionary <string, ColumnSchemaType>();

            sqlToColumnTypes.Add("bit", ColumnSchemaType.Boolean);
            sqlToColumnTypes.Add("datetime", ColumnSchemaType.DateTime);
            sqlToColumnTypes.Add("int", ColumnSchemaType.Integer);
            sqlToColumnTypes.Add("bigint", ColumnSchemaType.Integer);
            sqlToColumnTypes.Add("float", ColumnSchemaType.Float);
            sqlToColumnTypes.Add("nchar", ColumnSchemaType.String);
            sqlToColumnTypes.Add("nvarchar", ColumnSchemaType.String);
            sqlToColumnTypes.Add("varchar", ColumnSchemaType.String);
            sqlToColumnTypes.Add("xml", ColumnSchemaType.String);
            sqlToColumnTypes.Add("uniqueidentifier", ColumnSchemaType.String);
            sqlToColumnTypes.Add("char", ColumnSchemaType.String);
            sqlToColumnTypes.Add("varchar2", ColumnSchemaType.String);

            // Oracle's 'NUMBER' datatype may be an fixed or floating point number.
            // There is a test later in this code to set columns with fixed point NUMBERS to the Integer datatype.
            // Mapping a number to float will support up to 64 bits when replicated into sqlite db
            sqlToColumnTypes.Add("number", ColumnSchemaType.Float);
            sqlToColumnTypes.Add("date", ColumnSchemaType.DateTime);

            using (var conn = new OracleConnection(DBConectionString)) {
                conn.Open();

                ResourceSchema      resourceSchema        = new ResourceSchema();     // the schema used to initialize the Resource
                List <TableSchema>  parsedTableSchemaList = new List <TableSchema>(); // schemas created for each of the tables
                TableSchema         parsedTableSchema;                                // table schema created for a single table in the DB
                List <ColumnSchema> parsedColumnSchemaList;                           // column schema created for a single table in the DB
                ColumnSchema        parsedColumnSchema;                               // schema created for a single column
                DataTable           sourceColumns;                                    // columns in a single table in the source DB

                // Get the schema of the source DB into a DataTable for parsing
                // the tables collection has 3 possible ordered restrictions: owner, table name and column name
                string[] restrictions = new string[2];
                restrictions[0] = "HR";
                DataTable sourceSchema = conn.GetSchema("Tables", restrictions);

                // each sourceTable represents a table in the source DB
                foreach (DataRow sourceTable in sourceSchema.Rows)
                {
#if DEBUG
                    Console.WriteLine("Table Name ==========================");
                    Console.WriteLine(sourceTable["TABLE_NAME"]);
#endif
                    parsedTableSchema = new TableSchema()
                    {
                        Name = sourceTable["TABLE_NAME"].ToString()
                    };
                    parsedColumnSchemaList = new List <ColumnSchema>();
                    sourceColumns          = conn.GetSchema("Columns", new string[] { "HR", sourceTable["TABLE_NAME"].ToString(), null });

                    // Get a list of the source DB table's Primary Key column names
                    List <string> primayKeyColumnNames = GetPrimaryKeyColumnNames(conn, sourceTable["TABLE_NAME"].ToString());

                    // Create a schema for each column in the table containing the name, data type and primary key flag
                    // TODO: show error message when encountering non-matching types
#if DEBUG
                    Console.WriteLine("Columns ===============================");
#endif
                    foreach (DataRow r in sourceColumns.Rows)
                    {
#if DEBUG
                        if (r["DATATYPE"].ToString() == "NUMBER")
                        {
                            Console.WriteLine("{0}: {1} ({2}, {3})", r["COLUMN_NAME"], r["DATATYPE"], r["PRECISION"], r["SCALE"]);
                        }
                        else
                        {
                            Console.WriteLine("{0}: {1}", r["COLUMN_NAME"], r["DATATYPE"]);
                        }
#endif
                        try {
                            // check for fixed point NUMBERS - no precision or scale
                            if (r["DATATYPE"].ToString() == "NUMBER" && (!(r["PRECISION"] is DBNull) || !(r["SCALE"] is DBNull)))
                            {
                                parsedColumnSchema = new ColumnSchema()
                                {
                                    Name = r["COLUMN_NAME"].ToString(), Type = ColumnSchemaType.Integer
                                };
                            }
                            else
                            {
                                parsedColumnSchema = new ColumnSchema()
                                {
                                    Name = r["COLUMN_NAME"].ToString(), Type = sqlToColumnTypes[r["DATATYPE"].ToString().ToLower()]
                                };
                            }
                        } catch (Exception) {
                            Console.WriteLine("\n\nSchema Load Failed.");
                            Console.WriteLine("There is no mapping for Datatype: '{0}'; found in Table: '{1}', Column: '{2}' ",
                                              r["DATATYPE"], sourceTable["TABLE_NAME"], r["COLUMN_NAME"]);
                            Console.WriteLine("Please add a mapping in the 'sqlToColumnTypes' Dictionary.");
                            return;
                        }
                        // mark Primary key columns
                        if (primayKeyColumnNames.Contains(r["COLUMN_NAME"].ToString()))
                        {
#if DEBUG
                            Console.WriteLine("{0} is a Primary Key", r["COLUMN_NAME"]);
#endif
                            parsedColumnSchema.Key = true;
                        }
                        // Add created schema for column
                        parsedColumnSchemaList.Add(parsedColumnSchema);
                    }

                    // Add the list of column schemas to the table schema
                    parsedTableSchema.Columns = parsedColumnSchemaList;

                    // Add the created table schema to the list of tables
                    parsedTableSchemaList.Add(parsedTableSchema);
                }
                // Use the created list of tables schemas as the schema for the Resource to be created
                resourceSchema.Tables = parsedTableSchemaList;

                // Send the Resource as JSON to the MiCo Server to create the Resource
#if DEBUG
                var json = JsonConvert.SerializeObject(resourceSchema, Newtonsoft.Json.Formatting.Indented);
                Console.WriteLine(json);
#endif
                Console.WriteLine("Sending 'Put Schema' request to server...");
                PutResourceSchema(company, resource, resourceSchema, serverUrl).Wait();
            }
        }
Beispiel #28
0
 public DiscriminatedResourceKeywordCache(ResourceSchema resource)
     : base(resource)
 {
     _discriminatedKeywordTables = new ConcurrentDictionary <string, IReadOnlyDictionary <string, DslKeywordSchema> >();
     _commonKeywordsLazy         = new Lazy <Dictionary <string, DslKeywordSchema> >(BuildCommonKeywordDictionary);
 }