public TripField(string name, TripType type, long identifier, Required required) { Name = Enforce.IsNotNull<string>(name, "name"); Type = Enforce.IsNotNull<TripType>(type, "type"); Identifier = identifier; Required = required; }
private JSchema CreateSchemaWithFormat(Type type, Required required, string format) { JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(type, required != Required.Always); schema.Format = format; return schema; }
public void Should_fix_all_args() { var pattern = new Required(new Argument("N"), new Argument("N")); Assert.AreEqual(pattern.Children[0], pattern.Children[1]); Assert.AreNotSame(pattern.Children[0], pattern.Children[1]); pattern.FixIdentities(); Assert.AreSame(pattern.Children[0], pattern.Children[1]); }
/// <summary> /// Initializes a new instance of the <see cref="JSchemaTypeGenerationContext"/> class. /// </summary> /// <param name="objectType">The object type.</param> /// <param name="required">The required state.</param> /// <param name="memberProperty">The member property.</param> /// <param name="parentContract">The parent contract.</param> /// <param name="generator">The current <see cref="JSchemaGenerator"/>.</param> public JSchemaTypeGenerationContext(Type objectType, Required required, JsonProperty memberProperty, JsonContainerContract parentContract, JSchemaGenerator generator) { _objectType = objectType; _required = required; _memberProperty = memberProperty; _parentContract = parentContract; _generator = generator; }
public void When_Required_And_StringValue_Is_Null() { var customer = new Customer(); var validator = new Required<Customer, string>(); var context = new RuleValidatorContext<Customer, string>(customer, "Name", customer.Name, null, null); //Validate the validator only, return true of no error returned var result = validator.Validate(context, null); Assert.IsNotEmpty(result.Message); }
public void When_Required_And_CollectionValue_Is_Null() { var customer = new Customer(); var validator = new Required<Customer, IEnumerable>(); var context = new RuleValidatorContext<Customer, IEnumerable>(customer, "Contacts", customer.Contacts, null, null); //Validate the validator only, return true of no error returned var result = validator.Validate(context, null); Assert.IsNotEmpty(result.Message); }
public void When_Required_And_StringValue_Is_Null() { var customer = new Customer(); var validator = new Required<Customer, string>(); var context = new RuleValidatorContext<Customer, string>(customer, "Name", customer.Name, null, ValidationLevelType.Error, null); var notification = new ValidationNotification(); //Validate the validator only, return true of no error returned validator.Validate(context, null, notification); Assert.IsNotEmpty(notification.Errors[0].Message); }
public void When_Required_And_CollectionValue_Is_Empty_IsInvalid() { var customer = new Customer() {Contacts = new List<Contact>()}; var validator = new Required<Customer, IEnumerable>(); var context = new RuleValidatorContext<Customer, IEnumerable>(customer, "Contacts", customer.Contacts, null, ValidationLevelType.Error, null); var notification = new ValidationNotification(); //Validate the validator only, return true of no error returned validator.Validate(context, null, notification); Assert.IsNotEmpty(notification.Errors[0].Message); }
/// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { unchecked { var hashCode = Type.GetHashCode(); hashCode = (hashCode * 397) ^ (Id?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Schema?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Comment?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Title?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Description?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Default?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ MultipleOf.GetHashCode(); hashCode = (hashCode * 397) ^ Maximum.GetHashCode(); hashCode = (hashCode * 397) ^ ExclusiveMaximum.GetHashCode(); hashCode = (hashCode * 397) ^ Minimum.GetHashCode(); hashCode = (hashCode * 397) ^ ExclusiveMinimum.GetHashCode(); hashCode = (hashCode * 397) ^ (MaxLength?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (MinLength?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Pattern?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (AdditionalItems?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Items?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (MaxItems?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (MinItems?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (UniqueItems?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Contains?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (AdditionalProperties?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Definitions?.GetCollectionHashCode().GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Properties?.GetCollectionHashCode() ?? 0); hashCode = (hashCode * 397) ^ (PatternProperties?.GetCollectionHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Dependencies?.GetCollectionHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Const?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Enum?.GetCollectionHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Format?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (ContentMediaType?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (ContentEncoding?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (If?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Then?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Else?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (AllOf?.GetCollectionHashCode() ?? 0); hashCode = (hashCode * 397) ^ (AnyOf?.GetCollectionHashCode() ?? 0); hashCode = (hashCode * 397) ^ (OneOf?.GetCollectionHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Not?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Required?.GetCollectionHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Examples?.GetCollectionHashCode() ?? 0); return(hashCode); } }
public void When_Required_And_CollectionValue_Is_Empty_IsInvalid() { var customer = new Customer() { Contacts = new List <Contact>() }; var validator = new Required <Customer, IEnumerable>(); var context = new RuleValidatorContext <Customer, IEnumerable>(customer, "Contacts", customer.Contacts, null, ValidationLevelType.Error, null); var notification = new ValidationNotification(); //Validate the validator only, return true of no error returned validator.Validate(context, null, notification); Assert.IsNotEmpty(notification.Errors[0].Message); }
internal JSchemaTypeGenerationContext( Type objectType, Required required, JsonProperty?memberProperty, JsonContainerContract?parentContract, JSchemaGeneratorInternal generatorInternal, string?schemaTitle, string?schemaDescription) { SchemaTitle = schemaTitle; SchemaDescription = schemaDescription; ObjectType = objectType; Required = required; MemberProperty = memberProperty; ParentContract = parentContract; _generatorInternal = generatorInternal; }
/// <summary> /// 保存XML信息 /// </summary> /// <param name="doc"></param> /// <returns></returns> public XmlElement ToXml(XmlDocument doc) { XmlElement xe = doc.CreateElement("Parameter"); xe.SetAttribute("name", Name); xe.SetAttribute("title", Title); xe.SetAttribute("type", Type); xe.SetAttribute("maximum", Maximum); xe.SetAttribute("minimum", Minium); xe.SetAttribute("length", Length.ToString()); xe.SetAttribute("description", Description); xe.SetAttribute("required", Required.ToString()); xe.SetAttribute("defaultValue", DefaultValue); xe.SetAttribute("supportCopy", SupportCopy.ToString()); xe.SetAttribute("data", Data); return(xe); }
public JSchema Generate(Type type, Required required) { JSchema schema = GenerateInternal(type, required, null, null); if (_generator.SchemaLocationHandling == SchemaLocationHandling.Definitions) { if (_typeSchemas.Count > 1) { JToken definitions; if (!schema.ExtensionData.TryGetValue("definitions", out definitions)) { definitions = new JObject(); schema.ExtensionData["definitions"] = definitions; } foreach (TypeSchema t in _typeSchemas) { if (t.Schema == schema) { continue; } string id; if (t.Schema.Id != null) { id = t.Schema.Id.OriginalString; } else { id = t.Key.Type.Name; int i = 1; while (definitions[id] != null) { id = t.Key.Type.Name + "-" + i; i++; } } definitions[id] = t.Schema; } } } return(schema); }
public JSchema Generate(Type type, Required required) { JSchema schema = GenerateInternal(type, required, null, null); if (_generator.SchemaLocationHandling == SchemaLocationHandling.Definitions) { if (_typeSchemas.Count > 1) { JToken definitions; if (!schema.ExtensionData.TryGetValue("definitions", out definitions)) { definitions = new JObject(); schema.ExtensionData["definitions"] = definitions; } foreach (TypeSchema t in _typeSchemas) { if (t.Schema == schema) { continue; } string id; if (t.Schema.Id != null) { id = t.Schema.Id.OriginalString; } else { id = t.Key.Type.Name; int i = 1; while (definitions[id] != null) { id = t.Key.Type.Name + "-" + i; i++; } } definitions[id] = t.Schema; } } } return schema; }
public DictionarySourceDataCollection(Dictionary <string, Stream> data) { mData = data; Names .Where(i => mData.Keys.Contains(i.Value) == true) .ForEach(i => mStreams.Add(i.Key, ((Func <string, Stream>)GetStream).Curry()(i.Value))); var missing = Required.Except(mStreams.Keys); if (missing.Count() > 0) { if (!(missing.Count() == 1 && missing.Contains(TransitFileType.Calendar) == true)) { throw new ArgumentOutOfRangeException("Missing mandatory data."); } } }
public string WriteObjectConstructor() { var fields = string.Join(",", Fields.Select(field => field.WriteConstructor())); List <string> parameters = new List <string>() { Name.WrapInQuotes(), Unique.ToBoolString(), $"IdfObjectFormat.{Format}", Obsolete.ToBoolString(), MinNumberOfFields == null ? "null" : MinNumberOfFields.Value.ToString(), Required.ToBoolString(), $"new List<IdfField> {{{fields}}}", Extensible.ToBoolString(), TotalNumberOfDefinedFields.ToString() }; return($"new IdfObject({string.Join(",", parameters)} )"); }
public SchemaObject(EventSchema eventSchema, string name, string @namespace) : this() { Type = SchemaObjectType.Object; Title = name; Description = string.Format("JSON schema for {0}/{1}.", @namespace, name); if (eventSchema.Properties == null) { return; } if (eventSchema.ValidateByQuery) { ValidationQueryUrl = eventSchema.ValidationQueryUrl; } foreach (var property in eventSchema.Properties) { var validated = isPropertyValidated(property.Value); var propertyType = getPropertyType(property.Value); ISchemaPropertyMetadata metadata; if (validated) { var validationMetadata = getValidatedPropertyMetadata(property.Value, propertyType); if (validationMetadata.Required.HasValue && validationMetadata.Required.Value) { Required.Add(property.Key); } metadata = validationMetadata; } else { metadata = new SimplePropertyMetadata(propertyType); } Properties.Add(property.Key, metadata); } }
private bool method_18(JsonWriter jsonWriter_0, object object_0, JsonContainerContract jsonContainerContract_0, JsonProperty jsonProperty_0, JsonProperty jsonProperty_1, out JsonContract jsonContract_1, out object object_1) { if ((!jsonProperty_1.Ignored && jsonProperty_1.Readable) && (this.method_37(jsonWriter_0, jsonProperty_1, object_0) && this.method_38(jsonWriter_0, jsonProperty_1, object_0))) { if (jsonProperty_1.JsonContract_0 == null) { jsonProperty_1.JsonContract_0 = base.jsonSerializer_0.icontractResolver_0.ResolveContract(jsonProperty_1.PropertyType); } object_1 = jsonProperty_1.ValueProvider.GetValue(object_0); jsonContract_1 = jsonProperty_1.JsonContract_0.bool_2 ? jsonProperty_1.JsonContract_0 : this.method_5(object_1); if (this.method_10(object_1, jsonProperty_1)) { if (this.method_9(object_1, jsonProperty_1, jsonContract_1, jsonContainerContract_0, jsonProperty_0)) { jsonProperty_1.method_2(jsonWriter_0); this.method_12(jsonWriter_0, object_1); return(false); } if (!this.method_11(jsonWriter_0, object_1, jsonProperty_1, jsonContract_1, jsonContainerContract_0, jsonProperty_0)) { return(false); } if (object_1 == null) { Required? nullable3; JsonObjectContract contract = jsonContainerContract_0 as JsonObjectContract; Required? nullable = jsonProperty_1.nullable_0; if (!nullable.HasValue) { nullable3 = (contract != null) ? contract.ItemRequired : null; } Required required = nullable3.HasValue ? nullable.GetValueOrDefault() : Required.Default; if (required == Required.Always) { throw JsonSerializationException.smethod_3(null, jsonWriter_0.String_0, "Cannot write a null value for property '{0}'. Property requires a value.".smethod_0(CultureInfo.InvariantCulture, jsonProperty_1.PropertyName), null); } } return(true); } } jsonContract_1 = null; object_1 = null; return(false); }
private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue) { if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value)) { if (property.PropertyContract == null) { property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType); } memberValue = property.ValueProvider.GetValue(value); memberContract = (property.PropertyContract.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue); if (ShouldWriteProperty(memberValue, property)) { if (ShouldWriteReference(memberValue, property, memberContract, contract, member)) { property.WritePropertyName(writer); WriteReference(writer, memberValue); return(false); } if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member)) { return(false); } if (memberValue == null) { JsonObjectContract objectContract = contract as JsonObjectContract; Required resolvedRequired = property._required ?? ((objectContract != null) ? objectContract.ItemRequired : null) ?? Required.Default; if (resolvedRequired == Required.Always) { throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null); } } return(true); } } memberContract = null; memberValue = null; return(false); }
static JsonProperty CreateProperty <TProp> (String propName, Func <T, TProp> get, Required required = Required.Always, DefaultValueHandling defaultValueHandling = DefaultValueHandling.Include, Object?defaultValue = null) => new JsonProperty { PropertyName = propName, UnderlyingName = propName, PropertyType = typeof(TProp), DeclaringType = typeof(T), Readable = true, Writable = false, ValueProvider = new ReadOnlyValueProvider <T, TProp>(get), Required = required, DefaultValueHandling = defaultValueHandling, DefaultValue = defaultValue };
internal string Check() { var result = new StringBuilder(); foreach (var missingRequirement in Required.Where(req => !Provided.Contains(req))) { result.AppendLine("ERROR: " + missingRequirement.Source + " requires " + Context + " " + missingRequirement.Value + " but it's missing"); } if (CheckForAdditionals) { foreach (var additional in Provided.Where(req => !Required.Contains(req))) { result.AppendLine("WARN: " + additional.Source + " provides " + Context + " " + additional.Value + " but it's never used"); } } return(result.ToString()); }
public XmlNode GenerateXML() { // Create XML Node and Attributes XmlDocument d = new XmlDocument(); XmlNode output = d.CreateNode("element", "SoftwareGroup", null); XmlAttribute _default = d.CreateAttribute("Default"); XmlAttribute id = d.CreateAttribute("Id"); XmlAttribute label = d.CreateAttribute("Label"); XmlAttribute required = d.CreateAttribute("Required"); XmlAttribute condition = d.CreateAttribute("Condition"); // Assign Attribute Values _default.Value = Default.ToString(); id.Value = Id; label.Value = Label; required.Value = Required.ToString(); condition.Value = Condition; // Append Attributes if (null != Default) { output.Attributes.Append(_default); } output.Attributes.Append(id); output.Attributes.Append(label); if (null != Required) { output.Attributes.Append(required); } if (!string.IsNullOrEmpty(Condition)) { output.Attributes.Append(condition); } // Append Children foreach (ISoftwareRef softwareRef in SubChildren) { XmlNode importNode = d.ImportNode(softwareRef.GenerateXML(), true); output.AppendChild(importNode); } return(output); }
public override string ToString() { return("<Data>" + "<Param key=\"ParentWebID\">" + ParentWebID.ToString() + "</Param>" + "<Param key=\"LookupWebID\">" + LookupWebID.ToString() + "</Param>" + "<Param key=\"LookupListID\">" + LookupListID.ToString() + "</Param>" + "<Param key=\"LookupFieldInternalName\">" + LookupFieldInternalName + "</Param>" + "<Param key=\"LookupFieldID\">" + LookupFieldSourceFieldID.ToString() + "</Param>" + "<Param key=\"IsMultiSelect\">" + IsMultiSelect + "</Param>" + "<Param key=\"ListID\">" + ListID.ToString() + "</Param>" + "<Param key=\"ItemID\">" + ItemID.ToString() + "</Param>" + "<Param key=\"SourceControlID\">" + (!string.IsNullOrEmpty(SourceControlID) ? SourceControlID : string.Empty) + "</Param>" + "<Param key=\"SelectCandidateID\">" + (!string.IsNullOrEmpty(SelectCandidateID) ? SelectCandidateID : string.Empty) + "</Param>" + "<Param key=\"AddButtonID\">" + (!string.IsNullOrEmpty(AddButtonID) ? AddButtonID : string.Empty) + "</Param>" + "<Param key=\"RemoveButtonID\">" + (!string.IsNullOrEmpty(RemoveButtonID) ? RemoveButtonID : string.Empty) + "</Param>" + "<Param key=\"SelectResultID\">" + (!string.IsNullOrEmpty(SelectResultID) ? SelectResultID : string.Empty) + "</Param>" + "<Param key=\"Required\">" + Required.ToString() + "</Param>" + "</Data>"); }
public override bool Equals(object obj) { var other = obj as IdentityResourceModel; if (other == null) { return(false); } var result = UserClaims.SafeListEquals(other.UserClaims) && Description.SafeEquals(other.Description) && DisplayName.SafeEquals(other.DisplayName) && Enabled.SafeEquals(other.Enabled) && Emphasize.SafeEquals(other.Emphasize) && Required.SafeEquals(other.Required) && ShowInDiscoveryDocument.SafeEquals(other.ShowInDiscoveryDocument); return(result); }
// Token: 0x06000998 RID: 2456 RVA: 0x0003748C File Offset: 0x0003568C private bool method_20(JsonWriter jsonWriter_0, object object_0, JsonContainerContract jsonContainerContract_0, JsonProperty jsonProperty_0, JsonProperty jsonProperty_1, out JsonContract jsonContract_0, out object object_1) { if (!jsonProperty_1.Ignored && jsonProperty_1.Readable && this.ShouldSerialize(jsonWriter_0, jsonProperty_1, object_0) && this.method_40(jsonWriter_0, jsonProperty_1, object_0)) { if (jsonProperty_1.method_0() == null) { jsonProperty_1.method_1(this.jsonSerializer_0.icontractResolver_0.ResolveContract(jsonProperty_1.PropertyType)); } object_1 = jsonProperty_1.ValueProvider.GetValue(object_0); jsonContract_0 = (jsonProperty_1.method_0().bool_4 ? jsonProperty_1.method_0() : this.method_7(object_1)); if (this.method_12(object_1, jsonContainerContract_0 as JsonObjectContract, jsonProperty_1)) { if (this.method_11(object_1, jsonProperty_1, jsonContract_0, jsonContainerContract_0, jsonProperty_0)) { jsonProperty_1.method_3(jsonWriter_0); this.method_14(jsonWriter_0, object_1); return(false); } if (!this.method_13(jsonWriter_0, object_1, jsonProperty_1, jsonContract_0, jsonContainerContract_0, jsonProperty_0)) { return(false); } if (object_1 == null) { JsonObjectContract jsonObjectContract = jsonContainerContract_0 as JsonObjectContract; Required required = jsonProperty_1.nullable_0 ?? (((jsonObjectContract != null) ? jsonObjectContract.ItemRequired : null) ?? Required.Default); if (required == Required.Always) { throw JsonSerializationException.Create(null, jsonWriter_0.xEuXaafal7(), "Cannot write a null value for property '{0}'. Property requires a value.".smethod_0(CultureInfo.InvariantCulture, jsonProperty_1.PropertyName), null); } if (required == Required.DisallowNull) { throw JsonSerializationException.Create(null, jsonWriter_0.xEuXaafal7(), "Cannot write a null value for property '{0}'. Property requires a non-null value.".smethod_0(CultureInfo.InvariantCulture, jsonProperty_1.PropertyName), null); } } return(true); } } jsonContract_0 = null; object_1 = null; return(false); }
public override int GetHashCode() { unchecked { var hashCode = (Name != null ? Name.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Label != null ? Label.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Icon != null ? Icon.GetHashCode() : 0); hashCode = (hashCode * 397) ^ DisplayLabel.GetHashCode(); hashCode = (hashCode * 397) ^ LabelStacked.GetHashCode(); hashCode = (hashCode * 397) ^ DisplayIcon.GetHashCode(); hashCode = (hashCode * 397) ^ IconStacked.GetHashCode(); hashCode = (hashCode * 397) ^ Required.GetHashCode(); hashCode = (hashCode * 397) ^ IsStart.GetHashCode(); hashCode = (hashCode * 397) ^ (Value != null ? Value.GetHashCode() : 0); hashCode = (hashCode * 397) ^ NotVisible.GetHashCode(); hashCode = (hashCode * 397) ^ NotEnabled.GetHashCode(); hashCode = (hashCode * 397) ^ (ErrorMsg != null ? ErrorMsg.GetHashCode() : 0); return(hashCode); } }
/// <summary> /// Comapares list of required properties of this model /// </summary> /// <param name="context">Comaprision Context</param> /// <param name="priorSchema">Schema of the old model</param> private void CompareRequired(ComparisonContext <ServiceDefinition> context, Schema priorSchema) { if (Required == null) { return; } if (Required != null && priorSchema.Required == null) { context.LogBreakingChange(ComparisonMessages.AddedRequiredProperty, String.Join(", ", Required)); return; } List <string> addedRequiredProperties = Required.Except(priorSchema.Required).ToList(); if (addedRequiredProperties.Count > 0) { context.LogBreakingChange(ComparisonMessages.AddedRequiredProperty, String.Join(", ", addedRequiredProperties)); } }
protected override void Render(HtmlTextWriter writer) { CssClass = CssClass + " validator"; if (MinLength > 0) { Attributes["minlength"] = MinLength.ToString(); } if (MaxLength > 0 && MaxLength > MinLength) { Attributes["maxlength"] = MaxLength.ToString(); } if (!string.IsNullOrEmpty(Group)) { Attributes["group"] = Group; } if (!string.IsNullOrEmpty(GroupMessage)) { Attributes["groupmessage"] = GroupMessage; } if (Required) { Attributes["required"] = Required.ToString(); } if (CustomFunction == null) { CustomFunction = Function.ToString(); } Attributes["function"] = CustomFunction; if (!string.IsNullOrEmpty(ControlToValidate)) { Attributes["validates"] = ControlToValidate; } base.Render(writer); }
protected override void RenderEditMode(HtmlTextWriter writer) { if (ListEntries != null && ListEntries.Any()) { foreach (ListEntryInfo item in ListEntries) { Regions.Items.Add(new ListItem() { Text = item.Text, Value = item.EntryID.ToString() }); } } ControlStyle.AddAttributesToRender(writer); writer.AddAttribute("data-name", Name); writer.AddAttribute("data-list", "Region"); writer.AddAttribute("data-category", Category); writer.AddAttribute("data-required", Required.ToString().ToLowerInvariant()); writer.RenderBeginTag(HtmlTextWriterTag.Div); RenderChildren(writer); writer.RenderEndTag(); }
protected override void ProcessRecord() { var scope = new Scope() { Claims = Claims, ClaimsRule = ClaimsRule, Description = Description, DisplayName = DisplayName, Emphasize = Emphasize.GetValueOrDefault(DefaultValues.Emphasize), Enabled = Enabled.GetValueOrDefault(DefaultValues.Enabled), IncludeAllClaimsForUser = IncludeAllClaimsForUser.GetValueOrDefault(DefaultValues.IncludeAllClaimsForUser), Name = Name, Required = Required.GetValueOrDefault(DefaultValues.Required), ShowInDiscoveryDocument = ShowInDiscoveryDocument.GetValueOrDefault(DefaultValues.ShowInDiscoveryDocument), Type = Type.GetValueOrDefault(DefaultValues.Type) }; WriteObject(scope); }
public override int GetHashCode() { unchecked { var hashCode = Name != null?Name.GetHashCode() : 0; hashCode = (hashCode * 397) ^ (int)Type; hashCode = (hashCode * 397) ^ (From != null ? From.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (int)Rel; hashCode = (hashCode * 397) ^ (int)Scope; hashCode = (hashCode * 397) ^ (Default != null ? Default.GetHashCode() : 0); hashCode = (hashCode * 397) ^ Nullable.GetHashCode(); hashCode = (hashCode * 397) ^ Required.GetHashCode(); hashCode = (hashCode * 397) ^ Disabled.GetHashCode(); hashCode = (hashCode * 397) ^ Protected.GetHashCode(); hashCode = (hashCode * 397) ^ Personal.GetHashCode(); hashCode = (hashCode * 397) ^ (Annotations != null ? Annotations.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Description != null ? Description.GetHashCode() : 0); return(hashCode); } }
//public readonly JToken MinValue; //public readonly JToken MaxValue; //public readonly Type EnumType; public TypeSchemaKey( Type type, Required required, //string pattern, //string format, int?minLength, int?maxLength //JToken minValue, //JToken maxValue, //Type enumType ) { Type = type; Required = required; //Pattern = pattern; //Format = format; MinLength = minLength; MaxLength = maxLength; //MinValue = minValue; //MaxValue = maxValue; //EnumType = enumType; }
public XmlNode GenerateXML() { // Create XML Node and Attributes XmlDocument d = new XmlDocument(); XmlNode output = d.CreateNode("element", "SoftwareRef", null); XmlAttribute id = d.CreateAttribute("Id"); XmlAttribute hidden = d.CreateAttribute("Hidden"); XmlAttribute _default = d.CreateAttribute("Default"); XmlAttribute required = d.CreateAttribute("Required"); XmlAttribute condition = d.CreateAttribute("Condition"); // Set Attribute Values id.Value = Id; hidden.Value = Hidden.ToString(); _default.Value = Default.ToString(); required.Value = Required.ToString(); condition.Value = Condition; // Append Attributes output.Attributes.Append(id); if (null != Hidden) { output.Attributes.Append(hidden); } if (null != Default) { output.Attributes.Append(_default); } if (null != Required) { output.Attributes.Append(required); } if (!string.IsNullOrEmpty(Condition)) { output.Attributes.Append(condition); } return(output); }
private void GenerateObjectSchema(JSchema schema, Type type, JsonObjectContract contract) { foreach (JsonProperty property in contract.Properties) { if (!property.Ignored) { bool optional = property.NullValueHandling == NullValueHandling.Ignore || HasFlag(property.DefaultValueHandling.GetValueOrDefault(), DefaultValueHandling.Ignore) || property.ShouldSerialize != null || property.GetIsSpecified != null; Required required = property.Required; if (DataAnnotationHelpers.GetRequired(property)) { required = Required.Always; } JSchema propertySchema = GenerateInternal(property.PropertyType, required, property, contract); if (property.DefaultValue != null) { propertySchema.Default = JToken.FromObject(property.DefaultValue); } schema.Properties.Add(property.PropertyName, propertySchema); if (!optional) { schema.Required.Add(property.PropertyName); } } } if (type.IsSealed()) { schema.AllowAdditionalProperties = false; } }
private OpenApiSchema CreatePropertySchema( JsonProperty jsonProperty, IEnumerable <object> customAttributes, Required required, SchemaRepository schemaRepository) { var typeSchema = _schemaGenerator.GenerateSchema(jsonProperty.PropertyType, schemaRepository); // If it's a referenced/shared schema, "extend" it using allOf so that contextual metadata (e.g. property attributes) can be applied var propertySchema = (typeSchema.Reference != null) ? new OpenApiSchema { AllOf = new[] { typeSchema } } : typeSchema; propertySchema.ReadOnly = jsonProperty.Readable && !jsonProperty.Writable; propertySchema.WriteOnly = !jsonProperty.Readable && jsonProperty.Writable; propertySchema.Nullable = (required == Required.Default || required == Required.AllowNull) && jsonProperty.PropertyType.IsReferenceOrNullableType(); propertySchema.ApplyCustomAttributes(customAttributes); return(propertySchema); }
protected override void ProcessRecord() { var scope = new Scope() { Claims = (Claims ?? new ScopeClaim[] {}).ToList(), ClaimsRule = ClaimsRule, Description = Description, DisplayName = DisplayName, Emphasize = Emphasize.GetValueOrDefault(DefaultValues.Emphasize), Enabled = Enabled.GetValueOrDefault(DefaultValues.Enabled), IncludeAllClaimsForUser = IncludeAllClaimsForUser.GetValueOrDefault(DefaultValues.IncludeAllClaimsForUser), Name = Name, Required = Required.GetValueOrDefault(DefaultValues.Required), ShowInDiscoveryDocument = ShowInDiscoveryDocument.GetValueOrDefault(DefaultValues.ShowInDiscoveryDocument), Type = Type.GetValueOrDefault(DefaultValues.Type), AllowUnrestrictedIntrospection = AllowUnrestrictedIntrospection.GetValueOrDefault(DefaultValues.AllowUnrestrictedIntrospection), ScopeSecrets = (ScopeSecrets ?? new Secret[] { }).ToList() }; WriteObject(scope); }
public void Merge(IJsonSchemaValidator obj) { var rhs = obj as JsonObjectValidator; if (rhs == null) { throw new ArgumentException(); } foreach (var x in rhs.Required) { Required.Add(x); } if (rhs.AdditionalProperties != null) { if (AdditionalProperties != null) { throw new NotImplementedException(); } AdditionalProperties = rhs.AdditionalProperties; } }
protected void btnPrint_Click(object sender, EventArgs e) { Required require = new Required(); require.ItemID = Convert.ToInt32(DDLItem.SelectedValue); if (txtAmount.Text != null) { require.Price = Convert.ToInt32(txtAmount.Text); } if (txtDate.Text != null && !string.IsNullOrEmpty(txtDate.Text.ToString())) { if (CalendarFrom.CultureName == "ar-SA") { require.Date = MyDate.convertHijriToGregorian(txtDate.Text); } else { require.Date = DateTime.ParseExact(txtDate.Text, "yyyy/MM/dd", CultureInfo.CreateSpecificCulture("ar-EG")); } } int SchoolID = SchoolInfo.getId(); require.SchoolId = SchoolID; require.SemesterId = MyDate.getCurrentSemesterId(); onlineSchool.Requireds.Add(require); onlineSchool.SaveChanges(); ClientScript.RegisterStartupScript(this.GetType(), "openModal", "<script> addSuccess(' !! تمت الاضافة بنجاح'); </script>", false); }
/// <summary> /// Add the provided required property names to this JSON schema's list of required property names. /// </summary> /// <param name="requiredPropertyName"></param> /// <param name="extraRequiredPropertyNames"></param> public JsonSchema AddRequired(string requiredPropertyName, params string[] extraRequiredPropertyNames) { if (Properties == null || !Properties.ContainsKey(requiredPropertyName)) { throw new ArgumentException("No property exists with the provided requiredPropertyName (" + requiredPropertyName + ")", nameof(requiredPropertyName)); } if (Required == null) { Required = new List <string>(); } if (Required.Contains(requiredPropertyName)) { throw new ArgumentException("'" + requiredPropertyName + "' is already a required property.", "requiredPropertyName"); } Required.Add(requiredPropertyName); if (extraRequiredPropertyNames != null) { foreach (string extraRequiredPropertyName in extraRequiredPropertyNames) { if (Properties == null || !Properties.ContainsKey(extraRequiredPropertyName)) { throw new ArgumentException("No property exists with the provided extraRequiredPropertyName (" + extraRequiredPropertyName + ")", "extraRequiredPropertyNames"); } if (Required.Contains(extraRequiredPropertyName)) { throw new ArgumentException("'" + extraRequiredPropertyName + "' is already a required property.", "extraRequiredPropertyNames"); } Required.Add(extraRequiredPropertyName); } } return(this); }
private static TypeSchemaKey CreateKey(Required valueRequired, JsonProperty memberProperty, JsonContract contract) { int? minLength = DataAnnotationHelpers.GetMinLength(memberProperty); int? maxLength = DataAnnotationHelpers.GetMaxLength(memberProperty); Required resolvedRequired; switch (valueRequired) { case Required.Default: case Required.AllowNull: resolvedRequired = Required.AllowNull; break; case Required.Always: case Required.DisallowNull: resolvedRequired = Required.DisallowNull; break; default: throw new ArgumentOutOfRangeException("valueRequired"); } TypeSchemaKey key = new TypeSchemaKey(contract.UnderlyingType, resolvedRequired, minLength, maxLength); return key; }
private JsonSchema GenerateInternal(Type type, Required valueRequired) { ValidationUtils.ArgumentNotNull(type, "type"); string resolvedId = GetTypeId(type, false); string explicitId = GetTypeId(type, true); if (!string.IsNullOrEmpty(resolvedId)) { JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId); if (resolvedSchema != null) return resolvedSchema; } // test for unresolved circular reference if (_stack.Any(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, type)); } Push(new TypeSchema(type, new JsonSchema())); if (explicitId != null) CurrentSchema.Id = explicitId; CurrentSchema.Title = GetTitle(type); CurrentSchema.Description = GetDescription(type); if (CollectionUtils.IsDictionaryType(type)) { // TODO: include null CurrentSchema.Type = JsonSchemaType.Object; Type keyType; Type valueType; ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType); if (keyType != null) { // can be converted to a string if (typeof (IConvertible).IsAssignableFrom(keyType)) { CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default); } } } else if (CollectionUtils.IsCollectionType(type)) { // TODO: include null CurrentSchema.Type = JsonSchemaType.Array; CurrentSchema.Id = GetTypeId(type, false); JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute; bool allowNullItem = (arrayAttribute != null) ? arrayAttribute.AllowNullItems : false; Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); if (collectionItemType != null) { CurrentSchema.Items = new List<JsonSchema>(); CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default)); } } else { CurrentSchema.Type = GetJsonSchemaType(type, valueRequired); if (HasFlag(CurrentSchema.Type, JsonSchemaType.Object)) { CurrentSchema.Id = GetTypeId(type, false); JsonObjectContract contract = ContractResolver.ResolveContract(type) as JsonObjectContract; if (contract == null) throw new Exception("Could not resolve contract for '{0}'.".FormatWith(CultureInfo.InvariantCulture, type)); CurrentSchema.Properties = new Dictionary<string, JsonSchema>(); foreach (JsonProperty property in contract.Properties) { if (!property.Ignored) { JsonSchema propertySchema = GenerateInternal(property.PropertyType, property.Required); if (property.DefaultValue != null) propertySchema.Default = JToken.FromObject(property.DefaultValue); CurrentSchema.Properties.Add(property.PropertyName, propertySchema); } } if (type.IsSealed) CurrentSchema.AllowAdditionalProperties = false; } else if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum && !type.IsDefined(typeof(FlagsAttribute), true)) { CurrentSchema.Enum = new List<JToken>(); CurrentSchema.Options = new Dictionary<JToken, string>(); EnumValues<long> enumValues = EnumUtils.GetNamesAndValues<long>(type); foreach (EnumValue<long> enumValue in enumValues) { JToken value = JToken.FromObject(enumValue.Value); CurrentSchema.Enum.Add(value); CurrentSchema.Options.Add(value, enumValue.Name); } } } return Pop().Schema; }
private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired) { JsonSchemaType schemaType = JsonSchemaType.None; if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type)) { schemaType = JsonSchemaType.Null; if (ReflectionUtils.IsNullableType(type)) type = Nullable.GetUnderlyingType(type); } PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(type); switch (typeCode) { case PrimitiveTypeCode.Empty: case PrimitiveTypeCode.Object: return schemaType | JsonSchemaType.String; #if !(NETFX_CORE || PORTABLE) case PrimitiveTypeCode.DBNull: return schemaType | JsonSchemaType.Null; #endif case PrimitiveTypeCode.Boolean: return schemaType | JsonSchemaType.Boolean; case PrimitiveTypeCode.Char: return schemaType | JsonSchemaType.String; case PrimitiveTypeCode.SByte: case PrimitiveTypeCode.Byte: case PrimitiveTypeCode.Int16: case PrimitiveTypeCode.UInt16: case PrimitiveTypeCode.Int32: case PrimitiveTypeCode.UInt32: case PrimitiveTypeCode.Int64: case PrimitiveTypeCode.UInt64: #if !(PORTABLE || NET35 || NET20) case PrimitiveTypeCode.BigInteger: #endif return schemaType | JsonSchemaType.Integer; case PrimitiveTypeCode.Single: case PrimitiveTypeCode.Double: case PrimitiveTypeCode.Decimal: return schemaType | JsonSchemaType.Float; // convert to string? case PrimitiveTypeCode.DateTime: #if !NET20 case PrimitiveTypeCode.DateTimeOffset: #endif return schemaType | JsonSchemaType.String; case PrimitiveTypeCode.String: case PrimitiveTypeCode.Uri: case PrimitiveTypeCode.Guid: case PrimitiveTypeCode.TimeSpan: case PrimitiveTypeCode.Bytes: return schemaType | JsonSchemaType.String; default: throw new JsonException("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type)); } }
public void Insert(Required required) { DbContext.Requireds.Add(required); Update(); }
private JSchema GenerateInternal(Type type, Required? valueRequired, JsonProperty memberProperty, JsonContainerContract container) { ValidationUtils.ArgumentNotNull(type, "type"); Type nonNullableType = ReflectionUtils.IsNullableType(type) ? Nullable.GetUnderlyingType(type) : type; Uri explicitId = GetTypeId(nonNullableType, true); JsonContract contract = _generator.ContractResolver.ResolveContract(type); Required resolvedRequired = valueRequired ?? _generator.DefaultRequired; TypeSchemaKey key = CreateKey(resolvedRequired, memberProperty, contract); if (ShouldReferenceType(contract)) { TypeSchema typeSchema = _typeSchemas.SingleOrDefault(s => s.Key.Equals(key)); if (typeSchema != null) { return typeSchema.Schema; } } JSchema schema = null; JSchemaGenerationProvider provider = ResolveTypeProvider(nonNullableType, memberProperty); if (provider != null) { JSchemaTypeGenerationContext context = new JSchemaTypeGenerationContext(type, resolvedRequired, memberProperty, container, _generator); schema = provider.GetSchema(context); if (schema == null) { throw new JSchemaException("Could not get schema for type '{0}' from provider '{1}'.".FormatWith(CultureInfo.InvariantCulture, type.FullName, provider.GetType().FullName)); } } if (_generator._generationProviders != null) { JSchemaTypeGenerationContext context = new JSchemaTypeGenerationContext(type, resolvedRequired, memberProperty, container, _generator); foreach (JSchemaGenerationProvider generationProvider in _generator._generationProviders) { schema = generationProvider.GetSchema(context); } } if (schema != null) { if (ShouldReferenceType(contract)) { _typeSchemas.Add(new TypeSchema(key, schema)); } } else { schema = new JSchema(); if (explicitId != null) { schema.Id = explicitId; } if (ShouldReferenceType(contract)) { _typeSchemas.Add(new TypeSchema(key, schema)); } PopulateSchema(schema, contract, memberProperty, resolvedRequired); } return schema; }
private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired) { JsonSchemaType schemaType = JsonSchemaType.None; if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type)) { schemaType = JsonSchemaType.Null; if (ReflectionUtils.IsNullableType(type)) type = Nullable.GetUnderlyingType(type); } TypeCode typeCode = Type.GetTypeCode(type); switch (typeCode) { case TypeCode.Empty: case TypeCode.Object: return schemaType | JsonSchemaType.String; case TypeCode.DBNull: return schemaType | JsonSchemaType.Null; case TypeCode.Boolean: return schemaType | JsonSchemaType.Boolean; case TypeCode.Char: return schemaType | JsonSchemaType.String; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: return schemaType | JsonSchemaType.Integer; case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return schemaType | JsonSchemaType.Float; // convert to string? case TypeCode.DateTime: return schemaType | JsonSchemaType.String; case TypeCode.String: return schemaType | JsonSchemaType.String; default: throw new Exception("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type)); } }
// Token: 0x06000B87 RID: 2951 // RVA: 0x00042BE0 File Offset: 0x00040DE0 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 (Enumerable.Any<JsonSchemaGenerator.TypeSchema>(this._stack, (JsonSchemaGenerator.TypeSchema 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.", 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) { 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_4C4; 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 flag = 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, (!flag) ? Required.Always : Required.Default, false)); goto IL_4C4; } goto IL_4C4; } case JsonContractType.Primitive: { this.CurrentSchema.Type = new JsonSchemaType?(this.GetJsonSchemaType(type, valueRequired)); if (!(this.CurrentSchema.Type == JsonSchemaType.Integer) || !TypeExtensions.IsEnum(type) || type.IsDefined(typeof(FlagsAttribute), true)) { goto IL_4C4; } this.CurrentSchema.Enum = new List<JToken>(); IList<EnumValue<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_4C4; } 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_4C4; } JsonContract jsonContract2 = this.ContractResolver.ResolveContract(type2); if (jsonContract2.ContractType == JsonContractType.Primitive) { this.CurrentSchema.AdditionalProperties = this.GenerateInternal(type3, Required.Default, false); goto IL_4C4; } goto IL_4C4; } case JsonContractType.Dynamic: goto IL_455; 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_4C4; case JsonContractType.Linq: this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any); goto IL_4C4; default: goto IL_455; } JsonSchemaType value = (!ReflectionUtils.IsNullable(jsonContract.UnderlyingType)) ? JsonSchemaType.String : this.AddNullType(JsonSchemaType.String, valueRequired); this.CurrentSchema.Type = new JsonSchemaType?(value); goto IL_4C4; IL_455: throw new JsonException(StringUtils.FormatWith("Unexpected contract type: {0}", CultureInfo.InvariantCulture, jsonContract)); } this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any); IL_4C4: return this.Pop().Schema; }
// Token: 0x06000B8D RID: 2957 // RVA: 0x00043280 File Offset: 0x00041480 private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired) { JsonSchemaType jsonSchemaType = JsonSchemaType.None; if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type)) { jsonSchemaType = JsonSchemaType.Null; if (ReflectionUtils.IsNullableType(type)) { type = Nullable.GetUnderlyingType(type); } } PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(type); switch (typeCode) { case PrimitiveTypeCode.Empty: case PrimitiveTypeCode.Object: return jsonSchemaType | JsonSchemaType.String; case PrimitiveTypeCode.Char: return jsonSchemaType | JsonSchemaType.String; case PrimitiveTypeCode.Boolean: return jsonSchemaType | JsonSchemaType.Boolean; case PrimitiveTypeCode.SByte: case PrimitiveTypeCode.Int16: case PrimitiveTypeCode.UInt16: case PrimitiveTypeCode.Int32: case PrimitiveTypeCode.Byte: case PrimitiveTypeCode.UInt32: case PrimitiveTypeCode.Int64: case PrimitiveTypeCode.UInt64: return jsonSchemaType | JsonSchemaType.Integer; case PrimitiveTypeCode.Single: case PrimitiveTypeCode.Double: case PrimitiveTypeCode.Decimal: return jsonSchemaType | JsonSchemaType.Float; case PrimitiveTypeCode.DateTime: return jsonSchemaType | JsonSchemaType.String; case PrimitiveTypeCode.Guid: case PrimitiveTypeCode.TimeSpan: case PrimitiveTypeCode.Uri: case PrimitiveTypeCode.String: case PrimitiveTypeCode.Bytes: return jsonSchemaType | JsonSchemaType.String; case PrimitiveTypeCode.DBNull: return jsonSchemaType | JsonSchemaType.Null; } throw new JsonException(StringUtils.FormatWith("Unexpected type code '{0}' for type '{1}'.", CultureInfo.InvariantCulture, typeCode, type)); }
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required) { ValidationUtils.ArgumentNotNull(type, "type"); string resolvedId = GetTypeId(type, false); string explicitId = GetTypeId(type, true); if (!string.IsNullOrEmpty(resolvedId)) { JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId); if (resolvedSchema != null) { // resolved schema is not null but referencing member allows nulls // change resolved schema to allow nulls. hacky but what are ya gonna do? if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null)) resolvedSchema.Type |= JsonSchemaType.Null; if (required && resolvedSchema.Required != true) resolvedSchema.Required = true; return resolvedSchema; } } // test for unresolved circular reference if (_stack.Any(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, type)); } JsonContract contract = ContractResolver.ResolveContract(type); JsonConverter converter; if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null) { JsonSchema converterSchema = converter.GetSchema(); if (converterSchema != null) return converterSchema; } Push(new TypeSchema(type, new JsonSchema())); if (explicitId != null) CurrentSchema.Id = explicitId; if (required) CurrentSchema.Required = true; CurrentSchema.Title = GetTitle(type); CurrentSchema.Description = GetDescription(type); if (converter != null) { // todo: Add GetSchema to JsonConverter and use here? CurrentSchema.Type = JsonSchemaType.Any; } else { switch (contract.ContractType) { case JsonContractType.Object: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, false); GenerateObjectSchema(type, (JsonObjectContract) contract); break; case JsonContractType.Array: CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired); CurrentSchema.Id = GetTypeId(type, false); JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute; bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems); Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); if (collectionItemType != null) { CurrentSchema.Items = new List<JsonSchema>(); CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false)); } break; case JsonContractType.Primitive: CurrentSchema.Type = GetJsonSchemaType(type, valueRequired); if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum && !type.IsDefined(typeof (FlagsAttribute), true)) { CurrentSchema.Enum = new List<JToken>(); CurrentSchema.Options = new Dictionary<JToken, string>(); EnumValues<long> enumValues = EnumUtils.GetNamesAndValues<long>(type); foreach (EnumValue<long> enumValue in enumValues) { JToken value = JToken.FromObject(enumValue.Value); CurrentSchema.Enum.Add(value); CurrentSchema.Options.Add(value, enumValue.Name); } } break; case JsonContractType.String: JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType)) ? JsonSchemaType.String : AddNullType(JsonSchemaType.String, valueRequired); CurrentSchema.Type = schemaType; break; case JsonContractType.Dictionary: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); Type keyType; Type valueType; ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType); if (keyType != null) { // can be converted to a string if (typeof (IConvertible).IsAssignableFrom(keyType)) { CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false); } } break; #if !SILVERLIGHT && !PocketPC case JsonContractType.Serializable: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, false); GenerateISerializableContract(type, (JsonISerializableContract) contract); break; #endif #if !(NET35 || NET20 || WINDOWS_PHONE || MONOTOUCH || MONODROID) case JsonContractType.Dynamic: #endif case JsonContractType.Linq: CurrentSchema.Type = JsonSchemaType.Any; break; default: throw new Exception("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract)); } } return Pop().Schema; }
private static TypeSchemaKey CreateKey(Required valueRequired, JsonProperty memberProperty, JsonContract contract) { int? minLength = DataAnnotationHelpers.GetMinLength(memberProperty); int? maxLength = DataAnnotationHelpers.GetMaxLength(memberProperty); TypeSchemaKey key = new TypeSchemaKey(contract.UnderlyingType, valueRequired, minLength, maxLength); return key; }
private JSchema GenerateInternal(Type type, Required valueRequired, JsonProperty memberProperty, JsonContainerContract container) { ValidationUtils.ArgumentNotNull(type, "type"); Type nonNullableType = ReflectionUtils.IsNullableType(type) ? Nullable.GetUnderlyingType(type) : type; Uri explicitId = GetTypeId(nonNullableType, true); JsonContract contract = ContractResolver.ResolveContract(type); var key = CreateKey(valueRequired, memberProperty, contract); switch (contract.ContractType) { case JsonContractType.Object: case JsonContractType.Array: case JsonContractType.Dictionary: TypeSchema typeSchema = _typeSchemas.SingleOrDefault(s => s.Key.Equals(key)); if (typeSchema != null) return typeSchema.Schema; break; } JSchema schema = null; JSchemaGenerationProvider provider = ResolveTypeProvider(nonNullableType, memberProperty); if (provider != null) { JSchemaTypeGenerationContext context = new JSchemaTypeGenerationContext(type, valueRequired, memberProperty, container, this); schema = provider.GetSchema(context); if (schema == null) throw new JSchemaException("Could not get schema for type '{0}' from provider '{1}'.".FormatWith(CultureInfo.InvariantCulture, type.FullName, provider.GetType().FullName)); } if (_generationProviders != null) { JSchemaTypeGenerationContext context = new JSchemaTypeGenerationContext(type, valueRequired, memberProperty, container, this); foreach (JSchemaGenerationProvider generationProvider in _generationProviders) { schema = generationProvider.GetSchema(context); } } if (schema != null) { _typeSchemas.Add(new TypeSchema(key, schema)); return schema; } schema = new JSchema(); if (explicitId != null) schema.Id = explicitId; switch (contract.ContractType) { case JsonContractType.Object: case JsonContractType.Array: case JsonContractType.Dictionary: _typeSchemas.Add(new TypeSchema(key, schema)); break; } return PopulateSchema(schema, contract, memberProperty, valueRequired); }
private JSchemaType AddNullType(JSchemaType type, Required valueRequired) { if (valueRequired != Required.Always) return type | JSchemaType.Null; return type; }
private JSchema PopulateSchema(JSchema schema, JsonContract contract, JsonProperty memberProperty, Required valueRequired) { schema.Title = GetTitle(contract.NonNullableUnderlyingType); schema.Description = GetDescription(contract.NonNullableUnderlyingType); JsonConverter converter = contract.Converter ?? contract.InternalConverter; if (converter != null) { schema.Type = null; } else { switch (contract.ContractType) { case JsonContractType.Object: if (schema.Id == null) schema.Id = GetTypeId(contract.NonNullableUnderlyingType, false); schema.Type = AddNullType(JSchemaType.Object, valueRequired); GenerateObjectSchema(schema, contract.NonNullableUnderlyingType, (JsonObjectContract)contract); break; case JsonContractType.Array: if (schema.Id == null) schema.Id = GetTypeId(contract.NonNullableUnderlyingType, false); schema.Type = AddNullType(JSchemaType.Array, valueRequired); schema.MinimumItems = DataAnnotationHelpers.GetMinLength(memberProperty); schema.MaximumItems = DataAnnotationHelpers.GetMaxLength(memberProperty); JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetCachedAttribute<JsonArrayAttribute>(contract.NonNullableUnderlyingType); bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems); Type collectionItemType = ReflectionUtils.GetCollectionItemType(contract.NonNullableUnderlyingType); if (collectionItemType != null) { schema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, null, (JsonArrayContract)contract)); } break; case JsonContractType.Primitive: schema.Type = GetJSchemaType(contract.UnderlyingType, valueRequired); if (JSchemaTypeHelpers.HasFlag(schema.Type, JSchemaType.String)) { int minimumLength; int maximumLength; if (DataAnnotationHelpers.GetStringLength(memberProperty, out minimumLength, out maximumLength)) { schema.MinimumLength = minimumLength; schema.MaximumLength = maximumLength; } else { schema.MinimumLength = DataAnnotationHelpers.GetMinLength(memberProperty); schema.MaximumLength = DataAnnotationHelpers.GetMaxLength(memberProperty); } schema.Pattern = DataAnnotationHelpers.GetPattern(memberProperty); schema.Format = DataAnnotationHelpers.GetFormat(memberProperty); } if (JSchemaTypeHelpers.HasFlag(schema.Type, JSchemaType.Number) || JSchemaTypeHelpers.HasFlag(schema.Type, JSchemaType.Integer)) { double minimum; double maximum; if (DataAnnotationHelpers.GetRange(memberProperty, out minimum, out maximum)) { schema.Minimum = minimum; schema.Maximum = maximum; } } if (JSchemaTypeHelpers.HasFlag(schema.Type, JSchemaType.Integer) && contract.NonNullableUnderlyingType.IsEnum() && ReflectionUtils.GetAttribute<FlagsAttribute>(contract.NonNullableUnderlyingType) == null) { IList<EnumValue<long>> enumValues = EnumUtils.GetNamesAndValues<long>(contract.NonNullableUnderlyingType); foreach (EnumValue<long> enumValue in enumValues) { JToken value = JToken.FromObject(enumValue.Value); schema.Enum.Add(value); } } Type enumDataType = DataAnnotationHelpers.GetEnumDataType(memberProperty); if (enumDataType != null && CollectionUtils.IsNullOrEmpty(schema._enum)) { IList<EnumValue<long>> enumValues = EnumUtils.GetNamesAndValues<long>(enumDataType); foreach (EnumValue<long> enumValue in enumValues) { JToken value = (JSchemaTypeHelpers.HasFlag(schema.Type, JSchemaType.String)) ? enumValue.Name : JToken.FromObject(enumValue.Value); schema.Enum.Add(value); } } break; case JsonContractType.String: JSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType)) ? JSchemaType.String : AddNullType(JSchemaType.String, valueRequired); schema.Type = schemaType; schema.MinimumLength = DataAnnotationHelpers.GetMinLength(memberProperty); schema.MaximumLength = DataAnnotationHelpers.GetMaxLength(memberProperty); break; case JsonContractType.Dictionary: schema.Type = AddNullType(JSchemaType.Object, valueRequired); schema.MinimumProperties = DataAnnotationHelpers.GetMinLength(memberProperty); schema.MaximumProperties = DataAnnotationHelpers.GetMaxLength(memberProperty); Type keyType; Type valueType; ReflectionUtils.GetDictionaryKeyValueTypes(contract.NonNullableUnderlyingType, out keyType, out valueType); if (keyType != null) { JsonContract keyContract = ContractResolver.ResolveContract(keyType); // can be converted to a string if (keyContract.ContractType == JsonContractType.Primitive) { schema.AdditionalProperties = GenerateInternal(valueType, Required.Default, null, (JsonDictionaryContract)contract); } } break; case JsonContractType.Serializable: if (schema.Id == null) schema.Id = GetTypeId(contract.NonNullableUnderlyingType, false); schema.Type = AddNullType(JSchemaType.Object, valueRequired); schema.AllowAdditionalProperties = true; break; case JsonContractType.Dynamic: case JsonContractType.Linq: schema.Type = null; break; default: throw new JSchemaException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract)); } } return schema; }
private JSchemaType AddNullType(JSchemaType type, Required valueRequired) { if (valueRequired == Required.Default || valueRequired == Required.AllowNull) { return type | JSchemaType.Null; } return type; }
private JSchemaType GetJSchemaType(Type type, Required valueRequired) { JSchemaType schemaType = JSchemaType.None; if (ReflectionUtils.IsNullable(type)) { if (valueRequired != Required.Always) schemaType = JSchemaType.Null; if (ReflectionUtils.IsNullableType(type)) type = Nullable.GetUnderlyingType(type); } PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(type); switch (typeCode) { case PrimitiveTypeCode.Empty: case PrimitiveTypeCode.Object: return schemaType | JSchemaType.String; case PrimitiveTypeCode.DBNull: return schemaType | JSchemaType.Null; case PrimitiveTypeCode.Boolean: return schemaType | JSchemaType.Boolean; case PrimitiveTypeCode.Char: return schemaType | JSchemaType.String; case PrimitiveTypeCode.SByte: case PrimitiveTypeCode.Byte: case PrimitiveTypeCode.Int16: case PrimitiveTypeCode.UInt16: case PrimitiveTypeCode.Int32: case PrimitiveTypeCode.UInt32: case PrimitiveTypeCode.Int64: case PrimitiveTypeCode.UInt64: case PrimitiveTypeCode.BigInteger: return schemaType | JSchemaType.Integer; case PrimitiveTypeCode.Single: case PrimitiveTypeCode.Double: case PrimitiveTypeCode.Decimal: return schemaType | JSchemaType.Number; case PrimitiveTypeCode.DateTime: case PrimitiveTypeCode.DateTimeOffset: return schemaType | JSchemaType.String; case PrimitiveTypeCode.String: case PrimitiveTypeCode.Uri: case PrimitiveTypeCode.Guid: case PrimitiveTypeCode.TimeSpan: case PrimitiveTypeCode.Bytes: return schemaType | JSchemaType.String; default: throw new JSchemaException("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type)); } }
private JsonSchemaType AddNullType(JsonSchemaType type, Required valueRequired) { if (valueRequired != Required.Always) { return type | JsonSchemaType.Null; } return type; }
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; }
public ConsoleHelpAttribute(string helpText,Required requiredType = Required.NotReuired) { HelpText = helpText; RequiredType = requiredType; }