Example #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AccountManager"/> class.
 /// </summary>
 /// <param name="model">The Entity Framework data model.</param>
 public AccountManager(ModelContainer model)
     : base(model)
 {
     this.Accounts = model.Accounts;
     this.Servers = model.Servers;
     this.Users = model.Users;
 }
Example #2
0
        public void TestConstruction()
        {
            var obj = new ClassWithStructs();
            var container = new ModelContainer();
            container.NodeBuilder.PrimitiveTypes.Add(typeof(PrimitiveStruct));
            IModelNode model = container.GetOrCreateModelNode(obj, obj.GetType());
            Helper.PrintModelContainerContent(container, model);

            // Members should never have children
            Assert.That(model.GetChild("PrimitiveStruct").Children.Count, Is.EqualTo(0));
            // Primitive struct has been registered as a primitive type, so it should not hold a reference.
            Assert.Null(model.GetChild("PrimitiveStruct").Content.Reference);
            // Members should never have children.
            Assert.That(model.GetChild("NestedStruct").Children.Count, Is.EqualTo(0));
            // NestedStruct members should be accessible via a reference.
            Assert.NotNull(model.GetChild("NestedStruct").Content.Reference);
            // The referenced node must exist.
            var structNode = model.GetChild("NestedStruct").Content.Reference.AsObject.TargetNode;
            Assert.NotNull(structNode);
            // It should have two children, as the NestedStruct has.
            Assert.That(structNode.Children.Count, Is.EqualTo(2));
            // Similarly, the Struct member of the NestedStruct should hold a reference.
            Assert.NotNull(structNode.GetChild("Struct").Content.Reference);
            // The referenced node must exist.
            structNode = structNode.GetChild("Struct").Content.Reference.AsObject.TargetNode;
            Assert.NotNull(structNode);
            // It should have two children, as the SimpleStruct has.
            Assert.That(structNode.Children.Count, Is.EqualTo(2));
            // Finally, we run the ModelConsistencyCheckVisitor to detect potential other issues.
            Helper.ConsistencyCheck(container, obj);
        }
Example #3
0
    private void Load9Project()
    {
        ModelContainer ml = new ModelContainer();

        ProjectsReapeter.DataSource = ProjectView.GenerateFromProjects(ml.Projects.OrderByDescending(t => t.AddDate).Take(8).ToArray());
        ProjectsReapeter.DataBind();
    }
Example #4
0
 public MemberContent(INodeBuilder nodeBuilder, IContent container, IMemberDescriptor member, bool isPrimitive, IReference reference)
     : base(nodeBuilder.TypeDescriptorFactory.Find(member.Type), isPrimitive, reference)
 {
     if (container == null) throw new ArgumentNullException("container");
     Member = member;
     Container = container;
     modelContainer = nodeBuilder.ModelContainer;
 }
Example #5
0
 public static void ConsistencyCheck(ModelContainer container, object rootObject)
 {
     var visitor = new ModelConsistencyCheckVisitor(container.NodeBuilder);
     var model = container.GetModelNode(rootObject);
     visitor.Check((ModelNode)model, rootObject, rootObject.GetType(), true);
     foreach (var node in container.Models)
     {
         visitor.Check((ModelNode)node, node.Content.Value, node.Content.Type, true);
     }
 }
Example #6
0
        public void TestConstruction()
        {
            var obj = new ClassWithDictionaries();
            var container = new ModelContainer();
            IModelNode model = container.GetOrCreateModelNode(obj, obj.GetType());
            Console.WriteLine(model.PrintHierarchy());
            foreach (var guid in container.Guids)
            {
                var node = container.GetModelNode(guid);
                if (model != node)
                    Console.WriteLine(node.PrintHierarchy());
            }

            Assert.That(model.GetChild("StringIntDic").Children.Count, Is.EqualTo(0));
            Assert.That(model.GetChild("StringIntDic").Content.Value, Is.SameAs(obj.StringIntDic));
            Assert.That(model.GetChild("StringIntDic").Content.IsReference, Is.False);
            Assert.That(model.GetChild("StringClassDic").Children.Count, Is.EqualTo(0));
            Assert.That(model.GetChild("StringClassDic").Content.Value, Is.SameAs(obj.StringClassDic));
            Assert.That(model.GetChild("StringClassDic").Content.Reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            var enumerator = obj.StringClassDic.GetEnumerator();
            foreach (var reference in (ReferenceEnumerable)model.GetChild("StringClassDic").Content.Reference)
            {
                enumerator.MoveNext();
                var keyValuePair = enumerator.Current;
                Assert.That(reference.Index, Is.EqualTo(keyValuePair.Key));
                Assert.That(reference.ObjectValue, Is.EqualTo(keyValuePair.Value));
            }
            //Assert.That(model.GetChild("SimpleStructList").Children.Count, Is.EqualTo(0));
            //Assert.That(model.GetChild("SimpleStructList").Content.Value, Is.SameAs(obj.SimpleStructList));
            //Assert.That(model.GetChild("SimpleStructList").Content.Reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            //Assert.That(model.GetChild("NestedStructList").Children.Count, Is.EqualTo(0));
            //Assert.That(model.GetChild("NestedStructList").Content.Value, Is.SameAs(obj.NestedStructList));
            //Assert.That(model.GetChild("NestedStructList").Content.Reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            //Assert.That(model.GetChild("ListOfSimpleStructLists").Children.Count, Is.EqualTo(0));
            //Assert.That(model.GetChild("ListOfSimpleStructLists").Content.Value, Is.SameAs(obj.ListOfSimpleStructLists));
            //Assert.That(model.GetChild("ListOfSimpleStructLists").Content.Reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            //foreach (var reference in (ReferenceEnumerable)model.GetChild("ListOfSimpleStructLists").Content.Reference)
            //{
            //    Assert.That(reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            //}
            //Assert.That(model.GetChild("ListOfNestedStructLists").Children.Count, Is.EqualTo(0));
            //Assert.That(model.GetChild("ListOfNestedStructLists").Content.Value, Is.SameAs(obj.ListOfNestedStructLists));
            //Assert.That(model.GetChild("ListOfNestedStructLists").Content.Reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            //foreach (var reference in (ReferenceEnumerable)model.GetChild("ListOfNestedStructLists").Content.Reference)
            //{
            //    Assert.That(reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            //}

            //Assert.That(container.GetModelNode(obj.ClassList[0]), !Is.Null);
            //Assert.That(container.Guids.Count(), Is.EqualTo(10));
        }
Example #7
0
        public static void PrintModelContainerContent(ModelContainer container, IModelNode rootNode = null)
        {
            Console.WriteLine(@"Container content:");
            Console.WriteLine(@"------------------");
            // Print the root node first, if specified
            if (rootNode != null)
                Console.WriteLine(rootNode.PrintHierarchy());

            // Print other nodes next
            // TODO: FIXME
            //foreach (var node in container.Guids.Select(container.GetModelNode).Where(x => x != rootNode))
            //{
            //    Console.WriteLine(node.PrintHierarchy());
            //}
            Console.WriteLine(@"------------------");
        }
Example #8
0
        /// <summary>
        /// Mark account as "deleted".
        /// </summary>
        /// <param name="userId">User unique ID.</param>
        /// <param name="accountId">Account ID to mark as deleted.</param>
        public void DeleteAccount(Guid userId, int accountId)
        {
            if (userId == Guid.Empty)
            {
                throw new ArgumentException("User ID must not be empty.");
            }

            using (var mc = new ModelContainer())
            {
                Account account = ModelHelper.GetAccountById(mc, accountId);

                account.IsDeleted = true;

                mc.SaveChanges();
            }
        }
Example #9
0
        public void TestListOfNestedStructListsUpdate()
        {
            var        obj       = new ClassWithLists();
            var        container = new ModelContainer();
            IModelNode model     = container.GetOrCreateModelNode(obj, obj.GetType());

            Helper.PrintModelContainerContent(container, model);
            var listRef    = ((ReferenceEnumerable)model.GetChild("ListOfNestedStructLists").Content.Reference).Last();
            var objRef     = ((ReferenceEnumerable)listRef.TargetNode.Content.Reference).Last();
            var structNode = container.GetModelNode(((ObjectReference)objRef.TargetNode.GetChild("Struct").Content.Reference).TargetGuid);

            structNode.GetChild("SecondValue").Content.Value = 32;
            Helper.PrintModelContainerContent(container, model);
            Assert.That(obj.ListOfNestedStructLists[1][0].Struct.SecondValue, Is.EqualTo(32));
            Helper.ConsistencyCheck(container, obj);
        }
Example #10
0
        public async Task <bool> SetInterval(ModelContainer db, TelegramChat chat, AlertType alertType, int interval)
        {
            var telegramChatSetting = await db.TelegramChatSettings
                                      .FirstOrDefaultAsync(x => x.TelegramChatId == chat.Id && x.Type == alertType)
                                      .ConfigureAwait(false);

            if (telegramChatSetting == null)
            {
                return(false);
            }

            telegramChatSetting.Interval = interval;
            db.SaveChanges();

            return(true);
        }
Example #11
0
        public void TestDoubleReferenceMemberDataUpdate()
        {
            var        doubleRef = new DoubleReferenceClass(new SimpleObject());
            var        container = new ModelContainer();
            IModelNode model     = container.GetOrCreateModelNode(doubleRef, doubleRef.GetType());

            doubleRef.Object1.Name = "New Name";

            Assert.That(doubleRef.Object1.Name, Is.EqualTo("New Name"));
            Assert.That(doubleRef.Object2.Name, Is.EqualTo("New Name"));
            var object1TargetNode = ((ObjectReference)model.GetChild("Object1").Content.Reference).TargetNode;
            var object2TargetNode = ((ObjectReference)model.GetChild("Object2").Content.Reference).TargetNode;

            Assert.That(object1TargetNode.GetChild("Name").Content.Value, Is.EqualTo("New Name"));
            Assert.That(object2TargetNode.GetChild("Name").Content.Value, Is.EqualTo("New Name"));
        }
Example #12
0
        /// <summary>
        /// Mark category as "deleted".
        /// </summary>
        /// <param name="userId">User unique ID.</param>
        /// <param name="categoryId">Category ID to mark as deleted.</param>
        public void DeleteCategory(Guid userId, int categoryId)
        {
            if (userId == Guid.Empty)
            {
                throw new ArgumentException("User ID must not be empty.");
            }

            using (var mc = new ModelContainer())
            {
                Category category = ModelHelper.GetCategoryById(mc, categoryId);

                category.IsDeleted = true;

                mc.SaveChanges();
            }
        }
Example #13
0
        public void ProjectAsWrapper_Element_ProjectedValueContainsModelID()
        {
            // Arrange
            Customer           customer     = new Customer();
            SelectExpandClause selectExpand = new SelectExpandClause(new SelectItem[0], allSelected: true);
            Expression         source       = Expression.Constant(customer);

            // Act
            Expression projection = _binder.ProjectAsWrapper(source, selectExpand, _model.Customer, _model.Customers);

            // Assert
            SelectExpandWrapper <Customer> customerWrapper = Expression.Lambda(projection).Compile().DynamicInvoke() as SelectExpandWrapper <Customer>;

            Assert.NotNull(customerWrapper.ModelID);
            Assert.Same(_model.Model, ModelContainer.GetModel(customerWrapper.ModelID));
        }
Example #14
0
        public void TestConstruction()
        {
            var        obj       = new ClassWithDictionaries();
            var        container = new ModelContainer();
            IModelNode model     = container.GetOrCreateModelNode(obj, obj.GetType());

            Helper.PrintModelContainerContent(container, model);

            Assert.That(model.GetChild("StringIntDic").Children.Count, Is.EqualTo(0));
            Assert.That(model.GetChild("StringIntDic").Content.Value, Is.SameAs(obj.StringIntDic));
            Assert.That(model.GetChild("StringIntDic").Content.IsReference, Is.False);
            Assert.That(model.GetChild("StringClassDic").Children.Count, Is.EqualTo(0));
            Assert.That(model.GetChild("StringClassDic").Content.Value, Is.SameAs(obj.StringClassDic));
            Assert.That(model.GetChild("StringClassDic").Content.Reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            var enumerator = obj.StringClassDic.GetEnumerator();

            foreach (var reference in model.GetChild("StringClassDic").Content.Reference.AsEnumerable)
            {
                enumerator.MoveNext();
                var keyValuePair = enumerator.Current;
                Assert.That(reference.Index, Is.EqualTo(keyValuePair.Key));
                Assert.That(reference.ObjectValue, Is.EqualTo(keyValuePair.Value));
            }
            //Assert.That(model.GetChild("SimpleStructList").Children.Count, Is.EqualTo(0));
            //Assert.That(model.GetChild("SimpleStructList").Content.Value, Is.SameAs(obj.SimpleStructList));
            //Assert.That(model.GetChild("SimpleStructList").Content.Reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            //Assert.That(model.GetChild("NestedStructList").Children.Count, Is.EqualTo(0));
            //Assert.That(model.GetChild("NestedStructList").Content.Value, Is.SameAs(obj.NestedStructList));
            //Assert.That(model.GetChild("NestedStructList").Content.Reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            //Assert.That(model.GetChild("ListOfSimpleStructLists").Children.Count, Is.EqualTo(0));
            //Assert.That(model.GetChild("ListOfSimpleStructLists").Content.Value, Is.SameAs(obj.ListOfSimpleStructLists));
            //Assert.That(model.GetChild("ListOfSimpleStructLists").Content.Reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            //foreach (var reference in (ReferenceEnumerable)model.GetChild("ListOfSimpleStructLists").Content.Reference)
            //{
            //    Assert.That(reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            //}
            //Assert.That(model.GetChild("ListOfNestedStructLists").Children.Count, Is.EqualTo(0));
            //Assert.That(model.GetChild("ListOfNestedStructLists").Content.Value, Is.SameAs(obj.ListOfNestedStructLists));
            //Assert.That(model.GetChild("ListOfNestedStructLists").Content.Reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            //foreach (var reference in (ReferenceEnumerable)model.GetChild("ListOfNestedStructLists").Content.Reference)
            //{
            //    Assert.That(reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            //}

            //Assert.That(container.GetModelNode(obj.ClassList[0]), !Is.Null);
            //Assert.That(container.Guids.Count(), Is.EqualTo(10));
        }
Example #15
0
        public void Create()
        {
            m = ContentManager.GetModelByName("carro.3DS");
            m.CreateDisplayList(); //optimice the model and load it in opengl display lists

            m.ScaleX = 0.1f;
            m.ScaleY = 0.1f;
            m.ScaleZ = 0.1f;

            foreach (var item in m.GetMeshes)
            {
                item.CalcCenterPoint();// calculate th epivot point
                switch (item.Name)
                {
                case "tireA":
                case "tireB":
                case "tireC":
                case "tire":
                case "rimA":
                case "rimB":
                case "rimC":
                case "rim":
                    tires.Add(item);
                    break;

                case "body":
                    body = item;
                    break;
                }
            }

            if (color == Color.Blue)
            {
                texture = ContentManager.GetTextureByName("bodyBlue.jpg");
            }
            if (color == Color.Red)
            {
                texture = ContentManager.GetTextureByName("bodyRed.jpg");
            }
            if (color == Color.Black)
            {
                texture = ContentManager.GetTextureByName("bodyBlack.jpg");
                m.RemoveMeshesWithName("body");
                m.RemoveMeshesWithName("tire");
                m.RemoveMeshesWithName("rim");
            }
        }
Example #16
0
 public void TestConstruction()
 {
     var obj = new ClassWithStructs();
     var container = new ModelContainer();
     container.NodeBuilder.PrimitiveTypes.Add(typeof(PrimitiveStruct));
     IModelNode model = container.GetOrCreateModelNode(obj, obj.GetType());
     Console.WriteLine(model.PrintHierarchy());
     Assert.That(model.GetChild("NestedStruct").Children.Count, Is.EqualTo(2));
     Assert.That(model.GetChild("NestedStruct").GetChild("Struct").Children.Count, Is.EqualTo(2));
     Assert.That(model.GetChild("PrimitiveStruct").Children.Count, Is.EqualTo(0));
     var visitor = new ModelConsistencyCheckVisitor(container.NodeBuilder);
     visitor.Check((ModelNode)model, obj, typeof(ClassWithStructs), true);
     foreach (var node in container.Models)
     {
         visitor.Check((ModelNode)node, node.Content.Value, node.Content.Type, true);
     }
 }
Example #17
0
        public int AdaugaSalariat(Salariat salariat)
        {
            using (var model = new ModelContainer())
            {
                try
                {
                    model.Salariati.Add(salariat);
                    model.SaveChanges();

                    return(1);
                }
                catch
                {
                    return(-1);
                }
            }
        }
Example #18
0
        public ActionResult Stringer(Guid Id)
        {
            ModelContainer db = new ModelContainer();

            if (Id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Stringer stringer = db.Stringers.Find(Id);

            if (stringer == null)
            {
                return(HttpNotFound());
            }

            return(View(stringer));
        }
        public Res Bind(Test t, Group g, ModelContainer data)
        {
            bool Success = true;
            try
            {
                g.Tests.Add(t);
                data.Tests.First(tt => tt.TestId == t.TestId).Groups.Add(g);
                data.SaveChanges();

            }
            catch (Exception e)
            {
                Success = false;
            }

            return new Res(Success, null);
        }
Example #20
0
        public void TestSimpleContent()
        {
            var obj = new SimpleClass(1, "test");

            Assert.That(obj.FirstValue, Is.EqualTo(1));
            Assert.That(obj.SecondValue, Is.EqualTo("test"));

            var        container = new ModelContainer();
            IModelNode model     = container.GetOrCreateModelNode(obj, obj.GetType());

            Console.WriteLine(model.PrintHierarchy());
            model.GetChild("FirstValue").Content.Value  = 2;
            model.GetChild("SecondValue").Content.Value = "new value";

            Assert.That(obj.FirstValue, Is.EqualTo(2));
            Assert.That(obj.SecondValue, Is.EqualTo("new value"));
        }
Example #21
0
        /// <summary>
        /// Set the <see cref="TargetNode"/> and <see cref="TargetGuid"/> of the targeted object by retrieving it from or creating it to the given <see cref="ModelContainer"/>.
        /// </summary>
        /// <param name="modelContainer">The <see cref="ModelContainer"/> used to retrieve or create the target node.</param>
        public IModelNode SetTarget(ModelContainer modelContainer)
        {
            if (modelContainer == null) throw new ArgumentNullException("modelContainer");
            IModelNode targetNode = modelContainer.GetOrCreateModelNode(ObjectValue, Type);
            if (targetNode != null)
            {
                if (targetNode.Content.Value != null && !Type.IsInstanceOfType(targetNode.Content.Value)) throw new InvalidOperationException(@"The type of the retrieved node content does not match the type of this reference");

                if (TargetNode != null || TargetGuid != Guid.Empty)
                    throw new InvalidOperationException("TargetNode has already been set.");
                if (targetNode.Content.Value != null && !Type.IsInstanceOfType(targetNode.Content.Value))
                    throw new InvalidOperationException("TargetNode type does not match the reference type.");
                TargetNode = targetNode;
                TargetGuid = targetNode.Guid;
            }
            return targetNode;
        }
        public async Task <OkResult> Post([FromBody] Update update)
        {
            MessageController  messageController = this;
            ModelContainer     db     = new ModelContainer();
            TelegramBotService client = await Bot.Get();

            try
            {
                await client.ProcessCmd(db, update);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
                await client.SendTextMessageAsync(update.Message.Chat.Id, ex.Message);
            }
            return(messageController.Ok());
        }
Example #23
0
        //odeberu uživatele se zadaným Id z role správce konkrétního interpreta
        public ActionResult OdebratSpravce(int id)
        {
            using (ModelContainer db = new ModelContainer())
            {
                //zjistím id interpreta
                int idInterpreta = int.Parse(Session["idInterpretaPridatSpravce"].ToString());

                //odeberu správce interpreta
                db.SpravciInterpretu.Remove(db.SpravciInterpretu.Where(x => x.UzivatelId == id).Where(x => x.InterpretId == idInterpreta).First());

                //uložím změny
                db.SaveChanges();

                //přesměruji na potřebnou stránku
                return(RedirectToAction("PridatSpravce", new { id = idInterpreta }));
            }
        }
Example #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ObservableViewModel"/> class.
 /// </summary>
 /// <param name="serviceProvider">A service provider that can provide a <see cref="IDispatcherService"/> and an <see cref="ObservableViewModelService"/> to use for this view model.</param>
 /// <param name="modelContainer">A <see cref="ModelContainer"/> to use to build view model nodes.</param>
 /// <param name="dirtiables">The list of <see cref="IDirtiableViewModel"/> objects linked to this view model.</param>
 private ObservableViewModel(IViewModelServiceProvider serviceProvider, ModelContainer modelContainer, IEnumerable <IDirtiableViewModel> dirtiables)
     : base(serviceProvider)
 {
     if (modelContainer == null)
     {
         throw new ArgumentNullException("modelContainer");
     }
     if (dirtiables == null)
     {
         throw new ArgumentNullException("dirtiables");
     }
     this.modelContainer = modelContainer;
     this.dirtiables     = dirtiables;
     this.dirtiables.ForEach(x => x.DirtinessUpdated += DirtinessUpdated);
     observableViewModelService = serviceProvider.Get <ObservableViewModelService>();
     Logger = GlobalLogger.GetLogger(DefaultLoggerName);
 }
        public void TestDoubleReferenceAtConstruction()
        {
            var doubleRef = new DoubleReferenceClass(new SimpleObject());
            var container = new ModelContainer();
            IModelNode model = container.GetOrCreateModelNode(doubleRef, doubleRef.GetType());
            Assert.That(doubleRef.Object1, Is.EqualTo(doubleRef.Object2));
            Assert.That(model.GetChild("Object1").Content.Value, Is.EqualTo(doubleRef.Object1));
            Assert.That(model.GetChild("Object2").Content.Value, Is.EqualTo(doubleRef.Object2));

            Assert.That(model.GetChild("Object1").Content.IsReference, Is.True);
            Assert.That(model.GetChild("Object2").Content.IsReference, Is.True);

            var object1TargetNode = ((ObjectReference)model.GetChild("Object1").Content.Reference).TargetNode;
            var object2TargetNode = ((ObjectReference)model.GetChild("Object2").Content.Reference).TargetNode;
            Assert.That(object1TargetNode, Is.EqualTo(object2TargetNode));
            Assert.That(object1TargetNode.Content.Value, Is.EqualTo(doubleRef.Object1));
        }
Example #26
0
        public void TestSerializeObjectsTree()
        {
            var model = new ModelContainer();

            SimpleModelObject.CurrentModelContainer = model;

            var array1 = new TestObjectArray();
            var array2 = new TestObjectArray();

            var obj1 = new TestObject {
                Getal = 1
            };
            var obj2 = new TestObject {
                Getal = 2
            };
            var obj3 = new TestObject {
                Getal = 3
            };
            var obj4 = new TestObject {
                Getal = 4
            };
            var obj5 = new TestObject {
                Getal = 5
            };

            array1.Objects.Add(obj1);
            array2.Objects.Add(obj2);
            array2.Objects.Add(obj3);
            obj3.Object = obj4;
            obj4.Object = obj4;
            obj5.Object = obj5;


            var strm       = new MemoryStream();
            var writer     = new StreamWriter(strm);
            var serializer = new ModelSerializer(StringSerializer.Create(), new LoadedTypeSerializer());

            serializer.QueueForSerialization(array2);

            serializer.Serialize(writer);
            writer.Flush();

            strm.Position = 0;

            var str = getStringFromStream(strm);
        }
Example #27
0
        /// <summary>
        /// Gets account balance before specific date.
        /// </summary>
        /// <param name="accountId">Account ID.</param>
        /// <param name="dateTime">Specific date.</param>
        /// <returns>Account balance at the specific date.</returns>
        public decimal GetAccountBalance(int accountId, DateTime dateTime)
        {
            decimal balance;

            using (var mc = new ModelContainer(GetPersonalConnection(UserName)))
            {
                // Todo: Fix Sum() of Postings when there is no any posting yet.
                var firstPosting = mc.Postings.FirstOrDefault(p => p.Account.Id == accountId && p.Date < dateTime);

                balance = firstPosting != null
                                                ? mc.Postings.Where(p => p.Account.Id == accountId && p.Date < dateTime)
                          .Sum(p => p.Amount)
                                                : 0;
            }

            return(balance);
        }
Example #28
0
        /// <summary>
        /// Change user password or email to new values.
        /// </summary>
        /// <param name="userId">User unique ID.</param>
        /// <param name="oldPassword">User old password.</param>
        /// <param name="newPassword">User new password.</param>
        /// <param name="newEmail">User new email.</param>
        public void Update(Guid userId, string oldPassword, string newPassword, string newEmail)
        {
            if (userId == Guid.Empty)
            {
                throw new ArgumentException("User ID must not be empty.");
            }

            if (string.IsNullOrWhiteSpace(oldPassword))
            {
                throw new ArgumentException("Old password must not be empty.");
            }

            if (string.IsNullOrWhiteSpace(newPassword))
            {
                throw new ArgumentException("New password must not be empty.");
            }

            // Check password min length
            if (newPassword.Length < 5)
            {
                throw new Exception("New password is too short. Minimum length is 5.");
            }

            // Check password max length
            if (newPassword.Length > 256)
            {
                throw new Exception("New password is too long. Maximum length is 256.");
            }

            using (var mc = new ModelContainer())
            {
                User user = ModelHelper.GetUserById(mc, userId);

                if (user.Password != oldPassword)
                {
                    throw new Exception("Old password is incorrect.");
                }

                user.Password = newPassword;
                user.Email    = string.IsNullOrWhiteSpace(newEmail)
                                                                ? null
                                                                : newEmail.Trim();

                mc.SaveChanges();
            }
        }
Example #29
0
        public static bool addTag(Tag tag, DataFile file)
        {
            using (ModelContainer context = new ModelContainer())
            {
                Tag exists = context.Tags.Where(tg => tg.Name == tag.Name).FirstOrDefault();
                if (exists == null)
                {
                    exists = context.Tags.Add(tag);
                }
                context.SaveChanges();
                var toAdd = context.Tags.Where(tg => tg.Name == tag.Name).Include(tg => tg.DataFiles).FirstOrDefault();
                toAdd.DataFiles.Add(file);

                // context.SaveChanges();
                return(true);
            }
        }
Example #30
0
        public async Task <IActionResult> ChangeUserRole(string id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var UserData = await _context.UserData
                           .FirstOrDefaultAsync(m => m.Id == id);

            if (UserData == null)
            {
                return(NotFound());
            }

            var IdentRole = await _context.IdentRole
                            .FirstOrDefaultAsync(m => m.Id == id);

            if (UserData == null)
            {
                return(NotFound());
            }

            var val = await _context.IdentRole
                      .FirstOrDefaultAsync();


            //System.Diagnostics.Debug.WriteLine(roleManager.Roles);


            var CurrentRole = await _userManager.GetRolesAsync(UserData);

            this.currentID = id;

            System.Diagnostics.Debug.WriteLine("here yo");
            UserSpecs specs = new UserSpecs();

            specs.AvailableRoles = _roleManager.Roles.ToList();
            specs.CurrentRole    = CurrentRole.ToList();
            var modelCollection = new ModelContainer();

            modelCollection.AddModel(UserData);
            modelCollection.AddModel(specs);
            return(View(modelCollection));
        }
        private void BtnAcept_Click(object sender, EventArgs e)
        {
            switch (ExamenSeleccionado)
            {
                case "Word":

                    CerrarWords();
                    DestruirWords();
                    break;
                case "Excel":
                    CerrarExcels();
                    break;
                case "Power Point":
                    CerrarPowerPoints();
                    DestruirPowerPoints();
                    break;
            }

            if (RbContineLatter.Checked == true)
            {
                Application.Exit();
            }
               if(RbFinishQuestions.Checked == true)
            {
                while (this.preguntasResueltas <= FormMain.NUMERO_DE_PREGUNTAS)
                {
                    GuardarNoResueltas();
                };

                using (ModelContainer conexion = new ModelContainer())
                {
                    var examen = conexion.Examenes
                        .Where(p => p.IdExamen == examenIdExamen).
                        FirstOrDefault();
                    examen.avance = contadorDeAvance - 1;
                    examen.preguntasResueltas = this.preguntasResueltas - 1;
                    examen.banderaReanudar = false;
                    conexion.SaveChanges();
                }

                FormMain.formExamResult.Show();
                FormMain.formExamResult.Activate();
                this.Hide();
            }
        }
Example #32
0
        public SensorStatusViewModel(ModelContainer modelContainer)
        {
            this.modelContainer = modelContainer;
            AccStatus           = new SensorStatus();
            GyroStatus          = new SensorStatus();
            MagStatus           = new SensorStatus();
            BaroStatus          = new SensorStatus();
            AccChangedCallback(modelContainer.modelStatus.sensorStatus.AccStatus);
            GyroChangedCallback(modelContainer.modelStatus.sensorStatus.GyroStatus);
            BaroChangedCallback(modelContainer.modelStatus.sensorStatus.BaroStatus);
            MagChangedCallback(modelContainer.modelStatus.sensorStatus.MagStatus);

            modelContainer.modelStatus.networkStatus.ConnectedToJetsonCallback += (bool val) => { JetsonConnected = val; };
            modelContainer.modelStatus.sensorStatus.AccStatusChanged           += AccChangedCallback;
            modelContainer.modelStatus.sensorStatus.GyroStatusChanged          += GyroChangedCallback;
            modelContainer.modelStatus.sensorStatus.MagStatusChanged           += MagChangedCallback;
            modelContainer.modelStatus.sensorStatus.BaroStatusChanged          += BaroChangedCallback;
        }
Example #33
0
        public void TestNestedStructItemUpdate()
        {
            var        obj       = new ClassWithLists();
            var        container = new ModelContainer();
            IModelNode model     = container.GetOrCreateModelNode(obj, obj.GetType());

            Helper.PrintModelContainerContent(container, model);
            var objRef     = ((ReferenceEnumerable)model.GetChild("NestedStructList").Content.Reference).First();
            var structNode = container.GetModelNode(((ObjectReference)objRef.TargetNode.GetChild("Struct").Content.Reference).TargetGuid);

            structNode.GetChild("SecondValue").Content.Value = 32;
            Helper.PrintModelContainerContent(container, model);
            Assert.That(obj.NestedStructList[0].Struct.SecondValue, Is.EqualTo(32));
            var visitor = new ModelConsistencyCheckVisitor(container.NodeBuilder);

            visitor.Check((ModelNode)model, obj, typeof(ClassWithLists), true);
            Helper.ConsistencyCheck(container, obj);
        }
Example #34
0
        /// <summary>
        /// 固定模板的抽象类构造函数
        /// </summary>
        /// <param name="consType">创建类别</param>
        public CodeManageBase(ConstructType consType)
        {
            IsStaticModel = false;
            ModelEntity   = null;
            Construct     = consType;
            StringBuilder result = new StringBuilder();

            using (StreamReader reader = new StreamReader(string.Format("{0}.sem", consType.ToString()).GetFileResource("Code")))
            {
                while (reader.Peek() != -1)
                {
                    string temp = reader.ReadLine();
                    temp = ModelContainer.Replace(temp);
                    result.AppendLine(temp);
                }
            }
            CodeContent = result.ToString();
        }
        public Res ChangeTextQuastion(Func<Quastion, bool> p, string text, ModelContainer data)
        {
            bool Success = true;
            IEnumerable<Quastion> quastions = null;
            try
            {
                quastions = data.Quastions.Select(row => row).Where(p);
                foreach(Quastion q in quastions)
                    q.Text = text;
                data.SaveChanges();
            }
            catch (Exception e)
            {
                Success = false;
            }

            return new Res(Success, quastions);
        }
        public static DataFile updateFile(DataFile newFile)
        {
            using (ModelContainer context = new ModelContainer())
            {
                DataFile oldFile = context.DataFiles.Find(newFile.Id);
                if (oldFile == null)
                {
                    return(null);
                }

                oldFile.Path     = newFile.Path;
                oldFile.Deleted  = newFile.Deleted;
                oldFile.Location = newFile.Location;
                oldFile.Name     = newFile.Name;
                context.SaveChanges();
                return(oldFile);
            }
        }
Example #37
0
 public IHttpActionResult PostLogin([FromBody] UserBio userBio)//(string login, string pw) doesn't work coz [FromBody] can b applied to only 1 arg. Must have a complex type
 {
     using (ModelContainer db = new ModelContainer())
     {
         var     u                = db.Users.Where(x => x.loginName == userBio.loginName && x.pw == userBio.pw).FirstOrDefault();
         var     user_id          = u.Id_User; //db.Users.Where(x => x.loginName == userBio.loginName && x.pw == userBio.pw).Select(a => a.Id_User).FirstOrDefault();//.Any(x => x.loginName == loginPw.login && x.pw == loginPw.pw);
         UserBio userToBeReturned = new UserBio()
         {
             Id_User = u.Id_User, address = u.address, email = u.email, loginName = u.loginName, nameOfUser = u.nameOfUser, phone = u.phone, pw = u.pw, role = u.role
         };
         if (user_id > 0)
         {
             //navigation property interferes w serialization
             return(Ok(userToBeReturned));//login success
         }
     }
     return(Ok(0));//login fail
 }
Example #38
0
        public void TestConstructionWithNullObject()
        {
            var obj       = new ClassWithNullObject();
            var container = new ModelContainer();
            var node      = (ModelNode)container.GetOrCreateModelNode(obj, obj.GetType());

            Console.WriteLine(node.PrintHierarchy());

            var visitor = new ModelConsistencyCheckVisitor(container.NodeBuilder);

            visitor.Check(node, obj, typeof(ClassWithNullObject), true);

            foreach (var viewModel in container.Models)
            {
                visitor.Check((ModelNode)viewModel, viewModel.Content.Value, viewModel.Content.Type, true);
                Console.WriteLine(viewModel.PrintHierarchy());
            }
        }
        private void DgvAlumnos_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            BtnGoToExam.Enabled = false;

            int idAlumno = 0;

            foreach (DataGridViewRow row in DgvAlumnos.SelectedRows)
            {
                idAlumno = Convert.ToInt32(row.Cells[2].Value);
            }
            using (ModelContainer conexion = new ModelContainer())
            {
                this.DgvExams.DataSource = conexion.Examenes.Where(p => p.alumnoIdAlumno == idAlumno).Where(p => p.banderaReanudar == true).ToList();
            }
            FormMain.idAlumnoActual = idAlumno;

            DgvExams.Visible = true;
        }
Example #40
0
        /* GET /Home/Index
         * Vrací základní přehled novinek a zároveň rozcestník mezi interpreti, příspěvky a články.
         */
        public ActionResult Index()
        {
            HomeIndexViewModel model = new HomeIndexViewModel();

            using (ModelContainer db = new ModelContainer())
            {
                model.NejnovejsiInterpreti = db.Interpreti.OrderByDescending(x => x.DatumVytvoreni).Take(POCET_ZAZNAMU).ToList();
                model.NejnovejsiClanky     = db.Clanky.OrderByDescending(x => x.DatumVytvoreni).Take(POCET_ZAZNAMU).ToList();
                model.NejnovejsiPrispevky  = db.Prispevky.Where(x => x.Schvalen == true).OrderByDescending(x => x.DatumPridani).Take(POCET_ZAZNAMU).ToList();

                //zjistím zda existují případně kolik nevyřízené žádosti - pokud ano oznámím ve View přihlášenému uživateli
                int idPrihlaseneho           = int.Parse(Session["uzivatelID"].ToString());
                int pocetNevyrizenychZadosti = db.Zadosti.Where(x => x.ZadostKomu.Id == idPrihlaseneho).Where(x => x.StavZadosti == StavZadosti.Cekajici).Count();
                model.pocetNevyrizenychZadosti = pocetNevyrizenychZadosti;

                return(View(model));
            }
        }
Example #41
0
 public ModelNodeCommandWrapper(IViewModelServiceProvider serviceProvider, INodeCommand nodeCommand, string observableNodePath, ObservableViewModelIdentifier identifier, ModelNodePath nodePath, ModelContainer modelContainer, IEnumerable <IDirtiableViewModel> dirtiables)
     : base(serviceProvider, dirtiables)
 {
     if (nodeCommand == null)
     {
         throw new ArgumentNullException("nodeCommand");
     }
     if (modelContainer == null)
     {
         throw new ArgumentNullException("modelContainer");
     }
     this.identifier     = identifier;
     this.nodePath       = nodePath;
     this.modelContainer = modelContainer;
     this.nodeCommand    = nodeCommand;
     service             = serviceProvider.Get <ObservableViewModelService>();
     ObservableNodePath  = observableNodePath;
 }
Example #42
0
        public static void PrintModelContainerContent(ModelContainer container, IModelNode rootNode = null)
        {
            Console.WriteLine(@"Container content:");
            Console.WriteLine(@"------------------");
            // Print the root node first, if specified
            if (rootNode != null)
            {
                Console.WriteLine(rootNode.PrintHierarchy());
            }

            // Print other nodes next
            // TODO: FIXME
            //foreach (var node in container.Guids.Select(container.GetModelNode).Where(x => x != rootNode))
            //{
            //    Console.WriteLine(node.PrintHierarchy());
            //}
            Console.WriteLine(@"------------------");
        }
 public Res ChangeVariant(Func<Variant, bool> p, string Text, bool isValid, ModelContainer data)
 {
     bool Success = true;
     IEnumerable<Variant> variants = null;
     try
     {
         variants = data.Variants.Select(row => row).Where(p);
         foreach (Variant v in variants)
         {
             v.IsValid = isValid;
             v.Text = Text;
         }
         data.SaveChanges();
     }
     catch (Exception e)
     {
         Success = false;
     }
     return new Res(Success, variants);
 }
        public Res Check(Test t, ModelContainer data, aspnet_Users user)
        {
            int c = 0;
            bool Success = true;
            try
            {
                Test test = (ReadTests(x => x.TestId == t.TestId, data).Value as IEnumerable<Test>).First();
                //сравнение вопросов у тестов
                for(int i = 0; i < test.Quastions.ToList().Count; i++)
                {
                    int b = 1;
                    for(int j = 0; j < test.Quastions.ToList()[i].Variants.Count; j++)
                    {
                        if (test.Quastions.ToList()[i].Variants.ToList()[j].IsValid != t.Quastions.ToList()[i].Variants.ToList()[j].IsValid)
                        {
                            b = 0;
                        }
                    }
                    c += b;

                }

                //сохранение результатов, только если не уже не был пройден этот тест
                if (data.Results.FirstOrDefault(x => x.aspnet_Users.UserId == user.UserId && x.TestId == t.TestId) != null)
                    return new Res(Success, data.Results.FirstOrDefault(x => x.aspnet_Users.UserId == user.UserId && x.TestId == t.TestId).Result1);
                Result r = data.Results.Create();
                r.TestId = t.TestId;
                r.Test = test;
                r.Result1 = c;
                r.aspnet_Users = user;
                r.aspnet_Users_UserId = user.UserId;
                data.Results.Add(r);
                data.SaveChanges();
            }
            catch (Exception e)
            {
                Success = false;
            }

            return new Res(Success, c);
        }
Example #45
0
 public void TestNullLists()
 {
     var obj = new ClassWithNullLists();
     var container = new ModelContainer();
     IModelNode model = container.GetOrCreateModelNode(obj, obj.GetType());
     Helper.PrintModelContainerContent(container, model);
     Helper.ConsistencyCheck(container, obj);
 }
Example #46
0
 public void TestStructItemUpdate()
 {
     var obj = new ClassWithLists();
     var container = new ModelContainer();
     IModelNode model = container.GetOrCreateModelNode(obj, obj.GetType());
     Helper.PrintModelContainerContent(container, model);
     var objRef = ((ReferenceEnumerable)model.GetChild("SimpleStructList").Content.Reference).First();
     objRef.TargetNode.GetChild("SecondValue").Content.Value = 32;
     Helper.PrintModelContainerContent(container, model);
     Assert.That(obj.SimpleStructList[0].SecondValue, Is.EqualTo(32));
     Helper.ConsistencyCheck(container, obj);
 }
Example #47
0
 public void TestListOfNestedStructListsUpdate()
 {
     var obj = new ClassWithLists();
     var container = new ModelContainer();
     IModelNode model = container.GetOrCreateModelNode(obj, obj.GetType());
     Helper.PrintModelContainerContent(container, model);
     var listRef = ((ReferenceEnumerable)model.GetChild("ListOfNestedStructLists").Content.Reference).Last();
     var objRef = ((ReferenceEnumerable)listRef.TargetNode.Content.Reference).Last();
     var structNode = container.GetModelNode(((ObjectReference)objRef.TargetNode.GetChild("Struct").Content.Reference).TargetGuid);
     structNode.GetChild("SecondValue").Content.Value = 32;
     Helper.PrintModelContainerContent(container, model);
     Assert.That(obj.ListOfNestedStructLists[1][0].Struct.SecondValue, Is.EqualTo(32));
     Helper.ConsistencyCheck(container, obj);
 }
Example #48
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ModelManager"/> class.
 /// </summary>
 /// <param name="model">The Entity Framework data model.</param>
 public ModelManager(ModelContainer model)
 {
     this.container = model;
 }
Example #49
0
        public void TestMultipleNestedStruct()
        {
            var obj = new SimpleClassWithNestedStruct(1.0, "test", 5.0, "inner value");
            Assert.That(obj.Struct.FirstValue, Is.EqualTo(1.0));
            Assert.That(obj.Struct.SecondValue, Is.EqualTo("test"));
            Assert.That(obj.Struct.InnerStruct.FirstValue, Is.EqualTo(5.0));
            Assert.That(obj.Struct.InnerStruct.SecondValue, Is.EqualTo("inner value"));

            var container = new ModelContainer();
            IModelNode model = container.GetOrCreateModelNode(obj, obj.GetType());
            Console.WriteLine(model.PrintHierarchy());
            var structNode = model.GetChild("Struct").Content.Reference.AsObject.TargetNode;
            structNode.GetChild("FirstValue").Content.Value = 2.0;
            structNode.GetChild("SecondValue").Content.Value = "new value";
            structNode = structNode.GetChild("InnerStruct").Content.Reference.AsObject.TargetNode;
            structNode.GetChild("FirstValue").Content.Value = 7.0;
            structNode.GetChild("SecondValue").Content.Value = "new inner value";

            Assert.That(obj.Struct.FirstValue, Is.EqualTo(2.0));
            Assert.That(obj.Struct.SecondValue, Is.EqualTo("new value"));
            Assert.That(obj.Struct.InnerStruct.FirstValue, Is.EqualTo(7.0));
            Assert.That(obj.Struct.InnerStruct.SecondValue, Is.EqualTo("new inner value"));
        }
Example #50
0
 public void Create()
 {
     m = ContentManager.GetModelByName("nave.3DS");
      m.CreateDisplayList();
 }
Example #51
0
 public void TestPrimitiveItemUpdate()
 {
     var obj = new ClassWithDictionaries();
     var container = new ModelContainer();
     IModelNode model = container.GetOrCreateModelNode(obj, obj.GetType());
     Helper.PrintModelContainerContent(container, model);
     ((Dictionary<string, int>)model.GetChild("StringIntDic").Content.Value)["b"] = 42;
     ((Dictionary<string, int>)model.GetChild("StringIntDic").Content.Value).Add("d", 26);
     Assert.That(obj.StringIntDic.Count, Is.EqualTo(4));
     Assert.That(obj.StringIntDic["b"], Is.EqualTo(42));
     Assert.That(obj.StringIntDic["d"], Is.EqualTo(26));
     Helper.PrintModelContainerContent(container, model);
     Helper.ConsistencyCheck(container, obj);
 }
Example #52
0
 public void TestNestedStructItemUpdate()
 {
     var obj = new ClassWithLists();
     var container = new ModelContainer();
     IModelNode model = container.GetOrCreateModelNode(obj, obj.GetType());
     Helper.PrintModelContainerContent(container, model);
     var objRef = ((ReferenceEnumerable)model.GetChild("NestedStructList").Content.Reference).First();
     var structNode = container.GetModelNode(((ObjectReference)objRef.TargetNode.GetChild("Struct").Content.Reference).TargetGuid);
     structNode.GetChild("SecondValue").Content.Value = 32;
     Helper.PrintModelContainerContent(container, model);
     Assert.That(obj.NestedStructList[0].Struct.SecondValue, Is.EqualTo(32));
     var visitor = new ModelConsistencyCheckVisitor(container.NodeBuilder);
     visitor.Check((ModelNode)model, obj, typeof(ClassWithLists), true);
     Helper.ConsistencyCheck(container, obj);
 }
        public void TestDoubleReferenceMemberDataUpdate()
        {
            var doubleRef = new DoubleReferenceClass(new SimpleObject());
            var container = new ModelContainer();
            IModelNode model = container.GetOrCreateModelNode(doubleRef, doubleRef.GetType());

            doubleRef.Object1.Name = "New Name";

            Assert.That(doubleRef.Object1.Name, Is.EqualTo("New Name"));
            Assert.That(doubleRef.Object2.Name, Is.EqualTo("New Name"));
            var object1TargetNode = ((ObjectReference)model.GetChild("Object1").Content.Reference).TargetNode;
            var object2TargetNode = ((ObjectReference)model.GetChild("Object2").Content.Reference).TargetNode;
            Assert.That(object1TargetNode.GetChild("Name").Content.Value, Is.EqualTo("New Name"));
            Assert.That(object2TargetNode.GetChild("Name").Content.Value, Is.EqualTo("New Name"));
        }
Example #54
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PlayerManager"/> class.
 /// </summary>
 /// <param name="model">The Entity Framework data model.</param>
 public PlayerManager(ModelContainer model)
     : base(model)
 {
     this.Entities = model.Entities;
     this.Properties = model.Properties;
 }
Example #55
0
        public void TestNodeConstruction()
        {
            var obj = new SimpleObject(1, 2, 3, 4)
            {
                Name = "Test",
                MemberToIgnore = int.MaxValue,
                SubObject = new SimpleObject(5, 6, 7, 8),
                Collection = 
                {
                    "List Item",
                    22.5,
                    Guid.NewGuid(),
                    new List<string> { "one", "two", "three" },
                    new SimpleObject(9, 10, 11, 12),
                },
                Dictionary =
                {
                    { "Item1", "List Item" },
                    { "Item2", 22.5 },
                    { "Item3", Guid.NewGuid() },
                    { "Item4", new List<string> { "one", "two", "three" } },
                    { "Item5", new SimpleObject(9, 10, 11, 12) },
                },
            };

            var container = new ModelContainer();
            var node = (ModelNode)container.GetOrCreateModelNode(obj, obj.GetType());
            Helper.PrintModelContainerContent(container, node);
            // Run the consistency check to verify construction.
            Helper.ConsistencyCheck(container, obj);
        }
Example #56
0
        public void TestConstructionWithNullObject()
        {
            var obj = new ClassWithNullObject();
            var container = new ModelContainer();
            var node = (ModelNode)container.GetOrCreateModelNode(obj, obj.GetType());
            Console.WriteLine(node.PrintHierarchy());

            var visitor = new ModelConsistencyCheckVisitor(container.NodeBuilder);
            visitor.Check(node, obj, typeof(ClassWithNullObject), true);

            foreach (var viewModel in container.Models)
            {
                visitor.Check((ModelNode)viewModel, viewModel.Content.Value, viewModel.Content.Type, true);
                Console.WriteLine(viewModel.PrintHierarchy());
            }

        }
Example #57
0
        public void TestSimpleContent()
        {
            var obj = new SimpleClass(1, "test");
            Assert.That(obj.FirstValue, Is.EqualTo(1));
            Assert.That(obj.SecondValue, Is.EqualTo("test"));

            var container = new ModelContainer();
            IModelNode model = container.GetOrCreateModelNode(obj, obj.GetType());
            Console.WriteLine(model.PrintHierarchy());
            model.GetChild("FirstValue").Content.Value = 2;
            model.GetChild("SecondValue").Content.Value = "new value";

            Assert.That(obj.FirstValue, Is.EqualTo(2));
            Assert.That(obj.SecondValue, Is.EqualTo("new value"));
        }
Example #58
0
        public void TestNodeConstruction()
        {
            var simpleObject = new SimpleObject(1, 2, 3, 4) { Name = "Test", MemberToIgnore = int.MaxValue, SubObject = new SimpleObject(5, 6, 7, 8) };
            simpleObject.Collection.Add("List Item");
            simpleObject.Collection.Add(22.5);
            simpleObject.Collection.Add(Guid.NewGuid());
            simpleObject.Collection.Add(new List<string> { "one", "two", "three" });
            simpleObject.Collection.Add(new SimpleObject(9, 10, 11, 12));
            simpleObject.Dictionary.Add("Item1", "List Item");
            simpleObject.Dictionary.Add("Item2", 22.5);
            simpleObject.Dictionary.Add("Item3", Guid.NewGuid());
            simpleObject.Dictionary.Add("Item4", new List<string> { "one", "two", "three" });
            simpleObject.Dictionary.Add("Item5", new SimpleObject(9, 10, 11, 12));
            var container = new ModelContainer();
            var node = (ModelNode)container.GetOrCreateModelNode(simpleObject, simpleObject.GetType());
            Console.WriteLine(node.PrintHierarchy());

            var visitor = new ModelConsistencyCheckVisitor(container.NodeBuilder);
            visitor.Check(node, simpleObject, typeof(SimpleObject), true);

            foreach (var viewModel in container.Models)
            {
                visitor.Check((ModelNode)viewModel, viewModel.Content.Value, viewModel.Content.Type, true);
                Console.WriteLine(viewModel.PrintHierarchy());
            }
        }
Example #59
0
 public void TestPrimitiveItemUpdate()
 {
     var obj = new ClassWithLists();
     var container = new ModelContainer();
     IModelNode model = container.GetOrCreateModelNode(obj, obj.GetType());
     Console.WriteLine(model.PrintHierarchy());
     ((List<int>)model.GetChild("IntList").Content.Value)[1] = 42;
     ((List<int>)model.GetChild("IntList").Content.Value).Add(26);
     Assert.That(obj.IntList.Count, Is.EqualTo(4));
     Assert.That(obj.IntList[1], Is.EqualTo(42));
     Assert.That(obj.IntList[3], Is.EqualTo(26));
     Helper.ConsistencyCheck(container, obj);
 }
Example #60
0
        public void TestConstruction()
        {
            var obj = new ClassWithLists();
            var container = new ModelContainer();
            IModelNode model = container.GetOrCreateModelNode(obj, obj.GetType());
            Helper.PrintModelContainerContent(container, model);

            Assert.That(model.GetChild("IntList").Children.Count, Is.EqualTo(0));
            Assert.That(model.GetChild("IntList").Content.Value, Is.SameAs(obj.IntList));
            Assert.That(model.GetChild("IntList").Content.IsReference, Is.False);
            Assert.That(model.GetChild("ClassList").Children.Count, Is.EqualTo(0));
            Assert.That(model.GetChild("ClassList").Content.Value, Is.SameAs(obj.ClassList));
            Assert.That(model.GetChild("ClassList").Content.Reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            Assert.That(model.GetChild("SimpleStructList").Children.Count, Is.EqualTo(0));
            Assert.That(model.GetChild("SimpleStructList").Content.Value, Is.SameAs(obj.SimpleStructList));
            Assert.That(model.GetChild("SimpleStructList").Content.Reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            Assert.That(model.GetChild("NestedStructList").Children.Count, Is.EqualTo(0));
            Assert.That(model.GetChild("NestedStructList").Content.Value, Is.SameAs(obj.NestedStructList));
            Assert.That(model.GetChild("NestedStructList").Content.Reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            Assert.That(model.GetChild("ListOfSimpleStructLists").Children.Count, Is.EqualTo(0));
            Assert.That(model.GetChild("ListOfSimpleStructLists").Content.Value, Is.SameAs(obj.ListOfSimpleStructLists));
            Assert.That(model.GetChild("ListOfSimpleStructLists").Content.Reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            foreach (var reference in model.GetChild("ListOfSimpleStructLists").Content.Reference.AsEnumerable)
            {
                Assert.That(reference, Is.AssignableFrom(typeof(ObjectReference)));
            }
            Assert.That(model.GetChild("ListOfNestedStructLists").Children.Count, Is.EqualTo(0));
            Assert.That(model.GetChild("ListOfNestedStructLists").Content.Value, Is.SameAs(obj.ListOfNestedStructLists));
            Assert.That(model.GetChild("ListOfNestedStructLists").Content.Reference, Is.AssignableFrom(typeof(ReferenceEnumerable)));
            foreach (var reference in model.GetChild("ListOfNestedStructLists").Content.Reference.AsEnumerable)
            {
                Assert.That(reference, Is.AssignableFrom(typeof(ObjectReference)));
            }

            Assert.That(container.GetModelNode(obj.ClassList[0]), !Is.Null);
            Assert.That(container.Guids.Count(), Is.EqualTo(18));
            Helper.ConsistencyCheck(container, obj);
        }