Пример #1
0
 public static JsonSchema GenerateSchema(Type type)
 {
     var schemaGenerator = new JsonSchemaGenerator();
     var schema = schemaGenerator.Generate(type);
     schema.Title = type.Name;
     return schema.MapSchemaTypes(type);
 }
Пример #2
0
 /// <summary>
 /// Generate JSON schema for redwood.json file.
 /// </summary>
 private static void GenerateConfigSchema(string outputFile)
 {
     var generator = new JsonSchemaGenerator();
     var schema = generator.Generate(typeof(RedwoodConfiguration));
     using (var textWriter = new StreamWriter(outputFile))
     {
         using (var writer = new JsonTextWriter(textWriter))
         {
             writer.Formatting = Formatting.Indented;
             schema.WriteTo(writer);
         }
     }
 }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var parameterDescriptors = filterContext.ActionDescriptor.GetParameters();

            //// Get json data
            var rawValue = filterContext.Controller.ValueProvider.GetValue("data");
            var rawData = string.Empty;
            if (rawValue == null)
            {
                return;
            }
            else
            {
                rawData = rawValue.AttemptedValue;
            }

            //// Check Parameter type
            if (parameterDescriptors.Count() != 1 || parameterDescriptors.First().ParameterType.IsValueType)
            {
                return;
            }

            //// Get json schema from parameter
            JsonSchema jsonSchema = null;
            var parameterDescriptor = parameterDescriptors.First();
            var jsonSchemaGenerator = new JsonSchemaGenerator();
            jsonSchema = jsonSchemaGenerator.Generate(parameterDescriptor.ParameterType);
            jsonSchema.Title = parameterDescriptor.ParameterType.Name;

            jsonSchema = JsonSchema.Parse(jsonSchema.ToString().ToLower());

            var errs = new List<string>() as IList<string>;
            JObject jsonObject = null;

            //// 處理Json格式的異常
            try
            {
                jsonObject = JObject.Parse(rawData.ToLower());
            }
            catch (JsonReaderException ex)
            {
                throw new JsonSchemaNotValidException(ex.Message, ex);
            }

            var valid = jsonObject.IsValid(jsonSchema, out errs);
            if (errs.Count > 0)
            {
                throw new JsonSchemaNotValidException("請確認傳入資料型別是否符合規範!" +
                    string.Join(",", errs.ToArray()));
            }
        }
Пример #4
0
        public TypeDefinition GetOrCreate(Type type)
        {
            TypeDefinition def;

            if (_cache == null)
            {
                _generator = new JsonSchemaGenerator();
                if (_supportRecursive) _generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseAssemblyQualifiedName;
                _cache = new Dictionary<Type, TypeDefinition>();
            }

            if (!_cache.TryGetValue(type, out def))
            {
                def = new TypeDefinition(type, _generator, this);
                _cache.Add(type, def);
            }

            return def;
        }
    public void ReadAsDecimalFailure()
    {
      JsonSchema s = new JsonSchemaGenerator().Generate(typeof (decimal));
      s.DivisibleBy = 1;

      JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"5.5")))
        {
          Schema = s
        };
      reader.ReadAsDecimal();
    }
    public void ReadAsInt32Failure()
    {
      JsonSchema s = new JsonSchemaGenerator().Generate(typeof (int));
      s.Maximum = 2;

      JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"5")))
        {
          Schema = s
        };
      reader.ReadAsInt32();
    }
Пример #7
0
        public virtual async Task<bool> HandleContractMetadataAsync(ServerActionContext context)
        {
            try
            {
                string result = string.Empty;
                string actionName = context.HttpContext.Request.Query["action"]?.Trim();
                MethodInfo action = null;

                if (!string.IsNullOrEmpty(actionName))
                {
                    action = _actionResolver.Resolve(context.Contract, actionName);
                }

                if (action == null)
                {
                    var contractMetadata = CrateContractMetadata(context);
                    result = JsonConvert.SerializeObject(
                        contractMetadata,
                        Formatting.Indented,
                        new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
                }
                else
                {
                    context.Action = action;
                    JsonSchema actionSchema = new JsonSchema
                                                  {
                                                      Properties = new Dictionary<string, JsonSchema>(),
                                                      Description = $"Request and response parameters for action '{actionName}'."
                                                  };

                    List<ParameterInfo> actionParameters = BoltFramework.GetSerializableParameters(action).ToList();
                    if (actionParameters.Any())
                    {
                        JsonSchemaGenerator generator = new JsonSchemaGenerator();
                        JsonSchema arguments = new JsonSchema
                                                   {
                                                       Properties =
                                                           actionParameters.ToDictionary(
                                                               p => p.Name,
                                                               p => generator.Generate(p.ParameterType)),
                                                       Required = true,
                                                       Type = JsonSchemaType.Object,
                                                   };

                        actionSchema.Properties.Add("request", arguments);
                    }

                    if (context.ResponseType != typeof(void))
                    {
                        JsonSchemaGenerator generator = new JsonSchemaGenerator();
                        actionSchema.Properties.Add("response", generator.Generate(context.ResponseType));
                    }

                    using (var sw = new StringWriter())
                    {
                        using (JsonTextWriter jw = new JsonTextWriter(sw))
                        {

                            jw.Formatting = Formatting.Indented;
                            actionSchema.WriteTo(jw);
                        }
                        result = sw.GetStringBuilder().ToString();
                    }
                }

                context.HttpContext.Response.ContentType = "application/json";
                context.HttpContext.Response.StatusCode = 200;
                await context.HttpContext.Response.WriteAsync(result);
                return true;
            }
            catch (Exception e)
            {
                Logger.LogWarning(
                    BoltLogId.HandleContractMetadataError,
                    "Failed to generate Bolt metadata for contract '{0}'. Error: {1}",
                    context.Contract.Name,
                    e);
                return false;
            }
        }
Пример #8
0
		static void Main(string[] args)
		{
			#region ensure latest schema is in program directory
			var jsonSchemaGenerator = new JsonSchemaGenerator();
			var myType = typeof(Config);
			var schema = jsonSchemaGenerator.Generate(myType);
			schema.Title = "Bit Rot Watcher Configuration Schema";

			using (var writer = new StringWriter())
			using (var jsonTextWriter = new JsonTextWriter(writer))
			{
				schema.WriteTo(jsonTextWriter);
				dynamic parsedJson = JsonConvert.DeserializeObject(writer.ToString());
				var prettyString = JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
				using (var fileWriter = new StreamWriter("config.schema.json"))
					fileWriter.WriteLine(prettyString);
			}
			#endregion

			#region ensure we have a config file specified
			ConfigFilePath = args[0];//Make the naming not suck
			if (args.Length == 0 || string.IsNullOrEmpty(ConfigFilePath))
			{
				WriteOutput("No config file specified.");
				return;
			}
			#endregion

			#region load config
			try
			{
				var ConfigFile = new FileInfo(ConfigFilePath);
				if (!ConfigFile.Exists)
				{
					WriteOutput("Configuration file does not exist.");
					return;
				}

				Configuration = JsonConvert.DeserializeObject<Config>(File.ReadAllText(ConfigFile.FullName));
			}
			catch (Exception ex)
			{
				WriteOutput($"Error loading specified configuration file. Message: \"{ex.Message}\" Stack: \"{ex.StackTrace}\"");
				return;
			}
			#endregion

			#region prep log file stream
			FileInfo logFile = LogFile;
			if (Configuration.ClearOutputFile && logFile.Exists)
				logFile.Delete();
			LogStream = File.AppendText(logFile.FullName);
			#endregion

			#region load database
			var dbf = DatabaseFile;
			if (!dbf.Exists)
			{
				WriteOutput("Database file not found, creating new one.");
				HashDatabase = new Dictionary<string, WatchedFile>();
			}
			else
			{
				HashDatabase = JsonConvert.DeserializeObject<Dictionary<string, WatchedFile>>(File.ReadAllText(dbf.FullName));
			}
			#endregion

			#region process database
			foreach (var directory in Configuration.DirectoriesToMonitor.Select(x => new DirectoryInfo(x)))
			{
				WriteOutput($"Checking root folder \"{directory.FullName}\".");
				byte[] currentFileHash;
				WatchedFile databaseRecord;
				foreach (var file in directory.GetFilesRecurse())
				{
					currentFileHash = GetFileHash(file);

					if (HashDatabase.ContainsKey(file.FullName))
					{
						databaseRecord = HashDatabase[file.FullName];

						if (file.LastWriteTime != databaseRecord.LastWritetime)//File was modified, hash invalid.
						{
							ModifiedFiles++;
							databaseRecord.Hash = currentFileHash;//Update the database's copy so next time we can verify the file.
							WriteOutput($"File \"{file.FullName}\" was modified.");
						}
						else if (StructuralComparisons.StructuralEqualityComparer.Equals(databaseRecord.Hash, currentFileHash))
						{
							HealthyFiles++;
							WriteOutput($"File \"{file.FullName}\" verified succesfully.");
						}
						else
						{
							CorruptFiles++;
							WriteOutput($"File \"{file.FullName}\" corrupt!!");
						}
					}
					else
					{
						NewFiles++;
						HealthyFiles++;
						WriteOutput($"Added new file \"{file.FullName}\".");
						HashDatabase.Add(file.FullName, new WatchedFile(file.FullName, currentFileHash, file.LastWriteTime));
					}
				}
			}

			#region Remove deleted files from database
			foreach (var file in HashDatabase.Keys.Select(x => new FileInfo(x)))
				if (!file.Exists)
				{
					DeletedFiles++;
					HashDatabase.Remove(file.FullName);
					WriteOutput($"File \"{file.FullName}\" was deleted.");
				}
			#endregion
			#endregion

			//Write our database to disk
			File.WriteAllText(DatabaseFile.FullName, JsonConvert.SerializeObject(HashDatabase, Configuration.OptimizeDatabase ? Formatting.None : Formatting.Indented));

			#region report aggregate results
			WriteOutput(string.Empty);
			WriteOutput($"Files scanned: {FilesScanned}");
			WriteOutput($"New: {NewFiles}");
			WriteOutput($"Healthy: {HealthyFiles}");
			WriteOutput($"Corrupt: {CorruptFiles}");
			WriteOutput($"Health: {((HealthyFiles / FilesScanned) * 100)}%");
			WriteOutput($"Database File: {DatabaseFile.FullName}");
			WriteOutput($"Config File: {ConfigFilePath}");
			#endregion

			CryptoEngine.Dispose();
			LogStream.Dispose();

			#region send email if configured
			if ((Configuration.Email_When == Config.EmailWhen.Always || (Configuration.Email_When == Config.EmailWhen.OnError && CorruptFiles > 0)) && Configuration.Email_To != null)
			{
				using (var client = new SmtpClient())
				{
					client.Port = Configuration.Email_Port;
					client.DeliveryMethod = SmtpDeliveryMethod.Network;
					client.UseDefaultCredentials = false;
					client.Host = Configuration.Email_Server;
					client.Credentials = new NetworkCredential(Configuration.Email_User, Configuration.Email_Pass);

					using (var message = new MailMessage())
					{
						message.To.AddRange(Configuration.Email_To);
						message.From = new MailAddress(Configuration.Email_From);
						message.Subject = "Bitrot Report: " + (CorruptFiles > 0 ? $"{CorruptFiles} CORRUPT " : $"{HealthyFiles} Healthy") + " Files";
						message.Body = File.ReadAllText(LogFile.FullName);
						client.Send(message);
					}
				}
			}
			#endregion
		}
 // Token: 0x06000B7E RID: 2942
 // RVA: 0x0000CDF4 File Offset: 0x0000AFF4
 private void Push(JsonSchemaGenerator.TypeSchema typeSchema)
 {
     this._currentSchema = typeSchema.Schema;
     this._stack.Add(typeSchema);
     this._resolver.LoadedSchemas.Add(typeSchema.Schema);
 }
    public void ReadAsDecimal()
    {
      JsonSchema s = new JsonSchemaGenerator().Generate(typeof (decimal));

      JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"1.5")))
        {
          Schema = s
        };
      decimal? d = reader.ReadAsDecimal();

      Assert.AreEqual(1.5m, d);
    }
    public void ReadAsInt32()
    {
      JsonSchema s = new JsonSchemaGenerator().Generate(typeof (int));

      JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"1")))
        {
          Schema = s
        };
      int? i = reader.ReadAsInt32();

      Assert.AreEqual(1, i);
    }
Пример #12
0
        private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
        {
            ValidationUtils.ArgumentNotNull((object)type, "type");
            string typeId1 = this.GetTypeId(type, false);
            string typeId2 = this.GetTypeId(type, true);

            if (!string.IsNullOrEmpty(typeId1))
            {
                JsonSchema schema = this._resolver.GetSchema(typeId1);
                if (schema != null)
                {
                    if (valueRequired != Required.Always && !JsonSchemaGenerator.HasFlag(schema.Type, JsonSchemaType.Null))
                    {
                        JsonSchema     jsonSchema = schema;
                        JsonSchemaType?type1      = jsonSchema.Type;
                        JsonSchemaType?nullable   = type1.HasValue ? new JsonSchemaType?(type1.GetValueOrDefault() | JsonSchemaType.Null) : new JsonSchemaType?();
                        jsonSchema.Type = nullable;
                    }
                    if (required)
                    {
                        bool?required1 = schema.Required;
                        if ((!required1.GetValueOrDefault() ? 1 : (!required1.HasValue ? 1 : 0)) != 0)
                        {
                            schema.Required = new bool?(true);
                        }
                    }
                    return(schema);
                }
            }
            if (Enumerable.Any <JsonSchemaGenerator.TypeSchema>((IEnumerable <JsonSchemaGenerator.TypeSchema>) this._stack, (Func <JsonSchemaGenerator.TypeSchema, bool>)(tc => tc.Type == type)))
            {
                throw new JsonException(StringUtils.FormatWith("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.", (IFormatProvider)CultureInfo.InvariantCulture, (object)type));
            }
            JsonContract  jsonContract = this.ContractResolver.ResolveContract(type);
            JsonConverter jsonConverter;

            if ((jsonConverter = jsonContract.Converter) != null || (jsonConverter = jsonContract.InternalConverter) != null)
            {
                JsonSchema schema = jsonConverter.GetSchema();
                if (schema != null)
                {
                    return(schema);
                }
            }
            this.Push(new JsonSchemaGenerator.TypeSchema(type, new JsonSchema()));
            if (typeId2 != null)
            {
                this.CurrentSchema.Id = typeId2;
            }
            if (required)
            {
                this.CurrentSchema.Required = new bool?(true);
            }
            this.CurrentSchema.Title       = this.GetTitle(type);
            this.CurrentSchema.Description = this.GetDescription(type);
            if (jsonConverter != null)
            {
                this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any);
            }
            else
            {
                switch (jsonContract.ContractType)
                {
                case JsonContractType.Object:
                    this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                    this.CurrentSchema.Id   = this.GetTypeId(type, false);
                    this.GenerateObjectSchema(type, (JsonObjectContract)jsonContract);
                    break;

                case JsonContractType.Array:
                    this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Array, valueRequired));
                    this.CurrentSchema.Id   = this.GetTypeId(type, false);
                    JsonArrayAttribute jsonArrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute;
                    bool flag = jsonArrayAttribute == null || jsonArrayAttribute.AllowNullItems;
                    Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
                    if (collectionItemType != null)
                    {
                        this.CurrentSchema.Items = (IList <JsonSchema>) new List <JsonSchema>();
                        this.CurrentSchema.Items.Add(this.GenerateInternal(collectionItemType, !flag ? Required.Always : Required.Default, false));
                        break;
                    }
                    else
                    {
                        break;
                    }

                case JsonContractType.Primitive:
                    this.CurrentSchema.Type = new JsonSchemaType?(this.GetJsonSchemaType(type, valueRequired));
                    JsonSchemaType?type2 = this.CurrentSchema.Type;
                    if ((type2.GetValueOrDefault() != JsonSchemaType.Integer ? 0 : (type2.HasValue ? 1 : 0)) != 0 && TypeExtensions.IsEnum(type) && !type.IsDefined(typeof(FlagsAttribute), true))
                    {
                        this.CurrentSchema.Enum    = (IList <JToken>) new List <JToken>();
                        this.CurrentSchema.Options = (IDictionary <JToken, string>) new Dictionary <JToken, string>();
                        using (IEnumerator <EnumValue <long> > enumerator = EnumUtils.GetNamesAndValues <long>(type).GetEnumerator())
                        {
                            while (enumerator.MoveNext())
                            {
                                EnumValue <long> current = enumerator.Current;
                                JToken           key     = JToken.FromObject((object)current.Value);
                                this.CurrentSchema.Enum.Add(key);
                                this.CurrentSchema.Options.Add(key, current.Name);
                            }
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }

                case JsonContractType.String:
                    this.CurrentSchema.Type = new JsonSchemaType?(!ReflectionUtils.IsNullable(jsonContract.UnderlyingType) ? JsonSchemaType.String : this.AddNullType(JsonSchemaType.String, valueRequired));
                    break;

                case JsonContractType.Dictionary:
                    this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                    Type keyType;
                    Type valueType;
                    ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType);
                    if (keyType != null && ConvertUtils.IsConvertible(keyType))
                    {
                        this.CurrentSchema.AdditionalProperties = this.GenerateInternal(valueType, Required.Default, false);
                        break;
                    }
                    else
                    {
                        break;
                    }

                case JsonContractType.Serializable:
                    this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                    this.CurrentSchema.Id   = this.GetTypeId(type, false);
                    this.GenerateISerializableContract(type, (JsonISerializableContract)jsonContract);
                    break;

                case JsonContractType.Linq:
                    this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any);
                    break;

                default:
                    throw new JsonException(StringUtils.FormatWith("Unexpected contract type: {0}", (IFormatProvider)CultureInfo.InvariantCulture, (object)jsonContract));
                }
            }
            return(this.Pop().Schema);
        }
Пример #13
0
        private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
        {
            JsonSchemaType?nullable;
            Type           type1;
            Type           type2;
            JsonSchemaType?nullable1;

            ValidationUtils.ArgumentNotNull(type, "type");
            string typeId = this.GetTypeId(type, false);
            string str    = this.GetTypeId(type, true);

            if (!string.IsNullOrEmpty(typeId))
            {
                JsonSchema schema = this._resolver.GetSchema(typeId);
                if (schema != null)
                {
                    if (valueRequired != Required.Always && !JsonSchemaGenerator.HasFlag(schema.Type, JsonSchemaType.Null))
                    {
                        JsonSchema     jsonSchema = schema;
                        JsonSchemaType?nullable2  = jsonSchema.Type;
                        if (!nullable2.HasValue)
                        {
                            nullable  = null;
                            nullable1 = nullable;
                        }
                        else
                        {
                            nullable1 = new JsonSchemaType?(nullable2.GetValueOrDefault() | JsonSchemaType.Null);
                        }
                        jsonSchema.Type = nullable1;
                    }
                    if (required)
                    {
                        bool?nullable3 = schema.Required;
                        if ((!nullable3.GetValueOrDefault() ? true : !nullable3.HasValue))
                        {
                            schema.Required = new bool?(true);
                        }
                    }
                    return(schema);
                }
            }
            if (this._stack.Any <JsonSchemaGenerator.TypeSchema>((JsonSchemaGenerator.TypeSchema tc) => tc.Type == type))
            {
                throw new Exception("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, new object[] { type }));
            }
            JsonContract  jsonContract  = this.ContractResolver.ResolveContract(type);
            JsonConverter converter     = jsonContract.Converter;
            JsonConverter jsonConverter = converter;

            if (converter == null)
            {
                JsonConverter internalConverter = jsonContract.InternalConverter;
                jsonConverter = internalConverter;
                if (internalConverter == null)
                {
                    goto Label0;
                }
            }
            JsonSchema schema1 = jsonConverter.GetSchema();

            if (schema1 != null)
            {
                return(schema1);
            }
Label0:
            this.Push(new JsonSchemaGenerator.TypeSchema(type, new JsonSchema()));
            if (str != null)
            {
                this.CurrentSchema.Id = str;
            }
            if (required)
            {
                this.CurrentSchema.Required = new bool?(true);
            }
            this.CurrentSchema.Title       = this.GetTitle(type);
            this.CurrentSchema.Description = this.GetDescription(type);
            if (jsonConverter != null)
            {
                this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any);
            }
            else if (jsonContract is JsonDictionaryContract)
            {
                this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                ReflectionUtils.GetDictionaryKeyValueTypes(type, out type1, out type2);
                if (type1 != null && typeof(IConvertible).IsAssignableFrom(type1))
                {
                    this.CurrentSchema.AdditionalProperties = this.GenerateInternal(type2, Required.Default, false);
                }
            }
            else if (jsonContract is JsonArrayContract)
            {
                this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Array, valueRequired));
                this.CurrentSchema.Id   = this.GetTypeId(type, false);
                JsonArrayAttribute jsonContainerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute;
                bool flag = (jsonContainerAttribute == null ? true : jsonContainerAttribute.AllowNullItems);
                Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
                if (collectionItemType != null)
                {
                    this.CurrentSchema.Items = new List <JsonSchema>()
                    {
                        this.GenerateInternal(collectionItemType, (flag ? Required.Default : Required.Always), false)
                    };
                }
            }
            else if (jsonContract is JsonPrimitiveContract)
            {
                this.CurrentSchema.Type = new JsonSchemaType?(this.GetJsonSchemaType(type, valueRequired));
                nullable = this.CurrentSchema.Type;
                if ((nullable.GetValueOrDefault() != JsonSchemaType.Integer ? false : nullable.HasValue) && type.IsEnum && !type.IsDefined(typeof(FlagsAttribute), true))
                {
                    this.CurrentSchema.Enum    = new List <JToken>();
                    this.CurrentSchema.Options = new Dictionary <JToken, string>();
                    foreach (EnumValue <long> namesAndValue in EnumUtils.GetNamesAndValues <long>(type))
                    {
                        JToken jTokens = JToken.FromObject(namesAndValue.Value);
                        this.CurrentSchema.Enum.Add(jTokens);
                        this.CurrentSchema.Options.Add(jTokens, namesAndValue.Name);
                    }
                }
            }
            else if (jsonContract is JsonObjectContract)
            {
                this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                this.CurrentSchema.Id   = this.GetTypeId(type, false);
                this.GenerateObjectSchema(type, (JsonObjectContract)jsonContract);
            }
            else if (jsonContract is JsonISerializableContract)
            {
                this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                this.CurrentSchema.Id   = this.GetTypeId(type, false);
                this.GenerateISerializableContract(type, (JsonISerializableContract)jsonContract);
            }
            else if (!(jsonContract is JsonStringContract))
            {
                if (!(jsonContract is JsonLinqContract))
                {
                    throw new Exception("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, new object[] { jsonContract }));
                }
                this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any);
            }
            else
            {
                this.CurrentSchema.Type = new JsonSchemaType?((ReflectionUtils.IsNullable(jsonContract.UnderlyingType) ? this.AddNullType(JsonSchemaType.String, valueRequired) : JsonSchemaType.String));
            }
            return(this.Pop().Schema);
        }
        private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
        {
            ValidationUtils.ArgumentNotNull(type, "type");
            string typeId  = this.GetTypeId(type, false);
            string typeId2 = this.GetTypeId(type, true);

            if (!string.IsNullOrEmpty(typeId))
            {
                JsonSchema schema = this._resolver.GetSchema(typeId);
                if (schema != null)
                {
                    if (valueRequired != Required.Always && !JsonSchemaGenerator.HasFlag(schema.Type, JsonSchemaType.Null))
                    {
                        schema.Type |= JsonSchemaType.Null;
                    }
                    if (required && schema.Required != true)
                    {
                        schema.Required = new bool?(true);
                    }
                    return(schema);
                }
            }
            if (this._stack.Any((JsonSchemaGenerator.TypeSchema tc) => tc.Type == type))
            {
                throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type));
            }
            JsonContract  jsonContract = this.ContractResolver.ResolveContract(type);
            JsonConverter jsonConverter;

            if ((jsonConverter = jsonContract.Converter) != null || (jsonConverter = jsonContract.InternalConverter) != null)
            {
                JsonSchema schema2 = jsonConverter.GetSchema();
                if (schema2 != null)
                {
                    return(schema2);
                }
            }
            this.Push(new JsonSchemaGenerator.TypeSchema(type, new JsonSchema()));
            if (typeId2 != null)
            {
                this.CurrentSchema.Id = typeId2;
            }
            if (required)
            {
                this.CurrentSchema.Required = new bool?(true);
            }
            this.CurrentSchema.Title       = this.GetTitle(type);
            this.CurrentSchema.Description = this.GetDescription(type);
            if (jsonConverter != null)
            {
                this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any);
            }
            else
            {
                switch (jsonContract.ContractType)
                {
                case JsonContractType.Object:
                    this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                    this.CurrentSchema.Id   = this.GetTypeId(type, false);
                    this.GenerateObjectSchema(type, (JsonObjectContract)jsonContract);
                    goto IL_51E;

                case JsonContractType.Array:
                    {
                        this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Array, valueRequired));
                        this.CurrentSchema.Id   = this.GetTypeId(type, false);
                        JsonArrayAttribute jsonArrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute;
                        bool flag = jsonArrayAttribute == null || jsonArrayAttribute.AllowNullItems;
                        Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
                        if (collectionItemType != null)
                        {
                            this.CurrentSchema.Items = new List <JsonSchema>();
                            this.CurrentSchema.Items.Add(this.GenerateInternal(collectionItemType, (!flag) ? Required.Always : Required.Default, false));
                            goto IL_51E;
                        }
                        goto IL_51E;
                    }

                case JsonContractType.Primitive:
                {
                    this.CurrentSchema.Type = new JsonSchemaType?(this.GetJsonSchemaType(type, valueRequired));
                    if (!(this.CurrentSchema.Type == JsonSchemaType.Integer) || !type.IsEnum() || type.IsDefined(typeof(FlagsAttribute), true))
                    {
                        goto IL_51E;
                    }
                    this.CurrentSchema.Enum = new List <JToken>();
                    EnumValues <long> namesAndValues = EnumUtils.GetNamesAndValues <long>(type);
                    using (IEnumerator <EnumValue <long> > enumerator = namesAndValues.GetEnumerator())
                    {
                        while (enumerator.MoveNext())
                        {
                            EnumValue <long> current = enumerator.Current;
                            JToken           item    = JToken.FromObject(current.Value);
                            this.CurrentSchema.Enum.Add(item);
                        }
                        goto IL_51E;
                    }
                    break;
                }

                case JsonContractType.String:
                    break;

                case JsonContractType.Dictionary:
                {
                    this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                    Type type2;
                    Type type3;
                    ReflectionUtils.GetDictionaryKeyValueTypes(type, out type2, out type3);
                    if (!(type2 != null))
                    {
                        goto IL_51E;
                    }
                    JsonContract jsonContract2 = this.ContractResolver.ResolveContract(type2);
                    if (jsonContract2.ContractType == JsonContractType.Primitive)
                    {
                        this.CurrentSchema.AdditionalProperties = this.GenerateInternal(type3, Required.Default, false);
                        goto IL_51E;
                    }
                    goto IL_51E;
                }

                case JsonContractType.Dynamic:
                case JsonContractType.Linq:
                    this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any);
                    goto IL_51E;

                case JsonContractType.Serializable:
                    this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                    this.CurrentSchema.Id   = this.GetTypeId(type, false);
                    this.GenerateISerializableContract(type, (JsonISerializableContract)jsonContract);
                    goto IL_51E;

                default:
                    throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContract));
                }
                JsonSchemaType value = (!ReflectionUtils.IsNullable(jsonContract.UnderlyingType)) ? JsonSchemaType.String : this.AddNullType(JsonSchemaType.String, valueRequired);
                this.CurrentSchema.Type = new JsonSchemaType?(value);
            }
            IL_51E:
            return(this.Pop().Schema);
        }
Пример #15
0
        public TypeDefinition(Type type,JsonSchemaGenerator generator,TypeDefinitionContainer container)
        {
            _type = type;
            _schema = generator.Generate(type, true);
            _canNull = HasFlag(_schema.Type, JsonSchemaType.Null);
            _isArray = HasFlag(_schema.Type, JsonSchemaType.Array);
            _isObject = HasFlag(_schema.Type, JsonSchemaType.Object);

            if (_isArray && _isObject)
                throw new ApplicationException(string.Format("Type {0} is both array and object.", type.FullName));

            if (_isArray)
            {
                _subType = GetCollectionItemType(_type);
            }
            else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                _subType = type.GetGenericArguments()[0];
                var subDef = container.GetOrCreate(_subType);
                _name = subDef.Name;
                _demoValue = subDef.DemoValue;
            }
            else if (type == typeof(DateTime))
            {
                _name = "dateTime";
                _demoValue = JsonConvert.SerializeObject(DateTime.Now).Trim('\"');
            }
            else if (type == typeof(byte[]))
            {
                _name = "base64binary";
                _demoValue = JsonConvert.SerializeObject(Encoding.UTF8.GetBytes("Cus.WebApi")).Trim('\"');
            }

            _isLeaf = !(_isArray || _isObject);

            _id = Guid.NewGuid().ToString("N");

            if (_name == null)
            {
                if (IsArray)
                {
                    _name = "array";
                    _demoValue = "[]";
                }
                else if (IsObject)
                {
                    _name = "object";
                    _demoValue = "{}";
                    if (_schema.Id != null)
                        _isCustomObject = true;
                }
                else if (HasFlag(_schema.Type, JsonSchemaType.String))
                {
                    _name = "string";
                    _demoValue = "string1";
                }
                else if (HasFlag(_schema.Type, JsonSchemaType.Boolean))
                {
                    _name = "boolean";
                    _demoValue = true;
                }
                else if (HasFlag(_schema.Type, JsonSchemaType.Float))
                {
                    _name = "float";
                    _demoValue = 1.1f;
                }
                else if (HasFlag(_schema.Type, JsonSchemaType.Integer))
                {
                    _name = "integer";
                    _demoValue = 1;
                }
                else if (_schema.Type == JsonSchemaType.Any) _name = "any";
                else if (_schema.Type == JsonSchemaType.Null) _name = "null";
                else _name = "unknown";
            }
        }
    public void ReadAsBytes()
    {
      JsonSchema s = new JsonSchemaGenerator().Generate(typeof (byte[]));

      byte[] data = Encoding.UTF8.GetBytes("Hello world");

      JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"""" + Convert.ToBase64String(data) + @"""")))
        {
          Schema = s
        };
      byte[] bytes = reader.ReadAsBytes();

      CollectionAssert.AreEquivalent(data, bytes);
    }
Пример #17
0
        public void GenerateSchema()
        {
            JsonSchemaGenerator generator = new JsonSchemaGenerator();

            JsonSchema schema = generator.Generate(typeof(Session));

            // {
            //   "type": "object",
            //   "properties": {
            //     "Name": {
            //       "required": true,
            //       "type": [
            //         "string",
            //         "null"
            //       ]
            //     },
            //     "Date": {
            //       "required": true,
            //       "type": "string"
            //     }
            //   }
            // }
        }
    public void ReadAsInt32Failure()
    {
      ExceptionAssert.Throws<JsonSchemaException>("Integer 5 exceeds maximum value of 2. Line 1, position 1.",
      () =>
      {
        JsonSchema s = new JsonSchemaGenerator().Generate(typeof(int));
        s.Maximum = 2;

        JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"5")))
        {
          Schema = s
        };
        reader.ReadAsInt32();
      });
    }
Пример #19
0
        public bool CreateIfNotExists()
        {
            var path = DbSchemaPath;
            if (!System.IO.File.Exists(path))
            {
                var jsonSchemaGenerator = new JsonSchemaGenerator();
                var dispanser = typeof(Dispanser);
                var schema = jsonSchemaGenerator.Generate(dispanser);
                schema.Title = dispanser.Name;

                System.IO.File.WriteAllText(path, schema.ToString(), TextEncoding);

                return true;
            }

            return false;
        }
    public void ReadAsDecimalFailure()
    {
      ExceptionAssert.Throws<JsonSchemaException>("Float 5.5 is not evenly divisible by 1. Line 1, position 3.",
      () =>
      {
        JsonSchema s = new JsonSchemaGenerator().Generate(typeof(decimal));
        s.DivisibleBy = 1;

        JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"5.5")))
        {
          Schema = s
        };
        reader.ReadAsDecimal();
      });
    }
Пример #21
0
        // Token: 0x060013CD RID: 5069 RVA: 0x00068C14 File Offset: 0x00066E14
        private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
        {
            ValidationUtils.ArgumentNotNull(type, "type");
            string typeId  = this.GetTypeId(type, false);
            string typeId2 = this.GetTypeId(type, true);

            if (!StringUtils.IsNullOrEmpty(typeId))
            {
                JsonSchema schema = this._resolver.GetSchema(typeId);
                if (schema != null)
                {
                    if (valueRequired != Required.Always && !JsonSchemaGenerator.HasFlag(schema.Type, JsonSchemaType.Null))
                    {
                        schema.Type |= JsonSchemaType.Null;
                    }
                    if (required)
                    {
                        bool?required2 = schema.Required;
                        if (!(required2.GetValueOrDefault() & required2 != null))
                        {
                            schema.Required = new bool?(true);
                        }
                    }
                    return(schema);
                }
            }
            if (this._stack.Any((JsonSchemaGenerator.TypeSchema tc) => tc.Type == type))
            {
                throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type));
            }
            JsonContract jsonContract = this.ContractResolver.ResolveContract(type);
            bool         flag         = (jsonContract.Converter ?? jsonContract.InternalConverter) != null;

            this.Push(new JsonSchemaGenerator.TypeSchema(type, new JsonSchema()));
            if (typeId2 != null)
            {
                this.CurrentSchema.Id = typeId2;
            }
            if (required)
            {
                this.CurrentSchema.Required = new bool?(true);
            }
            this.CurrentSchema.Title       = this.GetTitle(type);
            this.CurrentSchema.Description = this.GetDescription(type);
            if (flag)
            {
                this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any);
            }
            else
            {
                switch (jsonContract.ContractType)
                {
                case JsonContractType.Object:
                    this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                    this.CurrentSchema.Id   = this.GetTypeId(type, false);
                    this.GenerateObjectSchema(type, (JsonObjectContract)jsonContract);
                    break;

                case JsonContractType.Array:
                    {
                        this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Array, valueRequired));
                        this.CurrentSchema.Id   = this.GetTypeId(type, false);
                        JsonArrayAttribute cachedAttribute = JsonTypeReflector.GetCachedAttribute <JsonArrayAttribute>(type);
                        bool flag2 = cachedAttribute == null || cachedAttribute.AllowNullItems;
                        Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
                        if (collectionItemType != null)
                        {
                            this.CurrentSchema.Items = new List <JsonSchema>();
                            this.CurrentSchema.Items.Add(this.GenerateInternal(collectionItemType, (!flag2) ? Required.Always : Required.Default, false));
                        }
                        break;
                    }

                case JsonContractType.Primitive:
                {
                    this.CurrentSchema.Type = new JsonSchemaType?(this.GetJsonSchemaType(type, valueRequired));
                    JsonSchemaType?type2 = this.CurrentSchema.Type;
                    if ((type2.GetValueOrDefault() == JsonSchemaType.Integer & type2 != null) && type.IsEnum() && !type.IsDefined(typeof(FlagsAttribute), true))
                    {
                        this.CurrentSchema.Enum = new List <JToken>();
                        EnumInfo enumValuesAndNames = EnumUtils.GetEnumValuesAndNames(type);
                        for (int i = 0; i < enumValuesAndNames.Names.Length; i++)
                        {
                            ulong  value = enumValuesAndNames.Values[i];
                            JToken item  = JToken.FromObject(Enum.ToObject(type, value));
                            this.CurrentSchema.Enum.Add(item);
                        }
                    }
                    break;
                }

                case JsonContractType.String:
                {
                    JsonSchemaType value2 = (!ReflectionUtils.IsNullable(jsonContract.UnderlyingType)) ? JsonSchemaType.String : this.AddNullType(JsonSchemaType.String, valueRequired);
                    this.CurrentSchema.Type = new JsonSchemaType?(value2);
                    break;
                }

                case JsonContractType.Dictionary:
                {
                    this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                    Type type3;
                    Type type4;
                    ReflectionUtils.GetDictionaryKeyValueTypes(type, out type3, out type4);
                    if (type3 != null && this.ContractResolver.ResolveContract(type3).ContractType == JsonContractType.Primitive)
                    {
                        this.CurrentSchema.AdditionalProperties = this.GenerateInternal(type4, Required.Default, false);
                    }
                    break;
                }

                case JsonContractType.Dynamic:
                case JsonContractType.Linq:
                    this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any);
                    break;

                case JsonContractType.Serializable:
                    this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                    this.CurrentSchema.Id   = this.GetTypeId(type, false);
                    this.GenerateISerializableContract(type, (JsonISerializableContract)jsonContract);
                    break;

                default:
                    throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContract));
                }
            }
            return(this.Pop().Schema);
        }