Generate() публичный Метод

Generate a JsonSchema from the specified type.
public Generate ( Type type ) : JsonSchema
type System.Type The type to generate a from.
Результат JsonSchema
Пример #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 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;
            }
        }
Пример #5
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
		}
Пример #6
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;
        }
Пример #7
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"
            //     }
            //   }
            // }
        }
Пример #8
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";
            }
        }