本文整理汇总了C#中JSchema类的典型用法代码示例。如果您正苦于以下问题:C# JSchema类的具体用法?C# JSchema怎么用?C# JSchema使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
JSchema类属于命名空间,在下文中一共展示了JSchema类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: RaiseError
public override void RaiseError(string message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors)
{
if (Errors == null)
Errors = new List<ValidationError>();
Errors.Add(Validator.CreateError(message, errorType, schema, value, childErrors));
}
示例2: RaiseError
public void RaiseError(IFormattable message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors)
{
ValidationError error = CreateError(message, errorType, schema, value, childErrors);
// shared cache information that could be read/populated from multiple threads
// lock to ensure that only one thread writes known schemas
if (Schema.KnownSchemas.Count == 0)
{
lock (Schema.KnownSchemas)
{
if (Schema.KnownSchemas.Count == 0)
{
JSchemaDiscovery discovery = new JSchemaDiscovery(Schema.KnownSchemas, KnownSchemaState.External);
discovery.Discover(Schema, null);
}
}
}
PopulateSchemaId(error);
SchemaValidationEventHandler handler = ValidationEventHandler;
if (handler != null)
handler(_publicValidator, new SchemaValidationEventArgs(error));
else
throw JSchemaValidationException.Create(error);
}
示例3: WriteTo_ReferenceWithRootId
public void WriteTo_ReferenceWithRootId()
{
JSchema nested = new JSchema
{
Type = JSchemaType.Object
};
JSchema s = new JSchema();
s.Id = new Uri("http://www.jnk.com/");
s.Items.Add(nested);
s.Properties["test"] = nested;
string json = s.ToString();
StringAssert.AreEqual(@"{
""id"": ""http://www.jnk.com/"",
""properties"": {
""test"": {
""type"": ""object""
}
},
""items"": {
""$ref"": ""#/properties/test""
}
}", json);
}
示例4: CreateError
protected ValidationError CreateError(string message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors, IJsonLineInfo lineInfo, string path)
{
if (_schemaDiscovery == null)
{
_schemaDiscovery = new JSchemaDiscovery();
_schemaDiscovery.Discover(Schema, null);
}
ValidationError error = new ValidationError();
error.Message = message;
error.ErrorType = errorType;
error.Path = path;
if (lineInfo != null)
{
error.LineNumber = lineInfo.LineNumber;
error.LinePosition = lineInfo.LinePosition;
}
error.Schema = schema;
error.SchemaId = _schemaDiscovery.KnownSchemas.Single(s => s.Schema == schema).Id;
error.SchemaBaseUri = schema.BaseUri;
error.Value = value;
error.ChildErrors = childErrors;
return error;
}
示例5: ArrayBasicValidation_Pass
public void ArrayBasicValidation_Pass()
{
JSchema schema = new JSchema();
schema.Type = JSchemaType.Array;
schema.Items.Add(new JSchema
{
Type = JSchemaType.Integer
});
SchemaValidationEventArgs a = null;
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
JSchemaValidatingWriter validatingWriter = new JSchemaValidatingWriter(writer);
validatingWriter.Schema = schema;
validatingWriter.ValidationEventHandler += (sender, args) => { a = args; };
validatingWriter.WriteStartArray();
validatingWriter.WriteValue(10);
validatingWriter.WriteValue(10);
validatingWriter.WriteEndArray();
Assert.IsNull(a);
Assert.AreEqual("[10,10]", sw.ToString());
}
示例6: GetSchema
/// <summary>
/// Gets a <see cref="JSchema"/> for a <see cref="Type"/>.
/// </summary>
/// <param name="context">The <see cref="Type"/> and associated information used to generate a <see cref="JSchema"/>.</param>
/// <returns>The generated <see cref="JSchema"/>.</returns>
public override JSchema GetSchema(JSchemaTypeGenerationContext context)
{
bool isNullable = ReflectionUtils.IsNullableType(context.ObjectType);
Type t = isNullable ? Nullable.GetUnderlyingType(context.ObjectType) : context.ObjectType;
if (!t.IsEnum())
{
return null;
}
JSchema schema = new JSchema
{
Type = JSchemaType.String
};
if (isNullable && context.Required != Required.Always)
{
schema.Type |= JSchemaType.Null;
}
string[] names = Enum.GetNames(t);
foreach (string name in names)
{
string finalName = EnumUtils.ToEnumName(t, name, CamelCaseText);
schema.Enum.Add(JValue.CreateString(finalName));
}
return schema;
}
示例7: DiscoverInternal
private void DiscoverInternal(JSchema schema, string latestPath)
{
if (schema.Reference != null)
return;
if (_knownSchemas.Any(s => s.Schema == schema))
return;
Uri newScopeId;
Uri schemaKnownId = GetSchemaIdAndNewScopeId(schema, ref latestPath, out newScopeId);
// check whether a schema with the resolved id is already known
// this will be hit when a schema contains duplicate ids or references a schema with a duplicate id
bool existingSchema = _knownSchemas.Any(s => UriComparer.Instance.Equals(s.Id, schemaKnownId));
#if DEBUG
if (_knownSchemas.Any(s => s.Schema == schema))
throw new InvalidOperationException("Schema with id '{0}' already a known schema.".FormatWith(CultureInfo.InvariantCulture, schemaKnownId));
#endif
// add schema to known schemas whether duplicate or not to avoid multiple errors
// the first schema with a duplicate id will be used
_knownSchemas.Add(new KnownSchema(schemaKnownId, schema, _state));
if (existingSchema)
{
if (ValidationErrors != null)
{
ValidationError error = ValidationError.CreateValidationError("Duplicate schema id '{0}' encountered.".FormatWith(CultureInfo.InvariantCulture, schemaKnownId.OriginalString), ErrorType.Id, schema, null, schemaKnownId, null, schema, schema.Path);
ValidationErrors.Add(error);
}
return;
}
_pathStack.Push(new SchemaPath(newScopeId, latestPath));
// discover should happen in the same order as writer except extension data (e.g. definitions)
if (schema._extensionData != null)
{
foreach (KeyValuePair<string, JToken> valuePair in schema._extensionData)
{
DiscoverTokenSchemas(EscapePath(valuePair.Key), valuePair.Value);
}
}
DiscoverSchema(Constants.PropertyNames.AdditionalProperties, schema.AdditionalProperties);
DiscoverSchema(Constants.PropertyNames.AdditionalItems, schema.AdditionalItems);
DiscoverDictionarySchemas(Constants.PropertyNames.Properties, schema._properties);
DiscoverDictionarySchemas(Constants.PropertyNames.PatternProperties, schema._patternProperties);
DiscoverDictionarySchemas(Constants.PropertyNames.Dependencies, schema._dependencies);
DiscoverArraySchemas(Constants.PropertyNames.Items, schema._items);
DiscoverArraySchemas(Constants.PropertyNames.AllOf, schema._allOf);
DiscoverArraySchemas(Constants.PropertyNames.AnyOf, schema._anyOf);
DiscoverArraySchemas(Constants.PropertyNames.OneOf, schema._oneOf);
DiscoverSchema(Constants.PropertyNames.Not, schema.Not);
_pathStack.Pop();
}
示例8: CreateTokenScope
public static SchemaScope CreateTokenScope(JsonToken token, JSchema schema, ContextBase context, Scope parent, int depth)
{
SchemaScope scope;
switch (token)
{
case JsonToken.StartObject:
var objectScope = new ObjectScope(context, parent, depth, schema);
context.Scopes.Add(objectScope);
objectScope.InitializeScopes(token);
scope = objectScope;
break;
case JsonToken.StartArray:
case JsonToken.StartConstructor:
scope = new ArrayScope(context, parent, depth, schema);
context.Scopes.Add(scope);
break;
default:
scope = new PrimativeScope(context, parent, depth, schema);
context.Scopes.Add(scope);
break;
}
if (schema._allOf != null && schema._allOf.Count > 0)
{
AllOfScope allOfScope = new AllOfScope(scope, context, depth);
context.Scopes.Add(allOfScope);
allOfScope.InitializeScopes(token, schema._allOf);
}
if (schema._anyOf != null && schema._anyOf.Count > 0)
{
AnyOfScope anyOfScope = new AnyOfScope(scope, context, depth);
context.Scopes.Add(anyOfScope);
anyOfScope.InitializeScopes(token, schema._anyOf);
}
if (schema._oneOf != null && schema._oneOf.Count > 0)
{
OneOfScope oneOfScope = new OneOfScope(scope, context, depth);
context.Scopes.Add(oneOfScope);
oneOfScope.InitializeScopes(token, schema._oneOf);
}
if (schema.Not != null)
{
NotScope notScope = new NotScope(scope, context, depth);
context.Scopes.Add(notScope);
notScope.InitializeScopes(token, Enumerable.Repeat(schema.Not, 1));
}
return scope;
}
示例9: Discover
public void Discover(JSchema schema, Uri uri, string path = "#")
{
Uri resolvedUri = uri ?? schema.Id ?? new Uri(string.Empty, UriKind.RelativeOrAbsolute);
_pathStack.Push(new SchemaPath(resolvedUri, string.Empty));
DiscoverInternal(schema, path);
_pathStack.Pop();
}
示例10: RaiseError
public void RaiseError(string message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors)
{
ValidationError error = CreateError(message, errorType, schema, value, childErrors);
SchemaValidationEventHandler handler = ValidationEventHandler;
if (handler != null)
handler(_publicValidator, new SchemaValidationEventArgs(error));
else
throw JSchemaValidationException.Create(error);
}
示例11: SetResolvedSchema
public void SetResolvedSchema(JSchema schema)
{
foreach (Action<JSchema> setSchema in SetSchemas)
{
setSchema(schema);
}
// successful
_success = (schema.Reference == null);
}
示例12: WriteTo_MaximumLength_Large
public void WriteTo_MaximumLength_Large()
{
JSchema s = new JSchema
{
MaximumLength = long.MaxValue
};
string json = s.ToString();
StringAssert.AreEqual(@"{
""maxLength"": 9223372036854775807
}", json);
}
示例13: WriteTo_UniqueItems
public void WriteTo_UniqueItems()
{
JSchema s = new JSchema
{
UniqueItems = true
};
string json = s.ToString();
StringAssert.AreEqual(@"{
""uniqueItems"": true
}", json);
}
示例14: ObjectScope
public ObjectScope(ContextBase context, Scope parent, int initialDepth, JSchema schema)
: base(context, parent, initialDepth, schema)
{
if (schema._required != null)
_requiredProperties = schema._required.ToList();
if (schema._dependencies != null && schema._dependencies.Count > 0)
{
_readProperties = new List<string>();
if (schema._dependencies.Values.OfType<JSchema>().Any())
_dependencyScopes = new Dictionary<string, SchemaScope>();
}
}
示例15: Example
public void Example()
{
#region Usage
JSchema schema = new JSchema
{
Type = JSchemaType.Object,
Properties =
{
{ "name", new JSchema { Type = JSchemaType.String } },
{
"hobbies", new JSchema
{
Type = JSchemaType.Array,
Items = { new JSchema { Type = JSchemaType.String } }
}
},
}
};
string schemaJson = schema.ToString();
Console.WriteLine(schemaJson);
// {
// "type": "object",
// "properties": {
// "name": {
// "type": "string"
// },
// "hobbies": {
// "type": "array",
// "items": {
// "type": "string"
// }
// }
// }
// }
JObject person = JObject.Parse(@"{
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}");
bool valid = person.IsValid(schema);
Console.WriteLine(valid);
// true
#endregion
Assert.IsTrue(valid);
}