protected bool ValidateScope(IExtendedScopeProvider scope, out IScopeProvider parentScope) { parentScope = null; if (ChildScope.IsNull()) return false; if (scope.IsNull()) return false; return ChildScope.ScopeId == scope.ScopeId; }
public virtual bool TryEndScope(IExtendedScopeProvider scope, out IScopeProvider parentScope) { if (!ValidateScope(scope, out parentScope)) return false; ChildScope.Dispose(); parentScope = this; InvalidateBinding(typeof(IExtendedScopeProvider)); return true; }
private static string SerializeDictionaryType(this DictionaryType dictionary, IScopeProvider scope, string objectReference, string valueReference, bool isRequired, Dictionary<Constraint, string> constraints, string modelReference = "client._models", bool serializeInnerTypes = false) { if (scope == null) { throw new ArgumentNullException("scope"); } var builder = new IndentedStringBuilder(" "); var escapedObjectReference = objectReference.EscapeSingleQuotes(); var valueVar = scope.GetVariableName("valueElement"); var innerConstraints = new Dictionary<Constraint, string>(); var innerSerialization = dictionary.ValueType.SerializeType(scope, objectReference + "[" + valueVar + "]", valueReference + "[" + valueVar + "]", false, innerConstraints, modelReference, true); if (!string.IsNullOrEmpty(innerSerialization)) { if (isRequired) { builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0} !== 'object') {{", objectReference) .Indent() .AppendLine("throw new Error('{0} cannot be null or undefined and it must be of type {1}.');", escapedObjectReference, dictionary.Name.ToLower(CultureInfo.InvariantCulture)) .Outdent() .AppendLine("}"); builder = dictionary.AppendConstraintValidations(objectReference, constraints, builder); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); builder.AppendLine("{0} = {{}};", valueReference) .AppendLine("for(var {0} in {1}) {{", valueVar, objectReference) .Indent() .AppendLine(innerSerialization) .Outdent() .AppendLine("}"); return builder.ToString(); } builder.AppendLine("if ({0} && typeof {0} === 'object') {{", objectReference).Indent(); builder = dictionary.AppendConstraintValidations(objectReference, constraints, builder); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); builder.AppendLine("{0} = {{}};", valueReference) .AppendLine("for(var {0} in {1}) {{", valueVar, objectReference) .Indent() .AppendLine(innerSerialization) .AppendLine("else {") .Indent() .AppendLine("{0} = {1};", valueReference + "[" + valueVar + "]", objectReference + "[" + valueVar + "]") .Outdent() .AppendLine("}") .Outdent() .AppendLine("}") .Outdent() .AppendLine("}"); return builder.ToString(); } return null; }
/// <summary> /// Generate code to perform deserialization on a parameter or property /// </summary> /// <param name="type">The type to deserialize</param> /// <param name="scope">A scope provider for generating variable names as necessary</param> /// <param name="objectReference">A reference to the object that will be assigned the deserialized value</param> /// <param name="valueReference">A reference to the value being deserialized</param> /// <param name="modelReference">A reference to the models</param> /// <returns>The code to deserialize the given type</returns> public static string DeserializeType(this IType type, IScopeProvider scope, string objectReference, string valueReference, string modelReference = "self._models") { if (scope == null) { throw new ArgumentNullException("scope"); } EnumType enumType = type as EnumType; CompositeType composite = type as CompositeType; SequenceType sequence = type as SequenceType; DictionaryType dictionary = type as DictionaryType; PrimaryType primary = type as PrimaryType; var builder = new IndentedStringBuilder(" "); string baseProperty = valueReference.GetBasePropertyFromUnflattenedProperty(); if (baseProperty != null) { builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", baseProperty).Indent(); } if (enumType != null) { builder = ProcessBasicType(objectReference, valueReference, builder); } else if (primary != null) { if (primary == PrimaryType.ByteArray) { builder.AppendLine("if ({0}) {{", valueReference) .Indent() .AppendLine("{1} = new Buffer({0}, 'base64');", valueReference, objectReference) .Outdent().AppendLine("}") .AppendLine("else if ({0} !== undefined) {{", valueReference) .Indent() .AppendLine("{1} = {0};", valueReference, objectReference) .Outdent() .AppendLine("}"); } else if (primary == PrimaryType.DateTime || primary == PrimaryType.Date || primary == PrimaryType.DateTimeRfc1123) { builder.AppendLine("if ({0}) {{", valueReference) .Indent() .AppendLine("{1} = new Date({0});", valueReference, objectReference) .Outdent() .AppendLine("}") .AppendLine("else if ({0} !== undefined) {{", valueReference) .Indent() .AppendLine("{1} = {0};", valueReference, objectReference) .Outdent() .AppendLine("}"); } else if (primary == PrimaryType.TimeSpan) { builder.AppendLine("if ({0}) {{", valueReference) .Indent() .AppendLine("{1} = moment.duration({0});", valueReference, objectReference) .Outdent() .AppendLine("}") .AppendLine("else if ({0} !== undefined) {{", valueReference) .Indent() .AppendLine("{1} = {0};", valueReference, objectReference) .Outdent() .AppendLine("}"); } else { builder.AppendLine("if ({0} !== undefined) {{", valueReference) .Indent() .AppendLine("{1} = {0};", valueReference, objectReference) .Outdent() .AppendLine("}"); } } else if (composite != null && composite.Properties.Any()) { builder = composite.ProcessCompositeType(objectReference, valueReference, modelReference, builder, "DeserializeType"); } else if (sequence != null) { builder = sequence.ProcessSequenceType(scope, objectReference, valueReference, modelReference, builder, "DeserializeType"); } else if (dictionary != null) { builder = dictionary.ProcessDictionaryType(scope, objectReference, valueReference, modelReference, builder, "DeserializeType"); } if (baseProperty != null) { builder.Outdent().AppendLine("}"); } return builder.ToString(); }
public RedirectsService() { _scopeProvider = Current.ScopeProvider; _domains = Current.Services.DomainService; _logger = Current.Logger; }
public override bool TryEndScope(IExtendedScopeProvider scope, out IScopeProvider parentScope) { parentScope = this; return true; }
private UserGroupRepository CreateRepository(IScopeProvider provider) =>
/// <summary> /// Generate code to perform validation on a parameter or property /// </summary> /// <param name="type">The type to validate</param> /// <param name="scope">A scope provider for generating variable names as necessary</param> /// <param name="valueReference">A reference to the value being validated</param> /// <param name="isRequired">True if the parameter is required.</param> /// <param name="modelReference">A reference to the models array</param> /// <returns>The code to validate the reference of the given type</returns> public static string ValidateType(this IType type, IScopeProvider scope, string valueReference, bool isRequired, string modelReference = "client.models") { if (scope == null) { throw new ArgumentNullException("scope"); } CompositeType composite = type as CompositeType; SequenceType sequence = type as SequenceType; DictionaryType dictionary = type as DictionaryType; PrimaryType primary = type as PrimaryType; EnumType enumType = type as EnumType; if (primary != null) { return primary.ValidatePrimaryType(scope, valueReference, isRequired); } else if (enumType != null && enumType.Values.Any()) { return enumType.ValidateEnumType(scope, valueReference, isRequired); } else if (composite != null && composite.Properties.Any()) { return ValidateCompositeType(scope, valueReference, isRequired); } else if (sequence != null) { return sequence.ValidateSequenceType(scope, valueReference, isRequired, modelReference); } else if (dictionary != null) { return dictionary.ValidateDictionaryType(scope, valueReference, isRequired, modelReference); } return null; }
public TStatisticRepository(IScopeProvider scopeProvider) { _scopeProvider = scopeProvider; }
private static string SerializeCompositeType(this CompositeType composite, IScopeProvider scope, string objectReference, string valueReference, bool isRequired, Dictionary<Constraint, string> constraints, string modelReference = "client._models", bool serializeInnerTypes = false) { if (scope == null) { throw new ArgumentNullException("scope"); } var builder = new IndentedStringBuilder(" "); var escapedObjectReference = objectReference.EscapeSingleQuotes(); builder.AppendLine("if ({0}) {{", objectReference).Indent(); builder = composite.AppendConstraintValidations(objectReference, constraints, builder); if (!string.IsNullOrEmpty(composite.PolymorphicDiscriminator)) { builder.AppendLine("if({0}['{1}'] !== null && {0}['{1}'] !== undefined && {2}.discriminators[{0}['{1}']]) {{", objectReference, composite.PolymorphicDiscriminator, modelReference) .Indent(); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); builder.AppendLine("{0} = {1}.serialize();", valueReference, objectReference) .Outdent() .AppendLine("}} else {{", valueReference) .Indent() .AppendLine("throw new Error('No discriminator field \"{0}\" was found in parameter \"{1}\".');", composite.PolymorphicDiscriminator, escapedObjectReference) .Outdent() .AppendLine("}"); } else { if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); builder.AppendLine("{0} = {1}.serialize();", valueReference, objectReference); } builder.Outdent().AppendLine("}"); if (isRequired) { builder.Append(" else {") .Indent() .AppendLine("throw new Error('{0} cannot be null or undefined.');", escapedObjectReference) .Outdent() .AppendLine("}"); } return builder.ToString(); }
public MemberGroupService(IScopeProvider provider, ILoggerFactory loggerFactory, IEventMessagesFactory eventMessagesFactory, IMemberGroupRepository memberGroupRepository) : base(provider, loggerFactory, eventMessagesFactory) =>
private static string ValidatePrimaryType(this PrimaryType primary, IScopeProvider scope, string valueReference, bool isRequired) { if (scope == null) { throw new ArgumentNullException("scope"); } if (primary == null) { throw new ArgumentNullException("primary"); } var builder = new IndentedStringBuilder(" "); var requiredTypeErrorMessage = "throw new Error('{0} cannot be null or undefined and it must be of type {1}.');"; var typeErrorMessage = "throw new Error('{0} must be of type {1}.');"; var lowercaseTypeName = primary.Name.ToLower(CultureInfo.InvariantCulture); if (primary.Type == KnownPrimaryType.Boolean || primary.Type == KnownPrimaryType.Double || primary.Type == KnownPrimaryType.Decimal || primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long || primary.Type == KnownPrimaryType.Object) { if (isRequired) { builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0} !== '{1}') {{", valueReference, lowercaseTypeName); return(ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString()); } builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0} !== '{1}') {{", valueReference, lowercaseTypeName); return(ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString()); } else if (primary.Type == KnownPrimaryType.Stream) { if (isRequired) { builder.AppendLine("if ({0} === null || {0} === undefined) {{", valueReference, lowercaseTypeName); return(ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString()); } builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0}.valueOf() !== '{1}') {{", valueReference, lowercaseTypeName); return(ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString()); } else if (primary.Type == KnownPrimaryType.String) { if (isRequired) { //empty string can be a valid value hence we cannot implement the simple check if (!{0}) builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0}.valueOf() !== '{1}') {{", valueReference, lowercaseTypeName); return(ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString()); } builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0}.valueOf() !== '{1}') {{", valueReference, lowercaseTypeName); return(ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString()); } else if (primary.Type == KnownPrimaryType.Uuid) { if (isRequired) { requiredTypeErrorMessage = "throw new Error('{0} cannot be null or undefined and it must be of type string and must be a valid {1}.');"; //empty string can be a valid value hence we cannot implement the simple check if (!{0}) builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0}.valueOf() !== 'string' || !msRest.isValidUuid({0})) {{", valueReference); return(ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString()); } typeErrorMessage = "throw new Error('{0} must be of type string and must be a valid {1}.');"; builder.AppendLine("if ({0} !== null && {0} !== undefined && !(typeof {0}.valueOf() === 'string' && msRest.isValidUuid({0}))) {{", valueReference); return(ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString()); } else if (primary.Type == KnownPrimaryType.ByteArray) { if (isRequired) { builder.AppendLine("if (!Buffer.isBuffer({0})) {{", valueReference, lowercaseTypeName); return(ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString()); } builder.AppendLine("if ({0} && !Buffer.isBuffer({0})) {{", valueReference, lowercaseTypeName); return(ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString()); } else if (primary.Type == KnownPrimaryType.DateTime || primary.Type == KnownPrimaryType.Date || primary.Type == KnownPrimaryType.DateTimeRfc1123) { if (isRequired) { builder.AppendLine("if(!{0} || !({0} instanceof Date || ", valueReference) .Indent() .Indent() .AppendLine("(typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{", valueReference); return(ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString()); } builder = builder.AppendLine("if ({0} && !({0} instanceof Date || ", valueReference) .Indent() .Indent() .AppendLine("(typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{", valueReference); return(ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString()); } else if (primary.Type == KnownPrimaryType.TimeSpan) { if (isRequired) { builder.AppendLine("if(!{0} || !moment.isDuration({0})) {{", valueReference); return(ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString()); } builder.AppendLine("if({0} && !moment.isDuration({0})) {{", valueReference); return(ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString()); } else { throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "'{0}' not implemented", valueReference)); } }
public TaskListAppFactory(IScopeProvider scopeProvider) { this.scopeProvider = scopeProvider; }
public void Get_All() { IContent[] content = CreateTestData(30).ToArray(); IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger <PublicAccessRepository>()); var allEntries = new List <PublicAccessEntry>(); for (int i = 0; i < 10; i++) { var rules = new List <PublicAccessRule>(); for (int j = 0; j < 50; j++) { rules.Add(new PublicAccessRule { RuleValue = "test" + j, RuleType = "RoleName" + j }); } var entry1 = new PublicAccessEntry(content[i], content[i + 1], content[i + 2], rules); repo.Save(entry1); allEntries.Add(entry1); } // now remove a few rules from a few of the items and then add some more, this will put things 'out of order' which // we need to verify our sort order is working for the relator // FIXME: no "relator" in v8?! for (int i = 0; i < allEntries.Count; i++) { // all the even ones if (i % 2 == 0) { PublicAccessRule[] rules = allEntries[i].Rules.ToArray(); for (int j = 0; j < rules.Length; j++) { // all the even ones if (j % 2 == 0) { allEntries[i].RemoveRule(rules[j]); } } allEntries[i].AddRule("newrule" + i, "newrule" + i); repo.Save(allEntries[i]); } } PublicAccessEntry[] found = repo.GetMany().ToArray(); Assert.AreEqual(10, found.Length); foreach (PublicAccessEntry publicAccessEntry in found) { PublicAccessEntry matched = allEntries.First(x => x.Key == publicAccessEntry.Key); Assert.AreEqual(matched.Rules.Count(), publicAccessEntry.Rules.Count()); } } }
public ContentProtectorTreeController(IScopeProvider scopeProvider) { _scopeProvider = scopeProvider; }
private static IndentedStringBuilder ProcessSequenceType(this SequenceType sequence, IScopeProvider scope, string objectReference, string valueReference, string modelReference, IndentedStringBuilder builder, string processType) { var elementVar = scope.GetVariableName("element"); string innerInitialization = null; if (processType == null) { throw new ArgumentNullException("processType"); } if (processType == "InitializeType") { innerInitialization = sequence.ElementType.InitializeType(scope, elementVar, elementVar, modelReference); } else if (processType == "DeserializeType") { innerInitialization = sequence.ElementType.DeserializeType(scope, elementVar, elementVar, modelReference); } else if (processType == "InitializeSerializationType") { innerInitialization = sequence.ElementType.InitializeSerializationType(scope, elementVar, elementVar, modelReference); } if (!string.IsNullOrEmpty(innerInitialization)) { var arrayName = valueReference.ToPascalCase().NormalizeValueReference(); builder.AppendLine("if ({0}) {{", valueReference) .Indent() .AppendLine("var temp{0} = [];", arrayName) .AppendLine("{0}.forEach(function({1}) {{", valueReference, elementVar) .Indent() .AppendLine(innerInitialization) .AppendLine("temp{0}.push({1});", arrayName, elementVar) .Outdent() .AppendLine("});") .AppendLine("{0} = temp{1};", objectReference, arrayName) .Outdent() .AppendLine("}"); } return builder; }
/// <summary> /// Generates Ruby code in form of string for deserializing object of given type. /// </summary> /// <param name="type">Type of object needs to be deserialized.</param> /// <param name="scope">Current scope.</param> /// <param name="valueReference">Reference to object which needs to be deserialized.</param> /// <param name="namespacesToLookForClasses">List of namespaces where classes for polymorphic serialization can be found.</param> /// <returns>Generated Ruby code in form of string.</returns> public static string DeserializeType( this IType type, IScopeProvider scope, string valueReference, List<string> namespacesToLookForClasses) { var composite = type as CompositeType; var sequence = type as SequenceType; var dictionary = type as DictionaryType; var primary = type as PrimaryType; var enumType = type as EnumType; var builder = new IndentedStringBuilder(" "); if (primary != null) { if (primary == PrimaryType.Int || primary == PrimaryType.Long) { return builder.AppendLine("{0} = Integer({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary == PrimaryType.Double) { return builder.AppendLine("{0} = Float({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary == PrimaryType.ByteArray) { return builder.AppendLine("{0} = Base64.strict_decode64({0}).unpack('C*') unless {0}.to_s.empty?", valueReference).ToString(); } if (primary == PrimaryType.Date) { return builder.AppendLine("{0} = MsRest::Serialization.deserialize_date({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary == PrimaryType.DateTime) { return builder.AppendLine("{0} = DateTime.parse({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary == PrimaryType.DateTimeRfc1123) { return builder.AppendLine("{0} = DateTime.parse({0}) unless {0}.to_s.empty?", valueReference).ToString(); } } else if (enumType != null && !string.IsNullOrEmpty(enumType.Name)) { return builder .AppendLine("if (!{0}.nil? && !{0}.empty?)", valueReference) .AppendLine( " enum_is_valid = {0}.constants.any? {{ |e| {0}.const_get(e).to_s.downcase == {1}.downcase }}", enumType.Name, valueReference) .AppendLine( " fail MsRest::DeserializationError.new('Error occured while deserializing the enum', nil, nil, nil) unless enum_is_valid") .AppendLine("end") .ToString(); } else if (sequence != null) { var elementVar = scope.GetVariableName("element"); var innerSerialization = sequence.ElementType.DeserializeType(scope, elementVar, namespacesToLookForClasses); if (!string.IsNullOrEmpty(innerSerialization)) { return builder .AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("deserialized{0} = [];", sequence.Name) .AppendLine("{0}.each do |{1}|", valueReference, elementVar) .Indent() .AppendLine(innerSerialization) .AppendLine("deserialized{0}.push({1});", sequence.Name.ToPascalCase(), elementVar) .Outdent() .AppendLine("end") .AppendLine("{0} = deserialized{1};", valueReference, sequence.Name.ToPascalCase()) .Outdent() .AppendLine("end") .ToString(); } } else if (dictionary != null) { var valueVar = scope.GetVariableName("valueElement"); var innerSerialization = dictionary.ValueType.DeserializeType(scope, valueVar, namespacesToLookForClasses); if (!string.IsNullOrEmpty(innerSerialization)) { return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0}.each do |key, {1}|", valueReference, valueVar) .Indent() .AppendLine(innerSerialization) .AppendLine("{0}[key] = {1}", valueReference, valueVar) .Outdent() .AppendLine("end") .Outdent() .AppendLine("end").ToString(); } } else if (composite != null) { if (!string.IsNullOrEmpty(composite.PolymorphicDiscriminator)) { builder .AppendLine("unless {0}['dtype'].nil?", valueReference) .Indent() .AppendLine("class_name = {0}['dtype'].capitalize", valueReference) .AppendLine("class_instance = Models.const_get(class_name)"); foreach (var ns in namespacesToLookForClasses) { builder .AppendLine("class_instance = {0}.const_get(class_name) if class_instance.nil?", ns); } builder .AppendLine("{0} = class_instance.deserialize_object({0})", valueReference) .Outdent() .AppendLine("else") .Indent() .AppendLine("{0} = {1}.deserialize_object({0})", valueReference, composite.Name) .Outdent() .AppendLine("end"); return builder.ToString(); } return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0} = {1}.deserialize_object({0})", valueReference, composite.Name) .Outdent() .AppendLine("end").ToString(); } return string.Empty; }
private static string SerializePrimaryType(this PrimaryType primary, IScopeProvider scope, string objectReference, string valueReference, bool isRequired, Dictionary<Constraint, string> constraints, bool serializeInnerTypes = false) { if (scope == null) { throw new ArgumentNullException("scope"); } var builder = new IndentedStringBuilder(" "); var requiredTypeErrorMessage = "throw new Error('{0} cannot be null or undefined and it must be of type {1}.');"; var typeErrorMessage = "throw new Error('{0} must be of type {1}.');"; var lowercaseTypeName = primary.Name.ToLower(CultureInfo.InvariantCulture); if (primary == PrimaryType.Boolean || primary == PrimaryType.Double || primary == PrimaryType.Decimal || primary == PrimaryType.Int || primary == PrimaryType.Long || primary == PrimaryType.Object) { if (isRequired) { builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0} !== '{1}') {{", objectReference, lowercaseTypeName); builder = ConstructValidationCheck(builder, requiredTypeErrorMessage, objectReference, primary.Name); builder = primary.AppendConstraintValidations(objectReference, constraints, builder); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); return builder.AppendLine("{0} = {1};", valueReference, objectReference).ToString(); } builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", objectReference) .Indent() .AppendLine("if (typeof {0} !== '{1}') {{", objectReference, lowercaseTypeName); builder = ConstructValidationCheck(builder, typeErrorMessage, objectReference, primary.Name); builder = primary.AppendConstraintValidations(objectReference, constraints, builder); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); return builder.AppendLine("{0} = {1};", valueReference, objectReference) .Outdent() .AppendLine("}").ToString(); } else if (primary == PrimaryType.Stream) { if (isRequired) { builder.AppendLine("if ({0} === null || {0} === undefined) {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString(); } builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0}.valueOf() !== '{1}') {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } else if (primary == PrimaryType.String) { if (isRequired) { //empty string can be a valid value hence we cannot implement the simple check if (!{0}) builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0}.valueOf() !== '{1}') {{", objectReference, lowercaseTypeName); builder = ConstructValidationCheck(builder, requiredTypeErrorMessage, objectReference, primary.Name); builder = primary.AppendConstraintValidations(objectReference, constraints, builder); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); return builder.AppendLine("{0} = {1};", valueReference, objectReference).ToString(); } builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", objectReference) .Indent() .AppendLine("if (typeof {0}.valueOf() !== '{1}') {{", objectReference, lowercaseTypeName); builder = ConstructValidationCheck(builder, typeErrorMessage, objectReference, primary.Name); builder = primary.AppendConstraintValidations(objectReference, constraints, builder); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); return builder.AppendLine("{0} = {1};", valueReference, objectReference) .Outdent() .AppendLine("}").ToString(); } else if (primary == PrimaryType.ByteArray) { if (isRequired) { builder.AppendLine("if (!Buffer.isBuffer({0})) {{", objectReference); builder = ConstructValidationCheck(builder, requiredTypeErrorMessage, objectReference, primary.Name); builder = primary.AppendConstraintValidations(objectReference, constraints, builder); builder = ConstructBasePropertyCheck(builder, valueReference); return builder.AppendLine("{0} = {1}.toString('base64');", valueReference, objectReference).ToString(); } builder.AppendLine("if ({0}) {{", objectReference) .Indent() .AppendLine("if (!Buffer.isBuffer({0})) {{", objectReference); builder = ConstructValidationCheck(builder, typeErrorMessage, objectReference, primary.Name); builder = primary.AppendConstraintValidations(objectReference, constraints, builder); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); return builder.AppendLine("{0} = {1}.toString('base64');", valueReference, objectReference) .Outdent() .AppendLine("}").ToString(); } else if (primary == PrimaryType.Date) { if (isRequired) { builder.AppendLine("if(!{0} || !({0} instanceof Date || (typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{", objectReference); builder = ConstructValidationCheck(builder, requiredTypeErrorMessage, objectReference, primary.Name); builder = primary.AppendConstraintValidations(objectReference, constraints, builder); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); return builder.AppendLine("{0} = ({1} instanceof Date) ? {1}.toISOString().substring(0,10) : {1};", valueReference, objectReference).ToString(); } builder.AppendLine("if ({0}) {{", objectReference) .Indent() .AppendLine("if (!({0} instanceof Date || typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0})))) {{", objectReference); builder = ConstructValidationCheck(builder, typeErrorMessage, objectReference, primary.Name); builder = primary.AppendConstraintValidations(objectReference, constraints, builder); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); return builder.AppendLine("{0} = ({1} instanceof Date) ? {1}.toISOString().substring(0,10) : {1};", valueReference, objectReference) .Outdent() .AppendLine("}").ToString(); } else if (primary == PrimaryType.DateTime) { if (isRequired) { builder.AppendLine("if(!{0} || !({0} instanceof Date || (typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{", objectReference); builder = ConstructValidationCheck(builder, requiredTypeErrorMessage, objectReference, primary.Name); builder = primary.AppendConstraintValidations(objectReference, constraints, builder); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); return builder.AppendLine("{0} = ({1} instanceof Date) ? {1}.toISOString() : {1};", valueReference, objectReference).ToString(); } builder.AppendLine("if ({0}) {{", objectReference) .Indent() .AppendLine("if (!({0} instanceof Date || typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0})))) {{", objectReference); builder = ConstructValidationCheck(builder, typeErrorMessage, objectReference, primary.Name); builder = primary.AppendConstraintValidations(objectReference, constraints, builder); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); return builder.AppendLine("{0} = ({1} instanceof Date) ? {1}.toISOString() : {1};", valueReference, objectReference) .Outdent() .AppendLine("}").ToString(); } else if (primary == PrimaryType.DateTimeRfc1123) { if (isRequired) { builder.AppendLine("if(!{0} || !({0} instanceof Date || (typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{", objectReference); builder = ConstructValidationCheck(builder, requiredTypeErrorMessage, objectReference, primary.Name); builder = primary.AppendConstraintValidations(objectReference, constraints, builder); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); return builder.AppendLine("{0} = ({1} instanceof Date) ? {1}.toUTCString() : {1};", valueReference, objectReference).ToString(); } builder.AppendLine("if ({0}) {{", objectReference) .Indent() .AppendLine("if (!({0} instanceof Date || typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0})))) {{", objectReference); builder = ConstructValidationCheck(builder, typeErrorMessage, objectReference, primary.Name); builder = primary.AppendConstraintValidations(objectReference, constraints, builder); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); return builder.AppendLine("{0} = ({1} instanceof Date) ? {1}.toUTCString() : {1};", valueReference, objectReference) .Outdent() .AppendLine("}").ToString(); } else if (primary == PrimaryType.TimeSpan) { if (isRequired) { builder.AppendLine("if(!{0} || !moment.isDuration({0})) {{", objectReference); builder = ConstructValidationCheck(builder, requiredTypeErrorMessage, objectReference, primary.Name); builder = primary.AppendConstraintValidations(objectReference, constraints, builder); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); return builder.AppendLine("{0} = {1}.toISOString();", valueReference, objectReference).ToString(); } builder.AppendLine("if ({0}) {{", objectReference) .Indent() .AppendLine("if (!moment.isDuration({0})) {{", objectReference); builder = ConstructValidationCheck(builder, typeErrorMessage, objectReference, primary.Name); builder = primary.AppendConstraintValidations(objectReference, constraints, builder); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); return builder.AppendLine("{0} = {1}.toISOString();", valueReference, objectReference) .Outdent() .AppendLine("}").ToString(); } else { throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "'{0}' not implemented", valueReference)); } }
private static string ValidateEnumType(this EnumType enumType, IScopeProvider scope, string valueReference, bool isRequired) { if (scope == null) { throw new ArgumentNullException("scope"); } var builder = new IndentedStringBuilder(" "); var allowedValues = scope.GetUniqueName("allowedValues"); builder.AppendLine("if ({0}) {{", valueReference) .Indent() .AppendLine("var {0} = {1};", allowedValues, enumType.GetEnumValuesArray()) .AppendLine("if (!{0}.some( function(item) {{ return item === {1}; }})) {{", allowedValues, valueReference) .Indent() .AppendLine("throw new Error({0} + ' is not a valid value. The valid values are: ' + {1});", valueReference, allowedValues) .Outdent() .AppendLine("}"); if (isRequired) { var escapedValueReference = valueReference.EscapeSingleQuotes(); builder.Outdent().AppendLine("} else {") .Indent() .AppendLine("throw new Error('{0} cannot be null or undefined.');", escapedValueReference) .Outdent() .AppendLine("}"); } else { builder.Outdent().AppendLine("}"); } return builder.ToString(); }
protected ScopeRepositoryService(IScopeProvider provider, ILogger logger, IEventMessagesFactory eventMessagesFactory) : base(provider, logger, eventMessagesFactory) { }
public RedirectsService(IScopeProvider scopeProvider, IDomainService domains, ILogger logger) { _scopeProvider = scopeProvider; _domains = domains; _logger = logger; }
public ResolveResult(IScopeProvider scopeProvider) { ScopeProvider = scopeProvider; }
public TFileSystemProviderRepository(IScopeProvider scopeProvider) { _scopeProvider = scopeProvider; }
private static string ValidateSequenceType(this SequenceType sequence, IScopeProvider scope, string valueReference, bool isRequired, string modelReference = "client.models") { if (scope == null) { throw new ArgumentNullException("scope"); } var builder = new IndentedStringBuilder(" "); var escapedValueReference = valueReference.EscapeSingleQuotes(); var indexVar = scope.GetUniqueName("i"); var innerValidation = sequence.ElementType.ValidateType(scope, valueReference + "[" + indexVar + "]", false, modelReference); if (!string.IsNullOrEmpty(innerValidation)) { if (isRequired) { return builder.AppendLine("if (!util.isArray({0})) {{", valueReference) .Indent() .AppendLine("throw new Error('{0} cannot be null or undefined and it must be of type {1}.');", escapedValueReference, sequence.Name.ToLower(CultureInfo.InvariantCulture)) .Outdent() .AppendLine("}") .AppendLine("for (var {1} = 0; {1} < {0}.length; {1}++) {{", valueReference, indexVar) .Indent() .AppendLine(innerValidation) .Outdent() .AppendLine("}").ToString(); } return builder.AppendLine("if (util.isArray({0})) {{", valueReference) .Indent() .AppendLine("for (var {1} = 0; {1} < {0}.length; {1}++) {{", valueReference, indexVar) .Indent() .AppendLine(innerValidation) .Outdent() .AppendLine("}") .Outdent() .AppendLine("}").ToString(); } return null; }
public DomainService(IScopeProvider provider, ILoggerFactory loggerFactory, IEventMessagesFactory eventMessagesFactory, IDomainRepository domainRepository) : base(provider, loggerFactory, eventMessagesFactory) { _domainRepository = domainRepository; }
/// <summary> /// Generate code to perform required validation on a type /// </summary> /// <param name="type">The type to validate</param> /// <param name="scope">A scope provider for generating variable names as necessary</param> /// <param name="valueReference">A reference to the value being validated</param> /// <param name="constraints">Constraints</param> /// <returns>The code to validate the reference of the given type</returns> public static string ValidateType(this IType type, IScopeProvider scope, string valueReference, Dictionary<Constraint, string> constraints) { if (scope == null) { throw new ArgumentNullException("scope"); } CompositeType model = type as CompositeType; SequenceType sequence = type as SequenceType; DictionaryType dictionary = type as DictionaryType; var sb = new IndentedStringBuilder(); if (model != null && model.ShouldValidateChain()) { sb.AppendLine("{0}.Validate();", valueReference); } if (constraints != null && constraints.Any()) { AppendConstraintValidations(valueReference, constraints, sb); } if (sequence != null && sequence.ShouldValidateChain()) { var elementVar = scope.GetUniqueName("element"); var innerValidation = sequence.ElementType.ValidateType(scope, elementVar, null); if (!string.IsNullOrEmpty(innerValidation)) { sb.AppendLine("foreach (var {0} in {1})", elementVar, valueReference) .AppendLine("{").Indent() .AppendLine(innerValidation).Outdent() .AppendLine("}"); } } else if (dictionary != null && dictionary.ShouldValidateChain()) { var valueVar = scope.GetUniqueName("valueElement"); var innerValidation = dictionary.ValueType.ValidateType(scope, valueVar, null); if (!string.IsNullOrEmpty(innerValidation)) { sb.AppendLine("foreach (var {0} in {1}.Values)", valueVar, valueReference) .AppendLine("{").Indent() .AppendLine(innerValidation).Outdent() .AppendLine("}").Outdent(); } } if (sb.ToString().Trim().Length > 0) { if (type.IsValueType()) { return sb.ToString(); } else { return CheckNull(valueReference, sb.ToString()); } } return null; }
public KeyValueService(IScopeProvider scopeProvider, ILogger logger) { _scopeProvider = scopeProvider; _logger = logger; }
/// <summary> /// Generate code to perform deserialization on a parameter or property /// </summary> /// <param name="type">The type to deserialize</param> /// <param name="scope">A scope provider for generating variable names as necessary</param> /// <param name="valueReference">A reference to the value being deserialized</param> /// <param name="modelReference">A reference to the models</param> /// <returns>The code to deserialize the given type</returns> public static string DeserializeType(this IType type, IScopeProvider scope, string valueReference, string modelReference = "self._models") { if (scope == null) { throw new ArgumentNullException("scope"); } CompositeType composite = type as CompositeType; SequenceType sequence = type as SequenceType; DictionaryType dictionary = type as DictionaryType; PrimaryType primary = type as PrimaryType; var builder = new IndentedStringBuilder(" "); if (primary != null) { if (primary == PrimaryType.ByteArray) { return builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0}.valueOf() === 'string') {{", valueReference) .Indent() .AppendLine("{0} = new Buffer({0}, 'base64');", valueReference) .Outdent() .AppendLine("}").ToString(); } else if (primary == PrimaryType.DateTime || primary == PrimaryType.Date) { return builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", valueReference) .Indent() .AppendLine("{0} = new Date({0});", valueReference) .Outdent() .AppendLine("}").ToString(); } } else if (composite != null && composite.Properties.Any()) { builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", valueReference).Indent(); if (!string.IsNullOrEmpty(composite.PolymorphicDiscriminator)) { builder.AppendLine("if({0}['{1}'] !== null && {0}['{1}'] !== undefined && {2}.discriminators[{0}['{1}']]) {{", valueReference, composite.PolymorphicDiscriminator, modelReference) .Indent() .AppendLine("{0} = {2}.discriminators[{0}['{1}']].deserialize({0});", valueReference, composite.PolymorphicDiscriminator, modelReference) .Outdent() .AppendLine("}} else {{", valueReference) .Indent() .AppendLine("throw new Error('No discriminator field \"{0}\" was found in parameter \"{1}\".');", composite.PolymorphicDiscriminator, valueReference) .Outdent() .AppendLine("}"); } else { builder.AppendLine("{0} = {2}['{1}'].deserialize({0});", valueReference, composite.Name, modelReference); } builder.Outdent().AppendLine("}"); return builder.ToString(); } else if (sequence != null) { var elementVar = scope.GetVariableName("element"); var innerSerialization = sequence.ElementType.DeserializeType(scope, elementVar, modelReference); if (!string.IsNullOrEmpty(innerSerialization)) { return builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", valueReference) .Indent() .AppendLine("var deserialized{0} = [];", sequence.Name.ToPascalCase()) .AppendLine("{0}.forEach(function({1}) {{", valueReference, elementVar) .Indent() .AppendLine(innerSerialization) .AppendLine("deserialized{0}.push({1});", sequence.Name.ToPascalCase(), elementVar) .Outdent() .AppendLine("});") .AppendLine("{0} = deserialized{1};", valueReference, sequence.Name.ToPascalCase()) .Outdent() .AppendLine("}").ToString(); } } else if (dictionary != null) { var valueVar = scope.GetVariableName("valueElement"); var innerSerialization = dictionary.ValueType.DeserializeType(scope, valueReference + "[" + valueVar + "]", modelReference); if (!string.IsNullOrEmpty(innerSerialization)) { return builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", valueReference) .Indent() .AppendLine("for(var {0} in {1}) {{", valueVar, valueReference) .Indent() .AppendLine(innerSerialization) .Outdent() .AppendLine("}") .Outdent() .AppendLine("}").ToString(); } } return null; }
public BlogPostHighFiveService(IScopeProvider scopeProvider) { _scopeProvider = scopeProvider; }
public override bool TryEndScope(IExtendedScopeProvider scope, out IScopeProvider parentScope) { if (!ValidateScope(scope, out parentScope)) return false; ChildScope.Dispose(); parentScope = this; ChildScope = null; return true; }
public static SafeXmlReaderWriter Get(IScopeProvider scopeProvider) { return(scopeProvider?.Context?.GetEnlisted <SafeXmlReaderWriter>(EnlistKey)); }
/// <summary> /// Generate code to perform serialization on a parameter or property /// </summary> /// <param name="type">The type to validate</param> /// <param name="scope">A scope provider for generating variable names as necessary</param> /// <param name="objectReference">A reference to the object being serialized</param> /// <param name="valueReference">A reference to the value that will be assigned the serialized object</param> /// <param name="isRequired">True if the parameter or property is required.</param> /// <param name="constraints">Constraints specified on the type.</param> /// <param name="modelReference">A reference to the models</param> /// <param name="serializeInnerTypes">True if we serializing valueType/elementType of Dictionary/Sequence respectively</param> /// <returns>The code to serialize the given type</returns> public static string SerializeType(this IType type, IScopeProvider scope, string objectReference, string valueReference, bool isRequired, Dictionary<Constraint, string> constraints, string modelReference = "client._models", bool serializeInnerTypes = false) { if (scope == null) { throw new ArgumentNullException("scope"); } CompositeType composite = type as CompositeType; SequenceType sequence = type as SequenceType; DictionaryType dictionary = type as DictionaryType; PrimaryType primary = type as PrimaryType; EnumType enumType = type as EnumType; if (primary != null) { return primary.SerializePrimaryType(scope, objectReference, valueReference, isRequired, constraints, serializeInnerTypes); } else if (enumType != null && enumType.Values.Any()) { return enumType.SerializeEnumType(scope, objectReference, valueReference, isRequired, constraints, serializeInnerTypes); } else if (composite != null && composite.Properties.Any()) { return composite.SerializeCompositeType(scope, objectReference, valueReference, isRequired, constraints, modelReference, serializeInnerTypes); } else if (sequence != null) { return sequence.SerializeSequenceType(scope, objectReference, valueReference, isRequired, constraints, modelReference, serializeInnerTypes); } else if (dictionary != null) { return dictionary.SerializeDictionaryType(scope, objectReference, valueReference, isRequired, constraints, modelReference, serializeInnerTypes); } return null; }
public THistoryRepository(IScopeProvider scopeProvider) { this.scopeProvider = scopeProvider; }
public static string InitializeSerializationType(this IType type, IScopeProvider scope, string objectReference, string valueReference, string modelReference = "models") { if (scope == null) { throw new ArgumentNullException("scope"); } CompositeType composite = type as CompositeType; SequenceType sequence = type as SequenceType; DictionaryType dictionary = type as DictionaryType; var builder = new IndentedStringBuilder(" "); if (composite != null && composite.Properties.Any()) { builder = composite.ProcessCompositeType(objectReference, valueReference, modelReference, builder, "InitializeSerializationType"); } else if (sequence != null) { builder = sequence.ProcessSequenceType(scope, objectReference, valueReference, modelReference, builder, "InitializeSerializationType"); } else if (dictionary != null) { builder = dictionary.ProcessDictionaryType(scope, objectReference, valueReference, modelReference, builder, "InitializeSerializationType"); } return builder.ToString(); }
private ITemplateRepository CreateRepository(IScopeProvider provider) { return(new TemplateRepository((IScopeAccessor)provider, AppCaches.Disabled, Logger, _fileSystems)); }
private static IndentedStringBuilder ProcessDictionaryType(this DictionaryType dictionary, IScopeProvider scope, string objectReference, string valueReference, string modelReference, IndentedStringBuilder builder, string processType) { var valueVar = scope.GetVariableName("valueElement"); string innerInitialization = null; if (processType == null) { throw new ArgumentNullException("processType"); } string elementObjectReference = objectReference + "[" + valueVar + "]"; string elementValueReference = valueReference + "[" + valueVar + "]"; if (processType == "InitializeType") { innerInitialization = dictionary.ValueType.InitializeType(scope, elementObjectReference, elementValueReference, modelReference); } else if (processType == "DeserializeType") { innerInitialization = dictionary.ValueType.DeserializeType(scope, elementObjectReference, elementValueReference, modelReference); } else if (processType == "InitializeSerializationType") { innerInitialization = dictionary.ValueType.InitializeSerializationType(scope, elementObjectReference, elementValueReference, modelReference); } if (!string.IsNullOrEmpty(innerInitialization)) { builder.AppendLine("if ({0}) {{", valueReference).Indent(); if (processType == "DeserializeType" || processType == "InitializeType") { builder.AppendLine("{0} = {{}};", objectReference); } builder.AppendLine("for(var {0} in {1}) {{", valueVar, valueReference) .Indent() .AppendLine(innerInitialization) .Outdent() .AppendLine("}") .Outdent() .AppendLine("}"); } return builder; }
protected ContentTypeServiceBase(IScopeProvider provider, ILoggerFactory loggerFactory, IEventMessagesFactory eventMessagesFactory) : base(provider, loggerFactory, eventMessagesFactory) { }
private static string SerializeEnumType(this EnumType enumType, IScopeProvider scope, string objectReference, string valueReference, bool isRequired, Dictionary<Constraint, string> constraints, bool serializeInnerTypes = false) { if (scope == null) { throw new ArgumentNullException("scope"); } var builder = new IndentedStringBuilder(" "); var allowedValues = scope.GetVariableName("allowedValues"); string tempReference = objectReference; builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", objectReference).Indent(); builder = enumType.AppendConstraintValidations(objectReference, constraints, builder); builder.AppendLine("var {0} = {1};", allowedValues, enumType.GetEnumValuesArray()); if (objectReference.IndexOfAny(new char[] { '.', '[', ']'}) >= 0) { tempReference = tempReference.NormalizeValueReference(); builder.AppendLine("var {0} = {1};", tempReference, objectReference); } builder.AppendLine("if (!{0}.some( function(item) {{ return item === {1}; }})) {{", allowedValues, tempReference) .Indent() .AppendLine("throw new Error({0} + ' is not a valid value. The valid values are: ' + {1});", objectReference, allowedValues) .Outdent() .AppendLine("}"); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); builder.AppendLine("{0} = {1};", valueReference, objectReference); if (isRequired) { var escapedObjectReference = objectReference.EscapeSingleQuotes(); builder.Outdent().AppendLine("} else {") .Indent() .AppendLine("throw new Error('{0} cannot be null or undefined.');", escapedObjectReference) .Outdent() .AppendLine("}"); } else { builder.Outdent().AppendLine("}"); } return builder.ToString(); }
public WorkflowExecutor(IWorkflowRegistry registry, IServiceProvider serviceProvider, IScopeProvider scopeProvider, IDateTimeProvider datetimeProvider, IExecutionResultProcessor executionResultProcessor, ILifeCycleEventPublisher publisher, ICancellationProcessor cancellationProcessor, WorkflowOptions options, IWorkflowMiddlewareRunner middlewareRunner, IStepExecutor stepExecutor, ILoggerFactory loggerFactory) { _serviceProvider = serviceProvider; _scopeProvider = scopeProvider; _registry = registry; _datetimeProvider = datetimeProvider; _publisher = publisher; _cancellationProcessor = cancellationProcessor; _options = options; _logger = loggerFactory.CreateLogger <WorkflowExecutor>(); _executionResultProcessor = executionResultProcessor; _middlewareRunner = middlewareRunner; _stepExecutor = stepExecutor; }
private static string SerializeSequenceType(this SequenceType sequence, IScopeProvider scope, string objectReference, string valueReference, bool isRequired, Dictionary<Constraint, string> constraints, string modelReference = "client._models", bool serializeInnerTypes = false) { if (scope == null) { throw new ArgumentNullException("scope"); } var builder = new IndentedStringBuilder(" "); var escapedObjectReference = objectReference.EscapeSingleQuotes(); var indexVar = scope.GetVariableName("i"); var innerConstraints = new Dictionary<Constraint, string>(); var innerSerialization = sequence.ElementType.SerializeType(scope, objectReference + "[" + indexVar + "]", valueReference + "[" + indexVar + "]", false, innerConstraints, modelReference, true); if (!string.IsNullOrEmpty(innerSerialization)) { if (isRequired) { builder.AppendLine("if (!util.isArray({0})) {{", objectReference) .Indent() .AppendLine("throw new Error('{0} cannot be null or undefined and it must be of type {1}.');", escapedObjectReference, sequence.Name.ToLower(CultureInfo.InvariantCulture)) .Outdent() .AppendLine("}"); builder = sequence.AppendConstraintValidations(objectReference, constraints, builder); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); builder.AppendLine("{0} = [];", valueReference) .AppendLine("for (var {1} = 0; {1} < {0}.length; {1}++) {{", objectReference, indexVar) .Indent() .AppendLine(innerSerialization) .Outdent() .AppendLine("}"); return builder.ToString(); } builder.AppendLine("if (util.isArray({0})) {{", objectReference).Indent(); builder = sequence.AppendConstraintValidations(objectReference, constraints, builder); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); builder.AppendLine("{0} = [];", valueReference) .AppendLine("for (var {1} = 0; {1} < {0}.length; {1}++) {{", objectReference, indexVar) .Indent() .AppendLine(innerSerialization) .Outdent() .AppendLine("}") .Outdent() .AppendLine("}"); return builder.ToString(); } return null; }
public UmbracoTestDataController(IScopeProvider scopeProvider, PropertyEditorCollection propertyEditors, IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, ILogger logger, IProfilingLogger profilingLogger, UmbracoHelper umbracoHelper) : base(umbracoContextAccessor, databaseFactory, services, appCaches, logger, profilingLogger, umbracoHelper) { _scopeProvider = scopeProvider; _propertyEditors = propertyEditors; }
public LogScrubber(IBackgroundTaskRunner <RecurringTaskBase> runner, int delayMilliseconds, int periodMilliseconds, IRuntimeState runtime, IAuditService auditService, IUmbracoSettingsSection settings, IScopeProvider scopeProvider, IProfilingLogger logger) : base(runner, delayMilliseconds, periodMilliseconds) { _runtime = runtime; _auditService = auditService; _settings = settings; _scopeProvider = scopeProvider; _logger = logger; }
public ExternalLoginStore(IScopeProvider scopeProvider) { _scopeProvider = scopeProvider ?? throw new ArgumentNullException(nameof(scopeProvider)); }
/// <summary> /// Generates Ruby code in form of string for serializing object of given type. /// </summary> /// <param name="type">Type of object needs to be serialized.</param> /// <param name="scope">Current scope.</param> /// <param name="valueReference">Reference to object which needs to serialized.</param> /// <param name="namespacesToLookForClasses">List of namespaces where classes for polymorphic deserialization can be found.</param> /// <returns>Generated Ruby code in form of string.</returns> public static string SerializeType( this IType type, IScopeProvider scope, string valueReference, List<string> namespacesToLookForClasses) { var composite = type as CompositeType; var sequence = type as SequenceType; var dictionary = type as DictionaryType; var primary = type as PrimaryType; var builder = new IndentedStringBuilder(" "); if (primary != null) { if (primary == PrimaryType.ByteArray) { return builder.AppendLine("{0} = Base64.strict_encode64({0}.pack('c*'))", valueReference).ToString(); } if (primary == PrimaryType.DateTime) { return builder.AppendLine("{0} = {0}.new_offset(0).strftime('%FT%TZ')", valueReference).ToString(); } if (primary == PrimaryType.DateTimeRfc1123) { return builder.AppendLine("{0} = {0}.new_offset(0).strftime('%a, %d %b %Y %H:%M:%S GMT')", valueReference).ToString(); } } else if (sequence != null) { var elementVar = scope.GetVariableName("element"); var innerSerialization = sequence.ElementType.SerializeType(scope, elementVar, namespacesToLookForClasses); if (!string.IsNullOrEmpty(innerSerialization)) { return builder .AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("serialized{0} = []", sequence.Name) .AppendLine("{0}.each do |{1}|", valueReference, elementVar) .Indent() .AppendLine(innerSerialization) .AppendLine("serialized{0}.push({1})", sequence.Name.ToPascalCase(), elementVar) .Outdent() .AppendLine("end") .AppendLine("{0} = serialized{1}", valueReference, sequence.Name.ToPascalCase()) .Outdent() .AppendLine("end") .ToString(); } } else if (dictionary != null) { var valueVar = scope.GetVariableName("valueElement"); var innerSerialization = dictionary.ValueType.SerializeType(scope, valueVar, namespacesToLookForClasses); if (!string.IsNullOrEmpty(innerSerialization)) { return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0}.each {{ |key, {1}|", valueReference, valueVar) .Indent() .AppendLine(innerSerialization) .AppendLine("{0}[key] = {1}", valueReference, valueVar) .Outdent() .AppendLine("}") .Outdent() .AppendLine("end").ToString(); } } else if (composite != null) { if (!string.IsNullOrEmpty(composite.PolymorphicDiscriminator)) { builder .AppendLine("unless {0}.dtype.nil?", valueReference) .Indent() .AppendLine("class_name = {0}.dtype.capitalize", valueReference) .AppendLine("class_instance = Models.const_get(class_name)"); foreach (var ns in namespacesToLookForClasses) { builder .AppendLine("class_instance = {0}.const_get(class_name) if class_instance.nil?", ns); } builder .AppendLine("{0} = class_instance.serialize_object({0})", valueReference) .Outdent() .AppendLine("else") .Indent() .AppendLine("{0} = {1}.serialize_object({0})", valueReference, composite.Name) .Outdent() .AppendLine("end"); return builder.ToString(); } return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0} = {1}.serialize_object({0})", valueReference, composite.Name) .Outdent() .AppendLine("end").ToString(); } return string.Empty; }
/// <summary> /// Generates Ruby code in form of string for serializing object of given type. /// </summary> /// <param name="type">Type of object needs to be serialized.</param> /// <param name="scope">Current scope.</param> /// <param name="valueReference">Reference to object which needs to serialized.</param> /// <returns>Generated Ruby code in form of string.</returns> public static string AzureSerializeType( this IType type, IScopeProvider scope, string valueReference) { var composite = type as CompositeType; var sequence = type as SequenceType; var dictionary = type as DictionaryType; var primary = type as PrimaryType; var builder = new IndentedStringBuilder(" "); if (primary != null) { if (primary.Type == KnownPrimaryType.ByteArray) { return(builder.AppendLine("{0} = Base64.strict_encode64({0}.pack('c*'))", valueReference).ToString()); } if (primary.Type == KnownPrimaryType.DateTime) { return(builder.AppendLine("{0} = {0}.new_offset(0).strftime('%FT%TZ')", valueReference).ToString()); } if (primary.Type == KnownPrimaryType.DateTimeRfc1123) { return(builder.AppendLine("{0} = {0}.new_offset(0).strftime('%a, %d %b %Y %H:%M:%S GMT')", valueReference).ToString()); } } else if (sequence != null) { var elementVar = scope.GetUniqueName("element"); var innerSerialization = sequence.ElementType.AzureSerializeType(scope, elementVar); if (!string.IsNullOrEmpty(innerSerialization)) { return (builder .AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("serialized{0} = []", sequence.Name) .AppendLine("{0}.each do |{1}|", valueReference, elementVar) .Indent() .AppendLine(innerSerialization) .AppendLine("serialized{0}.push({1})", sequence.Name.ToPascalCase(), elementVar) .Outdent() .AppendLine("end") .AppendLine("{0} = serialized{1}", valueReference, sequence.Name.ToPascalCase()) .Outdent() .AppendLine("end") .ToString()); } } else if (dictionary != null) { var valueVar = scope.GetUniqueName("valueElement"); var innerSerialization = dictionary.ValueType.AzureSerializeType(scope, valueVar); if (!string.IsNullOrEmpty(innerSerialization)) { return(builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0}.each {{ |key, {1}|", valueReference, valueVar) .Indent() .AppendLine(innerSerialization) .AppendLine("{0}[key] = {1}", valueReference, valueVar) .Outdent() .AppendLine("}") .Outdent() .AppendLine("end").ToString()); } } else if (composite != null) { var compositeName = composite.Name; if (compositeName == "Resource" || compositeName == "SubResource") { compositeName = string.Format(CultureInfo.InvariantCulture, "{0}::{1}", "MsRestAzure", compositeName); } return(builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0} = {1}.serialize_object({0})", valueReference, compositeName) .Outdent() .AppendLine("end").ToString()); } return(string.Empty); }
private static string ValidatePrimaryType(this PrimaryType primary, IScopeProvider scope, string valueReference, bool isRequired) { if (scope == null) { throw new ArgumentNullException("scope"); } if (primary == null) { throw new ArgumentNullException("primary"); } var builder = new IndentedStringBuilder(" "); var requiredTypeErrorMessage = "throw new Error('{0} cannot be null or undefined and it must be of type {1}.');"; var typeErrorMessage = "throw new Error('{0} must be of type {1}.');"; var lowercaseTypeName = primary.Name.ToLower(CultureInfo.InvariantCulture); if (primary.Type == KnownPrimaryType.Boolean || primary.Type == KnownPrimaryType.Double || primary.Type == KnownPrimaryType.Decimal || primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long || primary.Type == KnownPrimaryType.Object) { if (isRequired) { builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0} !== '{1}') {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString(); } builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0} !== '{1}') {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } else if (primary.Type == KnownPrimaryType.Stream) { if (isRequired) { builder.AppendLine("if ({0} === null || {0} === undefined) {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString(); } builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0}.valueOf() !== '{1}') {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } else if (primary.Type == KnownPrimaryType.String) { if (isRequired) { //empty string can be a valid value hence we cannot implement the simple check if (!{0}) builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0}.valueOf() !== '{1}') {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString(); } builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0}.valueOf() !== '{1}') {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } else if (primary.Type == KnownPrimaryType.Uuid) { if (isRequired) { requiredTypeErrorMessage = "throw new Error('{0} cannot be null or undefined and it must be of type string and must be a valid {1}.');"; //empty string can be a valid value hence we cannot implement the simple check if (!{0}) builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0}.valueOf() !== 'string' || !msRest.isValidUuid({0})) {{", valueReference); return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString(); } typeErrorMessage = "throw new Error('{0} must be of type string and must be a valid {1}.');"; builder.AppendLine("if ({0} !== null && {0} !== undefined && !(typeof {0}.valueOf() === 'string' && msRest.isValidUuid({0}))) {{", valueReference); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } else if (primary.Type == KnownPrimaryType.ByteArray || primary.Type == KnownPrimaryType.Base64Url) { if (isRequired) { builder.AppendLine("if (!Buffer.isBuffer({0})) {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString(); } builder.AppendLine("if ({0} && !Buffer.isBuffer({0})) {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } else if (primary.Type == KnownPrimaryType.DateTime || primary.Type == KnownPrimaryType.Date || primary.Type == KnownPrimaryType.DateTimeRfc1123) { if (isRequired) { builder.AppendLine("if(!{0} || !({0} instanceof Date || ", valueReference) .Indent() .Indent() .AppendLine("(typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{", valueReference); return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString(); } builder = builder.AppendLine("if ({0} && !({0} instanceof Date || ", valueReference) .Indent() .Indent() .AppendLine("(typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{", valueReference); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } else if (primary.Type == KnownPrimaryType.TimeSpan) { if (isRequired) { builder.AppendLine("if(!{0} || !moment.isDuration({0})) {{", valueReference); return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString(); } builder.AppendLine("if({0} && !moment.isDuration({0})) {{", valueReference); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } else { throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "'{0}' not implemented", valueReference)); } }
/// <summary> /// Generates Ruby code in form of string for deserializing object of given type. /// </summary> /// <param name="type">Type of object needs to be deserialized.</param> /// <param name="scope">Current scope.</param> /// <param name="valueReference">Reference to object which needs to be deserialized.</param> /// <returns>Generated Ruby code in form of string.</returns> public static string AzureDeserializeType( this IType type, IScopeProvider scope, string valueReference) { var composite = type as CompositeType; var sequence = type as SequenceType; var dictionary = type as DictionaryType; var primary = type as PrimaryType; var enumType = type as EnumType; var builder = new IndentedStringBuilder(" "); if (primary != null) { if (primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long) { return(builder.AppendLine("{0} = Integer({0}) unless {0}.to_s.empty?", valueReference).ToString()); } if (primary.Type == KnownPrimaryType.Double) { return(builder.AppendLine("{0} = Float({0}) unless {0}.to_s.empty?", valueReference).ToString()); } if (primary.Type == KnownPrimaryType.ByteArray) { return(builder.AppendLine("{0} = Base64.strict_decode64({0}).unpack('C*') unless {0}.to_s.empty?", valueReference).ToString()); } if (primary.Type == KnownPrimaryType.Date) { return(builder.AppendLine("{0} = MsRest::Serialization.deserialize_date({0}) unless {0}.to_s.empty?", valueReference).ToString()); } if (primary.Type == KnownPrimaryType.DateTime) { return(builder.AppendLine("{0} = DateTime.parse({0}) unless {0}.to_s.empty?", valueReference).ToString()); } if (primary.Type == KnownPrimaryType.DateTimeRfc1123) { return(builder.AppendLine("{0} = DateTime.parse({0}) unless {0}.to_s.empty?", valueReference).ToString()); } } else if (enumType != null && !string.IsNullOrEmpty(enumType.Name)) { return(builder .AppendLine("if (!{0}.nil? && !{0}.empty?)", valueReference) .AppendLine( " enum_is_valid = {0}.constants.any? {{ |e| {0}.const_get(e).to_s.downcase == {1}.downcase }}", enumType.Name, valueReference) .AppendLine( " warn 'Enum {0} does not contain ' + {1}.downcase + ', but was received from the server.' unless enum_is_valid", enumType.Name, valueReference) .AppendLine("end") .ToString()); } else if (sequence != null) { var elementVar = scope.GetUniqueName("element"); var innerSerialization = sequence.ElementType.AzureDeserializeType(scope, elementVar); if (!string.IsNullOrEmpty(innerSerialization)) { return (builder .AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("deserialized_{0} = []", sequence.Name.ToLower()) .AppendLine("{0}.each do |{1}|", valueReference, elementVar) .Indent() .AppendLine(innerSerialization) .AppendLine("deserialized_{0}.push({1})", sequence.Name.ToLower(), elementVar) .Outdent() .AppendLine("end") .AppendLine("{0} = deserialized_{1}", valueReference, sequence.Name.ToLower()) .Outdent() .AppendLine("end") .ToString()); } } else if (dictionary != null) { var valueVar = scope.GetUniqueName("valueElement"); var innerSerialization = dictionary.ValueType.AzureDeserializeType(scope, valueVar); if (!string.IsNullOrEmpty(innerSerialization)) { return(builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0}.each do |key, {1}|", valueReference, valueVar) .Indent() .AppendLine(innerSerialization) .AppendLine("{0}[key] = {1}", valueReference, valueVar) .Outdent() .AppendLine("end") .Outdent() .AppendLine("end").ToString()); } } else if (composite != null) { var compositeName = composite.Name; if (compositeName == "Resource" || compositeName == "SubResource") { compositeName = string.Format(CultureInfo.InvariantCulture, "{0}::{1}", "MsRestAzure", compositeName); } return(builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0} = {1}.deserialize_object({0})", valueReference, compositeName) .Outdent() .AppendLine("end").ToString()); } return(string.Empty); }
private static string ValidateCompositeType(IScopeProvider scope, string valueReference, bool isRequired) { if (scope == null) { throw new ArgumentNullException("scope"); } var builder = new IndentedStringBuilder(" "); var escapedValueReference = valueReference.EscapeSingleQuotes(); //Only validate whether the composite type is present, if it is required. Detailed validation happens in serialization. if (isRequired) { builder.AppendLine("if ({0} === null || {0} === undefined) {{", valueReference) .Indent() .AppendLine("throw new Error('{0} cannot be null or undefined.');", escapedValueReference) .Outdent() .AppendLine("}"); } return builder.ToString(); }
/// <summary> /// Generates Ruby code in form of string for deserializing object of given type. /// </summary> /// <param name="type">Type of object needs to be deserialized.</param> /// <param name="scope">Current scope.</param> /// <param name="valueReference">Reference to object which needs to be deserialized.</param> /// <returns>Generated Ruby code in form of string.</returns> public static string AzureDeserializeType( this IType type, IScopeProvider scope, string valueReference) { var composite = type as CompositeType; var sequence = type as SequenceType; var dictionary = type as DictionaryType; var primary = type as PrimaryType; var enumType = type as EnumType; var builder = new IndentedStringBuilder(" "); if (primary != null) { if (primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long) { return builder.AppendLine("{0} = Integer({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.Type == KnownPrimaryType.Double) { return builder.AppendLine("{0} = Float({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.Type == KnownPrimaryType.ByteArray) { return builder.AppendLine("{0} = Base64.strict_decode64({0}).unpack('C*') unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.Type == KnownPrimaryType.Date) { return builder.AppendLine("{0} = MsRest::Serialization.deserialize_date({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.Type == KnownPrimaryType.DateTime) { return builder.AppendLine("{0} = DateTime.parse({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.Type == KnownPrimaryType.DateTimeRfc1123) { return builder.AppendLine("{0} = DateTime.parse({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.Type == KnownPrimaryType.UnixTime) { return builder.AppendLine("{0} = DateTime.strptime({0}.to_s, '%s') unless {0}.to_s.empty?", valueReference).ToString(); } } else if (enumType != null && !string.IsNullOrEmpty(enumType.Name)) { return builder .AppendLine("if (!{0}.nil? && !{0}.empty?)", valueReference) .AppendLine( " enum_is_valid = {0}.constants.any? {{ |e| {0}.const_get(e).to_s.downcase == {1}.downcase }}", enumType.Name, valueReference) .AppendLine( " warn 'Enum {0} does not contain ' + {1}.downcase + ', but was received from the server.' unless enum_is_valid", enumType.Name, valueReference) .AppendLine("end") .ToString(); } else if (sequence != null) { var elementVar = scope.GetUniqueName("element"); var innerSerialization = sequence.ElementType.AzureDeserializeType(scope, elementVar); if (!string.IsNullOrEmpty(innerSerialization)) { return builder .AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("deserialized_{0} = []", sequence.Name.ToLower()) .AppendLine("{0}.each do |{1}|", valueReference, elementVar) .Indent() .AppendLine(innerSerialization) .AppendLine("deserialized_{0}.push({1})", sequence.Name.ToLower(), elementVar) .Outdent() .AppendLine("end") .AppendLine("{0} = deserialized_{1}", valueReference, sequence.Name.ToLower()) .Outdent() .AppendLine("end") .ToString(); } } else if (dictionary != null) { var valueVar = scope.GetUniqueName("valueElement"); var innerSerialization = dictionary.ValueType.AzureDeserializeType(scope, valueVar); if (!string.IsNullOrEmpty(innerSerialization)) { return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0}.each do |key, {1}|", valueReference, valueVar) .Indent() .AppendLine(innerSerialization) .AppendLine("{0}[key] = {1}", valueReference, valueVar) .Outdent() .AppendLine("end") .Outdent() .AppendLine("end").ToString(); } } else if (composite != null) { var compositeName = composite.Name; if(compositeName == "Resource" || compositeName == "SubResource") { compositeName = string.Format(CultureInfo.InvariantCulture, "{0}::{1}", "MsRestAzure", compositeName); } return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0} = {1}.deserialize_object({0})", valueReference, compositeName) .Outdent() .AppendLine("end").ToString(); } return string.Empty; }
private static string ValidateDictionaryType(this DictionaryType dictionary, IScopeProvider scope, string valueReference, bool isRequired, string modelReference = "client.models") { if (scope == null) { throw new ArgumentNullException("scope"); } var builder = new IndentedStringBuilder(" "); var escapedValueReference = valueReference.EscapeSingleQuotes(); var valueVar = scope.GetUniqueName("valueElement"); var innerValidation = dictionary.ValueType.ValidateType(scope, valueReference + "[" + valueVar + "]", false, modelReference); if (!string.IsNullOrEmpty(innerValidation)) { if (isRequired) { return builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0} !== 'object') {{", valueReference) .Indent() .AppendLine("throw new Error('{0} cannot be null or undefined and it must be of type {1}.');", escapedValueReference, dictionary.Name.ToLower(CultureInfo.InvariantCulture)) .Outdent() .AppendLine("}") .AppendLine("for(var {0} in {1}) {{", valueVar, valueReference) .Indent() .AppendLine(innerValidation) .Outdent() .AppendLine("}").ToString(); } return builder.AppendLine("if ({0} && typeof {0} === 'object') {{", valueReference) .Indent() .AppendLine("for(var {0} in {1}) {{", valueVar, valueReference) .Indent() .AppendLine(innerValidation) .Outdent() .AppendLine("}") .Outdent() .AppendLine("}").ToString(); } return null; }
private static string ValidatePrimaryType(this PrimaryType primary, IScopeProvider scope, string valueReference, bool isRequired) { if (scope == null) { throw new ArgumentNullException("scope"); } var builder = new IndentedStringBuilder(" "); var conditionBuilder = new IndentedStringBuilder(" "); var requiredTypeErrorMessage = "throw new Error('{0} cannot be null or undefined and it must be of type {1}.');"; var typeErrorMessage = "throw new Error('{0} must be of type {1}.');"; if (primary == PrimaryType.Boolean || primary == PrimaryType.Double || primary == PrimaryType.Int || primary == PrimaryType.Long) { if (isRequired) { return ConstructValidationCheck("if ({0} === null || {0} === undefined || typeof {0} !== '{1}') {{", requiredTypeErrorMessage, valueReference, primary.Name); } return ConstructValidationCheck("if ({0} !== null && {0} !== undefined && typeof {0} !== '{1}') {{", typeErrorMessage, valueReference, primary.Name); } else if (primary == PrimaryType.String) { if (isRequired) { //empty string can be a valid value hence we cannot implement the simple check if (!{0}) return ConstructValidationCheck("if ({0} === null || {0} === undefined || typeof {0}.valueOf() !== '{1}') {{", requiredTypeErrorMessage, valueReference, primary.Name); } return ConstructValidationCheck("if ({0} !== null && {0} !== undefined && typeof {0}.valueOf() !== '{1}') {{", typeErrorMessage, valueReference, primary.Name); } else if (primary == PrimaryType.ByteArray) { if (isRequired) { return ConstructValidationCheck("if (!Buffer.isBuffer({0})) {{", requiredTypeErrorMessage, valueReference, primary.Name); } return ConstructValidationCheck("if ({0} && !Buffer.isBuffer({0})) {{", typeErrorMessage, valueReference, primary.Name); } else if (primary == PrimaryType.DateTime || primary == PrimaryType.Date) { string condition = ""; if (isRequired) { condition = conditionBuilder.AppendLine("if(!{0} || !({0} instanceof Date || ") .Indent() .Indent() .AppendLine("(typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{").ToString(); return ConstructValidationCheck(condition, requiredTypeErrorMessage, valueReference, primary.Name); } condition = conditionBuilder.AppendLine("if ({0} && !({0} instanceof Date || ") .Indent() .Indent() .AppendLine("(typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{").ToString(); return ConstructValidationCheck(condition, typeErrorMessage, valueReference, primary.Name); } else if (primary == PrimaryType.Object) { if (isRequired) { return ConstructValidationCheck("if ({0} !== null || {0} !== undefined || typeof {0} !== '{1}') {{", requiredTypeErrorMessage, valueReference, primary.Name); } return builder.ToString(); } else { throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "'{0}' not implemented", valueReference)); } }
/// <summary> /// Generate code to perform required validation on a type. /// </summary> /// <param name="type">The type to validate.</param> /// <param name="scope">A scope provider for generating variable names as necessary.</param> /// <param name="valueReference">A reference to the value being validated.</param> /// <returns>The code to validate the reference of the given type.</returns> public static string ValidateType(this IType type, IScopeProvider scope, string valueReference) { CompositeType model = type as CompositeType; SequenceType sequence = type as SequenceType; DictionaryType dictionary = type as DictionaryType; if (model != null && model.Properties.Any()) { return string.Format("{0}.validate unless {0}.nil?", valueReference); } if (sequence != null || dictionary != null) { return string.Format("{0}.each{{ |e| e.validate if e.respond_to?(:validate) }} unless {0}.nil?" + Environment.NewLine, valueReference); } return null; }
private static string ValidateCompositeType(this CompositeType composite, IScopeProvider scope, string valueReference, bool isRequired, string modelReference = "client._models") { if (scope == null) { throw new ArgumentNullException("scope"); } var builder = new IndentedStringBuilder(" "); var escapedValueReference = valueReference.EscapeSingleQuotes(); builder.AppendLine("if ({0}) {{", valueReference).Indent(); if (!string.IsNullOrEmpty(composite.PolymorphicDiscriminator)) { builder.AppendLine("if({0}['{1}'] !== null && {0}['{1}'] !== undefined && {2}.discriminators[{0}['{1}']]) {{", valueReference, composite.PolymorphicDiscriminator, modelReference) .Indent() .AppendLine("{2}.discriminators[{0}['{1}']].validate({0});", valueReference, composite.PolymorphicDiscriminator, modelReference) .Outdent() .AppendLine("}} else {{", valueReference) .Indent() .AppendLine("throw new Error('No discriminator field \"{0}\" was found in parameter \"{1}\".');", composite.PolymorphicDiscriminator, escapedValueReference) .Outdent() .AppendLine("}"); } else { builder.AppendLine("{2}['{0}'].validate({1});", composite.Name, valueReference, modelReference); } builder.Outdent().AppendLine("}"); if (isRequired) { builder.Append(" else {") .Indent() .AppendLine("throw new Error('{0} cannot be null or undefined.');", escapedValueReference) .Outdent() .AppendLine("}"); } return builder.ToString(); }
/// <summary> /// Generate code to perform required validation on a type /// </summary> /// <param name="type">The type to validate</param> /// <param name="scope">A scope provider for generating variable names as necessary</param> /// <param name="valueReference">A reference to the value being validated</param> /// <returns>The code to validate the reference of the given type</returns> public static string ValidateType(this IType type, IScopeProvider scope, string valueReference) { if (scope == null) { throw new ArgumentNullException("scope"); } CompositeType model = type as CompositeType; SequenceType sequence = type as SequenceType; DictionaryType dictionary = type as DictionaryType; if (model != null && model.ShouldValidateChain()) { return CheckNull(valueReference, string.Format(CultureInfo.InvariantCulture, "{0}.Validate();", valueReference)); } if (sequence != null && sequence.ShouldValidateChain()) { var elementVar = scope.GetVariableName("element"); var innerValidation = sequence.ElementType.ValidateType(scope, elementVar); if (!string.IsNullOrEmpty(innerValidation)) { var sb = new IndentedStringBuilder(); sb.AppendLine("foreach (var {0} in {1})", elementVar, valueReference) .AppendLine("{").Indent() .AppendLine(innerValidation).Outdent() .AppendLine("}"); return CheckNull(valueReference, sb.ToString()); } } else if (dictionary != null && dictionary.ShouldValidateChain()) { var valueVar = scope.GetVariableName("valueElement"); var innerValidation = dictionary.ValueType.ValidateType(scope, valueVar); if (!string.IsNullOrEmpty(innerValidation)) { var sb = new IndentedStringBuilder(); sb.AppendLine("if ({0} != null)", valueReference) .AppendLine("{").Indent() .AppendLine("foreach (var {0} in {1}.Values)",valueVar,valueReference) .AppendLine("{").Indent() .AppendLine(innerValidation).Outdent() .AppendLine("}").Outdent() .AppendLine("}"); return CheckNull(valueReference, sb.ToString()); } } return null; }
public KeyValueService(IScopeProvider scopeProvider, IKeyValueRepository repository) { _scopeProvider = scopeProvider; _repository = repository; }