/// <summary>
        /// Writes the messages section of a protocol definition
        /// </summary>
        /// <param name="writer">writer</param>
        /// <param name="names">list of names written</param>
        /// <param name="encspace">enclosing namespace</param>
        internal void writeJson(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace)
        {
            writer.WriteStartObject();
            JsonHelper.writeIfNotNullOrEmpty(writer, "doc", this.Doc);

            if (null != this.Request)
                this.Request.WriteJsonFields(writer, names, null);

            if (null != this.Response)
            {
                writer.WritePropertyName("response");
                Response.WriteJson(writer, names, encspace);
            }

            if (null != this.Error)
            {
                writer.WritePropertyName("errors");
                this.Error.WriteJson(writer, names, encspace);
            }

            if (null != Oneway)
            {
                writer.WritePropertyName("one-way");
                writer.WriteValue(Oneway);
            }

            writer.WriteEndObject();
        }
Exemple #2
0
        public virtual EnsureSchemaStatus TryEnsureSchema(Type type, bool force, out Exception ex, ILogger logger = null)
        {
            EnsureSchemaStatus result = EnsureSchemaStatus.Invalid;

            ex = null;
            try
            {
                string schemaName = Dao.RealConnectionName(type);
                if (!SchemaNames.Contains(schemaName) || force)
                {
                    _schemaNames.Add(schemaName);
                    SchemaWriter schema = ServiceProvider.Get <SchemaWriter>();
                    schema.WriteSchemaScript(type);
                    ExecuteSql(schema, ServiceProvider.Get <IParameterBuilder>());
                    result = EnsureSchemaStatus.Success;
                }
                else
                {
                    result = EnsureSchemaStatus.AlreadyDone;
                }
            }
            catch (Exception e)
            {
                ex     = e;
                result = EnsureSchemaStatus.Error;
                logger = logger ?? Log.Default;
                logger.AddEntry("Non fatal error occurred trying to write schema for type {0}: {1}", LogEventType.Warning, ex, type.Name, ex.Message);
            }
            return(result);
        }
        public static Schema Create(
            DocumentNode schemaDocument,
            Action <ISchemaConfiguration> configure,
            bool strict,
            IServiceProvider services)
        {
            if (schemaDocument == null)
            {
                throw new ArgumentNullException(nameof(schemaDocument));
            }

            if (configure == null)
            {
                throw new ArgumentNullException(nameof(configure));
            }

            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            SchemaContext context = CreateSchemaContext();

            // deserialize schema objects
            SchemaSyntaxVisitor visitor = new SchemaSyntaxVisitor(context.Types);

            visitor.Visit(schemaDocument);

            SchemaNames names = new SchemaNames(
                visitor.QueryTypeName,
                visitor.MutationTypeName,
                visitor.SubscriptionTypeName);

            return(CreateSchema(services, context, names, configure, strict));
        }
        /// <summary>
        /// Parses the messages section of a protocol definition
        /// </summary>
        /// <param name="jmessage">messages JSON object</param>
        /// <param name="names">list of parsed names</param>
        /// <param name="encspace">enclosing namespace</param>
        /// <returns></returns>
        internal static Message Parse(JProperty jmessage, SchemaNames names, string encspace)
        {
            string name = jmessage.Name;
            string doc = JsonHelper.GetOptionalString(jmessage.Value, "doc");
            bool? oneway = JsonHelper.GetOptionalBoolean(jmessage.Value, "one-way");

            PropertyMap props = Schema.GetProperties(jmessage.Value);
            RecordSchema schema = RecordSchema.NewInstance(Schema.Type.Record, jmessage.Value as JObject, props, names, encspace);

            JToken jresponse = jmessage.Value["response"];
            var response = Schema.ParseJson(jresponse, names, encspace);

            JToken jerrors = jmessage.Value["errors"];
            UnionSchema uerrorSchema = null;
            if (null != jerrors)
            {
                Schema errorSchema = Schema.ParseJson(jerrors, names, encspace);
                if (!(errorSchema is UnionSchema))
                    throw new AvroException("");

                uerrorSchema = errorSchema as UnionSchema;
            }

            return new Message(name, doc, schema, response, uerrorSchema, oneway);
        }
Exemple #5
0
        /// <summary>
        /// Generate list of named schemas from given schema
        /// </summary>
        /// <param name="schema">schema to process</param>
        /// <returns></returns>
        protected virtual SchemaNames generateNames(Schema schema)
        {
            var names = new SchemaNames();

            addName(schema, names);
            return(names);
        }
Exemple #6
0
        /// <summary>
        /// Generates code for the protocol objects
        /// </summary>
        protected virtual void processProtocols()
        {
            foreach (Protocol protocol in Protocols)
            {
                SchemaNames names = generateNames(protocol);
                foreach (KeyValuePair <SchemaName, NamedSchema> sn in names)
                {
                    switch (sn.Value.Tag)
                    {
                    case Schema.Type.Enumeration: processEnum(sn.Value); break;

                    case Schema.Type.Fixed: processFixed(sn.Value); break;

                    case Schema.Type.Record: processRecord(sn.Value); break;

                    case Schema.Type.Error: processRecord(sn.Value); break;

                    default:
                        throw new CodeGenException("Names in protocol should only be of type NamedSchema, type found " + sn.Value.Tag);
                    }
                }

                processInterface(protocol);
            }
        }
Exemple #7
0
        /// <summary>
        /// Writes Protocol in JSON format
        /// </summary>
        /// <param name="writer">JSON writer</param>
        /// <param name="names">list of named schemas already written</param>
        internal void WriteJson(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names)
        {
            writer.WriteStartObject();

            JsonHelper.writeIfNotNullOrEmpty(writer, "protocol", this.Name);
            JsonHelper.writeIfNotNullOrEmpty(writer, "namespace", this.Namespace);
            JsonHelper.writeIfNotNullOrEmpty(writer, "doc", this.Doc);

            writer.WritePropertyName("types");
            writer.WriteStartArray();

            foreach (Schema type in this.Types)
            {
                type.WriteJson(writer, names, this.Namespace);
            }

            writer.WriteEndArray();

            writer.WritePropertyName("messages");
            writer.WriteStartObject();

            foreach (KeyValuePair <string, Message> message in this.Messages)
            {
                writer.WritePropertyName(message.Key);
                message.Value.writeJson(writer, names, this.Namespace);
            }

            writer.WriteEndObject();
            writer.WriteEndObject();
        }
Exemple #8
0
        /// <summary>
        /// Parses the given JSON object to create a Protocol object
        /// </summary>
        /// <param name="jtok">JSON object</param>
        /// <returns>Protocol object</returns>
        private static Protocol Parse(JToken jtok)
        {
            string name  = JsonHelper.GetRequiredString(jtok, "protocol");
            string space = JsonHelper.GetOptionalString(jtok, "namespace");
            string doc   = JsonHelper.GetOptionalString(jtok, "doc");

            var names = new SchemaNames();

            JToken jtypes = jtok["types"];
            var    types  = new List <Schema>();

            if (jtypes is JArray)
            {
                foreach (JToken jtype in jtypes)
                {
                    var schema = Schema.ParseJson(jtype, names, space);
                    types.Add(schema);
                }
            }

            var    messages  = new Dictionary <string, Message>();
            JToken jmessages = jtok["messages"];

            if (null != jmessages)
            {
                foreach (JProperty jmessage in jmessages)
                {
                    var message = Message.Parse(jmessage, names, space);
                    messages.Add(message.Name, message);
                }
            }

            return(new Protocol(name, space, doc, types, messages));
        }
            public static SchemaTypes Create(
                IEnumerable <INamedType> types,
                IEnumerable <ITypeBinding> typeBindings,
                SchemaNames names)
            {
                if (types == null)
                {
                    throw new ArgumentNullException(nameof(types));
                }

                if (typeBindings == null)
                {
                    throw new ArgumentNullException(nameof(typeBindings));
                }

                SchemaNames n = string.IsNullOrEmpty(names.QueryTypeName)
                    ? new SchemaNames(null, null, null)
                    : names;

                return(new SchemaTypes(types,
                                       typeBindings,
                                       n.QueryTypeName,
                                       n.MutationTypeName,
                                       n.SubscriptionTypeName));
            }
Exemple #10
0
        /// <summary>
        /// Generate list of named schemas from given protocol
        /// </summary>
        /// <param name="protocol">protocol to process</param>
        /// <returns></returns>
        protected virtual SchemaNames generateNames(Protocol protocol)
        {
            var names = new SchemaNames();

            foreach (Schema schema in protocol.Types)
            {
                addName(schema, names);
            }
            return(names);
        }
Exemple #11
0
        /// <summary>
        /// Generates code for the schema objects
        /// </summary>
        protected virtual void processSchemas()
        {
            foreach (Schema schema in this.Schemas)
            {
                SchemaNames names = generateNames(schema);
                foreach (KeyValuePair <SchemaName, NamedSchema> sn in names)
                {
                    switch (sn.Value.Tag)
                    {
                    case Schema.Type.Enumeration: processEnum(sn.Value); break;

                    case Schema.Type.Fixed: processFixed(sn.Value); break;

                    case Schema.Type.Record: processRecord(sn.Value); break;

                    case Schema.Type.Error: processRecord(sn.Value); break;

                    default:
                        throw new CodeGenException("Names in schema should only be of type NamedSchema, type found " + sn.Value.Tag);
                    }
                }
            }
        }
        private void GenerateSchemas(IEnumerable <Record> results, string outDir)
        {
            var codegen = new Avro.CodeGen();

            var schemaNames = new SchemaNames();

            foreach (var result in results)
            {
                Console.WriteLine("Start processing : {0}", result.Fullname);

                var scheme = Schema.Parse(result.Schema, schemaNames);

                schemaNames.Add((NamedSchema)scheme);

                codegen.AddSchema(scheme);

                Console.WriteLine("Generate : {0}", result.Fullname);
            }

            codegen.GenerateCode();
            codegen.WriteTypes(outDir);
            Console.WriteLine("Completed.");
        }
Exemple #13
0
        /// <summary>
        /// Recursively search the given schema for named schemas and adds them to the given container
        /// </summary>
        /// <param name="schema">schema object to search</param>
        /// <param name="names">list of named schemas</param>
        protected virtual void addName(Schema schema, SchemaNames names)
        {
            NamedSchema ns = schema as NamedSchema;

            if (null != ns)
            {
                if (names.Contains(ns.SchemaName))
                {
                    return;
                }
            }

            switch (schema.Tag)
            {
            case Schema.Type.Null:
            case Schema.Type.Boolean:
            case Schema.Type.Int:
            case Schema.Type.Long:
            case Schema.Type.Float:
            case Schema.Type.Double:
            case Schema.Type.Bytes:
            case Schema.Type.String:
                break;

            case Schema.Type.Enumeration:
            case Schema.Type.Fixed:
                names.Add(ns);
                break;

            case Schema.Type.Record:
            case Schema.Type.Error:
                var rs = schema as RecordSchema;
                names.Add(rs);
                foreach (Field field in rs.Fields)
                {
                    addName(field.Schema, names);
                }
                break;

            case Schema.Type.Array:
                var asc = schema as ArraySchema;
                addName(asc.ItemSchema, names);
                break;

            case Schema.Type.Map:
                var ms = schema as MapSchema;
                addName(ms.ValueSchema, names);
                break;

            case Schema.Type.Union:
                var us = schema as UnionSchema;
                foreach (Schema usc in us.Schemas)
                {
                    addName(usc, names);
                }
                break;

            default:
                throw new CodeGenException("Unable to add name for " + schema.Name + " type " + schema.Tag);
            }
        }
Exemple #14
0
        private static Schema CreateSchema(
            IServiceProvider services,
            SchemaContext context,
            SchemaNames names,
            Action <ISchemaConfiguration> configure,
            bool strict)
        {
            List <SchemaError> errors = new List <SchemaError>();

            // setup introspection fields
            IntrospectionFields introspectionFields =
                new IntrospectionFields(context, e => errors.Add(e));

            SchemaNames internalNames = names;

            try
            {
                // configure resolvers, custom types and type mappings.
                SchemaConfiguration configuration = new SchemaConfiguration(services);
                configure(configuration);
                errors.AddRange(configuration.RegisterTypes(context));
                configuration.RegisterResolvers(context);
                errors.AddRange(context.CompleteTypes());

                string queryTypeName        = configuration.QueryTypeName ?? names.QueryTypeName;
                string mutationTypeName     = configuration.MutationTypeName ?? names.MutationTypeName;
                string subscriptionTypeName = configuration.SubscriptionTypeName ?? names.SubscriptionTypeName;

                internalNames = new SchemaNames(queryTypeName, mutationTypeName, subscriptionTypeName);
            }
            catch (ArgumentException ex)
            {
                // TODO : maybe we should throw a more specific
                // argument exception that at least contains the config object.
                throw new SchemaException(new[]
                {
                    new SchemaError(ex.Message, null)
                });
            }

            if (strict && errors.Any())
            {
                throw new SchemaException(errors);
            }

            internalNames = string.IsNullOrEmpty(names.QueryTypeName)
                ? new SchemaNames(null, null, null)
                : names;

            if (strict && !context.Types.TryGetType <ObjectType>(
                    internalNames.QueryTypeName, out ObjectType ot))
            {
                throw new SchemaException(new SchemaError(
                                              "Schema is missing the mandatory `Query` type."));
            }

            return(new Schema(
                       services,
                       SchemaTypes.Create(
                           context.Types.GetTypes(),
                           context.Types.GetTypeBindings(),
                           internalNames),
                       introspectionFields));
        }
 protected RepositoryBase(T context, string schemaName = null)
 {
     Context         = context ?? throw new ArgumentNullException(nameof(context));
     _schemaName     = schemaName ?? throw new ArgumentNullException(nameof(schemaName));
     _fullSchemaName = SchemaNames.SchemaWithTable(schemaName) ?? "";
 }