public virtual void AddChild(IChild child)
		{
			if (child != null)
			{
				children.Add(child);
			}
		}
        public void SetUp()
        {
            _mocks = new MockRepository();

            _mockBase = _mocks.Stub<IBase>();
            _mockChild = _mocks.Stub<IChild>();

            _mocks.ReplayAll();
        }
        public StubDemoTestFixture()
        {
            _mocks = new MockRepository();

            _mockBase = _mocks.Stub<IBase>();
            _mockChild = _mocks.Stub<IChild>();

            _mocks.ReplayAll();
        }
		public override void RemoveChild(IChild child)
		{
			// Note: if the collection is a bag, the same child can be in the collection more than once
			base.RemoveChild(child);
			// only remove the parent from the child's set if child is no longer in the collection
			if (!Children.Contains(child))
			{
				((ChildWithBidirectionalManyToMany) child).RemoveParent(this);
			}
		}
		public override void RemoveChild(IChild child)
		{
			// Note: there can be more than one child in the collection
			base.RemoveChild(child);
			// only set the parent to null if child is no longer in the bag
			if (!Children.Contains(child))
			{
				((ChildWithManyToOne)child).Parent = null;

			}
		}
        protected void AddEntityDeleteStatement(IChild child, EntityInfo childInfo)
        {
            var builder = new ComplexCommandBuilder();

            var idParameter = child.Id.ToParameter();
            builder.AddParameter(idParameter);
            var whereClause = string.Format("{0}.{1} = {2}", childInfo.Name, childInfo.Identifier.Name, idParameter.Name);
            var statement = new DeleteStatement(childInfo.Name, whereClause);

            builder.AddStatement(statement);
            Add(builder);

            AddDeleteStatements(child, childInfo);
        }
Example #7
0
        public void MoveChildToDifferentParent()
        {
            CollectionListeners   listeners   = new CollectionListeners(Sfi);
            IParentWithCollection parent      = CreateParentWithOneChild("parent", "child");
            IParentWithCollection otherParent = CreateParentWithOneChild("otherParent", "otherChild");
            IChild child = GetFirstChild(parent.Children);

            listeners.Clear();
            ISession     s  = OpenSession();
            ITransaction tx = s.BeginTransaction();

            parent      = (IParentWithCollection)s.Get(parent.GetType(), parent.Id);
            otherParent = (IParentWithCollection)s.Get(otherParent.GetType(), otherParent.Id);
            IEntity e = child as IEntity;

            if (e != null)
            {
                child = (IChild)s.Get(child.GetType(), e.Id);
            }
            parent.RemoveChild(child);
            otherParent.AddChild(child);
            tx.Commit();
            s.Close();
            int index = 0;

            if (((IPersistentCollection)parent.Children).WasInitialized)
            {
                CheckResult(listeners, listeners.InitializeCollection, parent, index++);
            }
            ChildWithBidirectionalManyToMany childWithManyToMany = child as ChildWithBidirectionalManyToMany;

            if (childWithManyToMany != null)
            {
                CheckResult(listeners, listeners.InitializeCollection, childWithManyToMany, index++);
            }
            if (((IPersistentCollection)otherParent.Children).WasInitialized)
            {
                CheckResult(listeners, listeners.InitializeCollection, otherParent, index++);
            }
            CheckResult(listeners, listeners.PreCollectionUpdate, parent, index++);
            CheckResult(listeners, listeners.PostCollectionUpdate, parent, index++);
            CheckResult(listeners, listeners.PreCollectionUpdate, otherParent, index++);
            CheckResult(listeners, listeners.PostCollectionUpdate, otherParent, index++);
            if (childWithManyToMany != null)
            {
                CheckResult(listeners, listeners.PreCollectionUpdate, childWithManyToMany, index++);
                CheckResult(listeners, listeners.PostCollectionUpdate, childWithManyToMany, index++);
            }
            CheckNumberOfResults(listeners, index);
        }
Example #8
0
 public void DoDragDrop(IChild child)
 {
     /*VirtualFileDataObject virtualFileDataObject = new VirtualFileDataObject();
      * List<VirtualFileDataObject.FileDescriptor> files = new List<VirtualFileDataObject.FileDescriptor>();
      * this.PopulateFile(files, (FileEntry)child, ((IViewable)child).Name);
      * virtualFileDataObject.SetData(files);
      *
      * var effect = VirtualFileDataObject.DoDragDrop(this.Control, virtualFileDataObject, DragDropEffects.Copy);
      * if (effect == DragDropEffects.None)
      * {
      *  virtualFileDataObject = null;
      * }
      * Console.WriteLine("Finished Drag-Drop operation setup");*/
 }
Example #9
0
        public virtual void UpdateParentOneToTwoSameChildren()
        {
            CollectionListeners   listeners = new CollectionListeners(Sfi);
            IParentWithCollection parent    = CreateParentWithOneChild("parent", "child");
            IChild child = GetFirstChild(parent.Children);

            Assert.That(parent.Children.Count, Is.EqualTo(1));
            listeners.Clear();
            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    parent = (IParentWithCollection)s.Get(parent.GetType(), parent.Id);
                    IEntity e = child as IEntity;
                    if (e != null)
                    {
                        child = (IChild)s.Get(child.GetType(), e.Id);
                    }
                    parent.AddChild(child);
                    tx.Commit();
                }
            int index = 0;

            if (((IPersistentCollection)parent.Children).WasInitialized)
            {
                CheckResult(listeners, listeners.InitializeCollection, parent, index++);
            }
            ChildWithBidirectionalManyToMany childWithManyToMany = child as ChildWithBidirectionalManyToMany;

            if (childWithManyToMany != null)
            {
                if (((IPersistentCollection)childWithManyToMany.Parents).WasInitialized)
                {
                    CheckResult(listeners, listeners.InitializeCollection, childWithManyToMany, index++);
                }
            }

            if (!(parent.Children is PersistentGenericSet <IChild>))
            {
                CheckResult(listeners, listeners.PreCollectionUpdate, parent, index++);
                CheckResult(listeners, listeners.PostCollectionUpdate, parent, index++);
            }
            if (childWithManyToMany != null && !(childWithManyToMany.Parents is PersistentGenericSet <ParentWithBidirectionalManyToMany>))
            {
                CheckResult(listeners, listeners.PreCollectionUpdate, childWithManyToMany, index++);
                CheckResult(listeners, listeners.PostCollectionUpdate, childWithManyToMany, index++);
            }

            CheckNumberOfResults(listeners, index);
        }
        protected void AddEntityDeleteStatement(IChild child, EntityInfo childInfo)
        {
            var builder = new ComplexCommandBuilder();

            var idParameter = child.Id.ToParameter();

            builder.AddParameter(idParameter);
            var whereClause = string.Format("{0}.{1} = {2}", childInfo.Name, childInfo.Identifier.Name, idParameter.Name);
            var statement   = new DeleteStatement(childInfo.Name, whereClause);

            builder.AddStatement(statement);
            Add(builder);

            AddDeleteStatements(child, childInfo);
        }
Example #11
0
        public static string GetUniqueName(this IChild scope, string desiredName)
        {
            // current hack: get the methods params and add them to the local list.
            var names = new HashSet <string>((scope as Method)?.Parameters.Select(each => each.Name.Value) ?? Enumerable.Empty <string>());

            names.AddRange(scope.LocallyUsedNames);

            // get a unique name
            var result = CodeNamer.Instance.GetUnique(desiredName, scope, scope.Parent.IdentifiersInScope,
                                                      scope.Parent.Children, names);


            // tell the child that they own that name now.
            scope?.LocallyUsedNames?.Add(result);
            return(result);
        }
Example #12
0
        private IChild[] GetArrayItems(int size)
        {
            var stw = m_stopwatches["GetArrayItems"];

            stw.Start();

            var arr = new IChild[size];

            for (var i = 0; i < arr.Length; i++)
            {
                arr[i] = new ArrayItem(i);
            }

            stw.Stop();

            return(arr);
        }
Example #13
0
        public void UpdateParentOneChildToNoneByRemove()
        {
            CollectionListeners   listeners = new CollectionListeners(Sfi);
            IParentWithCollection parent    = CreateParentWithOneChild("parent", "child");

            Assert.That(parent.Children.Count, Is.EqualTo(1));
            IChild child = GetFirstChild(parent.Children);

            listeners.Clear();
            ISession     s  = OpenSession();
            ITransaction tx = s.BeginTransaction();

            parent = (IParentWithCollection)s.Get(parent.GetType(), parent.Id);
            IEntity e = child as IEntity;

            if (e != null)
            {
                child = (IChild)s.Get(child.GetType(), e.Id);
            }
            parent.RemoveChild(child);
            tx.Commit();
            s.Close();
            int index = 0;

            if (((IPersistentCollection)parent.Children).WasInitialized)
            {
                CheckResult(listeners, listeners.InitializeCollection, parent, index++);
            }
            ChildWithBidirectionalManyToMany childWithManyToMany = child as ChildWithBidirectionalManyToMany;

            if (childWithManyToMany != null)
            {
                if (((IPersistentCollection)childWithManyToMany.Parents).WasInitialized)
                {
                    CheckResult(listeners, listeners.InitializeCollection, childWithManyToMany, index++);
                }
            }
            CheckResult(listeners, listeners.PreCollectionUpdate, parent, index++);
            CheckResult(listeners, listeners.PostCollectionUpdate, parent, index++);
            if (childWithManyToMany != null)
            {
                CheckResult(listeners, listeners.PreCollectionUpdate, childWithManyToMany, index++);
                CheckResult(listeners, listeners.PostCollectionUpdate, childWithManyToMany, index++);
            }
            CheckNumberOfResults(listeners, index);
        }
        public static TResult Result <TSource, TResult>(this IChild <TSource, TResult> child,
                                                        TSource source, int?firstIndex, int?lastIndex)
        {
            var length = child.Count(source);

            if (length == 0)
            {
                return(child.Empty);
            }

            var left = firstIndex ?? 0;

            if (left > length)
            {
                return(child.Empty);
            }
            if (left < 0)
            {
                left = length + left;
            }
            if (left < 0)
            {
                left = 0;
            }

            var right = lastIndex ?? length - 1;

            if (right >= length)
            {
                return(child.Empty);
            }
            if (right < 0)
            {
                right = length + right;
            }
            if (right < 0)
            {
                right = 0;
            }
            if (left >= right)
            {
                return(child.Empty);
            }

            return(child.GetChilds(source, left, right));
        }
Example #15
0
        /// <summary>
        /// Find the root node of a Pipeline tree
        /// </summary>
        /// <returns></returns>
        private ANamable GetRoot()
        {
            Pipeline pipeRoot = this as Pipeline;

            if (pipeRoot != null)
            {
                return(pipeRoot);
            }

            IChild ancestor = this as IChild;

            if (ancestor != null && ancestor.Parent != null && ancestor.Parent != this)
            {
                return(ancestor.Parent.GetRoot());
            }

            return(this);
        }
Example #16
0
        public void DeleteParentAndChild()
        {
            CollectionListeners   listeners = new CollectionListeners(Sfi);
            IParentWithCollection parent    = CreateParentWithOneChild("parent", "child");
            IChild child = GetFirstChild(parent.Children);

            listeners.Clear();
            ISession     s  = OpenSession();
            ITransaction tx = s.BeginTransaction();

            parent = (IParentWithCollection)s.Get(parent.GetType(), parent.Id);
            IEntity e = child as IEntity;

            if (e != null)
            {
                child = (IChild)s.Get(child.GetType(), e.Id);
            }
            parent.RemoveChild(child);
            if (e != null)
            {
                s.Delete(child);
            }
            s.Delete(parent);
            tx.Commit();
            s.Close();
            int index = 0;

            CheckResult(listeners, listeners.InitializeCollection, parent, index++);
            ChildWithBidirectionalManyToMany childWithManyToMany = child as ChildWithBidirectionalManyToMany;

            if (childWithManyToMany != null)
            {
                CheckResult(listeners, listeners.InitializeCollection, childWithManyToMany, index++);
            }
            CheckResult(listeners, listeners.PreCollectionRemove, parent, index++);
            CheckResult(listeners, listeners.PostCollectionRemove, parent, index++);
            if (childWithManyToMany != null)
            {
                CheckResult(listeners, listeners.PreCollectionRemove, childWithManyToMany, index++);
                CheckResult(listeners, listeners.PostCollectionRemove, childWithManyToMany, index++);
            }
            CheckNumberOfResults(listeners, index);
        }
Example #17
0
        private static string ValidateSequenceType(this SequenceType sequence, IChild scope, string valueReference, bool isRequired, string modelReference = "client.models")
        {
            if (scope == null)
            {
                throw new ArgumentNullException(nameof(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())
                           .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);
        }
Example #18
0
        private static string ValidateEnumType(this EnumType enumType, IChild scope, string valueReference, bool isRequired)
        {
            if (scope == null)
            {
                throw new ArgumentNullException(nameof(scope));
            }

            var builder       = new IndentedStringBuilder("  ");
            var allowedValues = scope.GetUniqueName("allowedValues");
            var enumValue     = scope.GetUniqueName("enumValue");
            var updatedValue  = valueReference;

            builder.AppendLine("if ({0}) {{", valueReference)
            .Indent()
            .AppendLine("let {0} = {1};", allowedValues, enumType.GetEnumValuesArray());

            if (valueReference.StartsWith("this."))
            {
                builder.AppendLine("let {0} = {1};", enumValue, valueReference);
                updatedValue = enumValue;
            }
            builder.AppendLine("if (!{0}.some( function(item) {{ return item === {1}; }})) {{", allowedValues, updatedValue)
            .Indent()
            .AppendLine("throw new Error({0} + ' is not a valid value. The valid values are: ' + {1});", updatedValue, 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());
        }
Example #19
0
        private static string ValidateDictionaryType(this DictionaryType dictionary, IChild scope, string valueReference, bool isRequired, string modelReference = "client.models")
        {
            if (scope == null)
            {
                throw new ArgumentNullException(nameof(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())
                           .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);
        }
Example #20
0
        public static List <object> ParentTree(this IChild self)
        {
            List <object> objs = new List <object>();
            object        obj  = self;

            while (obj != null)
            {
                objs.Add(obj);
                if (obj is IChild)
                {
                    obj = ((IChild)obj).Parent;
                }
                else
                {
                    break;
                }
            }

            return(objs);
        }
        private void AddEntityUpdateStatement(IChild child, EntityInfo childInfo, DateTime timeStamp)
        {
            var builder = new ComplexCommandBuilder();

            var idParameter = child.Id.ToParameter();

            builder.AddParameter(idParameter);
            var whereClause = string.Format("{0}.{1} = {2}", childInfo.Name, childInfo.Identifier.Name, idParameter.Name);
            var statement   = new UpdateStatement(childInfo.Name, whereClause);

            var timeStampParameter = timeStamp.ToParameter();

            statement.Set(childInfo.TimeStamp.Name, timeStampParameter.Name);
            builder.AddParameter(timeStampParameter);

            foreach (var element in childInfo.Elements.Where(x => !x.IsReadOnly))
            {
                var value     = element.GetValue(child);
                var parameter = value.ToParameter();
                statement.Set(element.Name, parameter.Name);
                builder.AddParameter(parameter);
            }

            foreach (var dataType in childInfo.DataTypes)
            {
                foreach (var element in dataType.Elements)
                {
                    var value     = dataType.GetValue(element, child);
                    var parameter = value.ToParameter();
                    statement.Set(element.Name, parameter.Name);
                    builder.AddParameter(parameter);
                }
            }

            builder.AddStatement(statement);
            Add(builder);

            AddSaveStatements(child, childInfo, timeStamp);

            child.Save(timeStamp);
        }
Example #22
0
        private static string ValidateCompositeType(IChild scope, string valueReference, bool isRequired)
        {
            if (scope == null)
            {
                throw new ArgumentNullException(nameof(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());
        }
        private List <ExpressionNode> GetMethodCallParameters(IChild parent, ParserRuleContext context, ExpressionListContext expressionListContext)
        {
            List <ExpressionNode> results = new List <ExpressionNode>();

            if (expressionListContext != null)
            {
                var parameters = expressionListContext.GetRuleContexts <ParserRuleContext>();

                foreach (var parameter in parameters)
                {
                    ExpressionListener listener = new ExpressionListener(parent);

                    parameter.EnterRule(listener);

                    ExpressionNode result = listener.GetResult();
                    results.Add(result);
                }
            }

            return(results);
        }
Example #24
0
        /// <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 IModelType type, IChild scope, string valueReference, bool isRequired, string modelReference = "client.models")
        {
            if (scope == null)
            {
                throw new ArgumentNullException(nameof(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())
            {
                if (enumType.ModelAsString)
                {
                    return(New <PrimaryType>(KnownPrimaryType.String).ValidatePrimaryType(scope, valueReference, isRequired));
                }
                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 Parent(IChild child, IGrandChild grandChild)
 {
     _child = child;
     _grandChild = grandChild;
 }
		public virtual void RemoveChild(IChild child)
		{
			children.Remove(child);
		}
Example #27
0
 public ConstBoolExpression(IChild parent, ParserRuleContext context, bool value) : base(parent, context)
 {
     this.Value = value;
 }
        /// <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 IModelType type, IChild scope, string valueReference,
                                          Dictionary <Constraint, string> constraints)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var model      = type as CompositeTypeCs;
            var sequence   = type as SequenceTypeCs;
            var dictionary = type as DictionaryTypeCs;

            var sb = new IndentedStringBuilder();

            if (model != null && model.ShouldValidateChain())
            {
                sb.AppendLine("{0}.Validate();", valueReference);
            }

            if (constraints != null && constraints.Any())
            {
                AppendConstraintValidations(valueReference, constraints, sb, type);
            }

            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 override void AddChild(IChild child)
		{
			base.AddChild(child);
			((ChildWithBidirectionalManyToMany) child).AddParent(this);
		}
 public RequestsArrayWithDefaultCtor(IChild[] children)
     : base(children)
 {
 }
		public override void AddChild(IChild child)
		{
			base.AddChild(child);
			((ChildWithManyToOne)child).Parent = this;
		}
        /// <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 IModelType type,
            IChild 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.KnownPrimaryType == KnownPrimaryType.ByteArray)
                {
                    return builder.AppendLine("{0} = Base64.strict_encode64({0}.pack('c*'))", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == KnownPrimaryType.DateTime)
                {
                    return builder.AppendLine("{0} = {0}.new_offset(0).strftime('%FT%TZ')", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == KnownPrimaryType.DateTimeRfc1123)
                {
                    return builder.AppendLine("{0} = {0}.new_offset(0).strftime('%a, %d %b %Y %H:%M:%S GMT')", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == KnownPrimaryType.UnixTime)
                {
                    return builder.AppendLine("{0} = {0}.new_offset(0).strftime('%s')", 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;
        }
 public ParentImpl(IChild child)
 {
     m_child = child;
 }
 public RequestsArray(IChild[] children)
 {
     Children = children;
 }
Example #35
0
        private static string ValidatePrimaryType(this PrimaryType primary, IChild scope, string valueReference, bool isRequired)
        {
            if (scope == null)
            {
                throw new ArgumentNullException(nameof(scope));
            }

            if (primary == null)
            {
                throw new ArgumentNullException(nameof(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();

            if (primary.KnownPrimaryType == KnownPrimaryType.Boolean ||
                primary.KnownPrimaryType == KnownPrimaryType.Double ||
                primary.KnownPrimaryType == KnownPrimaryType.Decimal ||
                primary.KnownPrimaryType == KnownPrimaryType.Int ||
                primary.KnownPrimaryType == KnownPrimaryType.Long ||
                primary.KnownPrimaryType == 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.KnownPrimaryType == 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.KnownPrimaryType == 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.KnownPrimaryType == 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.KnownPrimaryType == KnownPrimaryType.ByteArray || primary.KnownPrimaryType == 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.KnownPrimaryType == KnownPrimaryType.DateTime || primary.KnownPrimaryType == KnownPrimaryType.Date ||
                     primary.KnownPrimaryType == KnownPrimaryType.DateTimeRfc1123 || primary.KnownPrimaryType == KnownPrimaryType.UnixTime)
            {
                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.KnownPrimaryType == 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($"'{valueReference}' not implemented");
            }
        }
Example #36
0
 public Statement(IChild parent, ParserRuleContext ruleContext)
 {
     this.Parent         = parent;
     this.ParsingContext = ruleContext;
 }
 public GrandParent(IParent parent, IChild child)
 {
 }
Example #38
0
 public void InheritedInterface()
 {
     // Test problem reported by Sean Rohead. This will throw an exception
     // if method Foo in the base class Parent is not implemented
     IChild proxy = (IChild)XmlRpcProxyGen.Create(typeof(IChild));
 }
 public Parent(IChild child, IGrandChild grandChild)
 {
     _child      = child;
     _grandChild = grandChild;
 }
Example #40
0
 public void ListMethods()
 {
     IChild proxy = (IChild)XmlRpcProxyGen.Create(typeof(IChild));
 }
 private static string GetFeatureName(IChild feature)
 {
     var split = feature.ToString().Split('.');
     if (split.Length > 0)
     {
         return split.Last();
     }
     return feature.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 IModelType type,
            IChild 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 EnumTypeRb;

            var builder = new IndentedStringBuilder("  ");

            if (primary != null)
            {
                if (primary.KnownPrimaryType == KnownPrimaryType.Int || primary.KnownPrimaryType == KnownPrimaryType.Long)
                {
                    return builder.AppendLine("{0} = Integer({0}) unless {0}.to_s.empty?", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == KnownPrimaryType.Double)
                {
                    return builder.AppendLine("{0} = Float({0}) unless {0}.to_s.empty?", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == KnownPrimaryType.ByteArray)
                {
                    return builder.AppendLine("{0} = Base64.strict_decode64({0}).unpack('C*') unless {0}.to_s.empty?", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == KnownPrimaryType.Date)
                {
                    return builder.AppendLine("{0} = MsRest::Serialization.deserialize_date({0}) unless {0}.to_s.empty?", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == KnownPrimaryType.DateTime)
                {
                    return builder.AppendLine("{0} = DateTime.parse({0}) unless {0}.to_s.empty?", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == KnownPrimaryType.DateTimeRfc1123)
                {
                    return builder.AppendLine("{0} = DateTime.parse({0}) unless {0}.to_s.empty?", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == 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.ModuleName, valueReference)
                    .AppendLine(
                        "  warn 'Enum {0} does not contain ' + {1}.downcase + ', but was received from the server.' unless enum_is_valid", enumType.ModuleName, 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;
        }
 public ApplicationCloseCheck(IChild screen, Action<IDialogManager, Action<bool>> closeCheck) {
     this.screen = screen;
     this.closeCheck = closeCheck;
 }
        /// <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 IModelType type, IChild scope, string valueReference, 
            Dictionary<Constraint, string> constraints)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var model = type as CompositeTypeCs;
            var sequence = type as SequenceTypeCs;
            var dictionary = type as DictionaryTypeCs;

            var sb = new IndentedStringBuilder();

            if (model != null && model.ShouldValidateChain())
            {
                sb.AppendLine("{0}.Validate();", valueReference);
            }

            if (constraints != null && constraints.Any())
            {
                AppendConstraintValidations(valueReference, constraints, sb, (type as PrimaryType)?.KnownFormat ?? KnownFormat.none);
            }

            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 StubDemoTestFixture()
 {
     _mockBase = MockRepository.Mock<IBase>();
     _mockChild = MockRepository.Mock<IChild>();
 }
 public ApplicationCloseCheck(IChild screen, Action <IDialogManager, Action <bool> > closeCheck)
 {
     this.screen     = screen;
     this.closeCheck = closeCheck;
 }
Example #47
0
 public Root(IChild child)
 {
     Child = child;
 }
 public virtual void RemoveChild(IChild child)
 {
     children.Remove(child);
 }
Example #49
0
 /// <summary>Returns a reference to the dialog host if the provided ViewModel is currently hosted in the dialog host.</summary>
 /// <param name="source">The hosted ViewModel.</param>
 /// <returns>Null if the ViewModel is not currently hosted in a dialog host, otherwise a reference to the current dialog host.</returns>
 public static IDialogHost GetCurrent(IChild source)
 {
     return source.Parent as IDialogHost;
 }
Example #50
0
 public Expression(IChild parent, ParserRuleContext context)
 {
     this.Parent         = parent;
     this.ParsingContext = context;
 }
Example #51
0
 public Parent(IChild child)
 {
     this.Child = child;
 }
Example #52
0
        private ResultModel <IChild> CreateContentInfoResultStatus(int code, string message, IChild data = null)
        {
            ResultModel <IChild> status = new ResultModel <IChild>()
            {
                Code    = code,
                Message = message,
                Data    = data
            };

            return(status);
        }
 public Root(IChild child)
 {
     Child = child;
 }