Example #1
0
        public void NoFail()
        {
            IDataPortal <RollbackRoot> dataPortal = _testDIContext.CreateDataPortal <RollbackRoot>();

            TestResults.Reinitialise();
            RollbackRoot root = Csla.Test.RollBack.RollbackRoot.NewRoot(dataPortal);

            root.BeginEdit();
            root.Data = "saved";
            Assert.AreEqual("saved", root.Data, "data is 'saved'");
            Assert.AreEqual(false, root.Fail, "fail is false");
            Assert.AreEqual(true, root.IsDirty, "isdirty is true");
            Assert.AreEqual(true, root.IsValid, "isvalid is true");
            Assert.AreEqual(true, root.IsNew, "isnew is true");

            TestResults.Reinitialise();
            RollbackRoot tmp = (RollbackRoot)(root.Clone());

            root.ApplyEdit();
            root = root.Save();

            Assert.IsNotNull(root, "obj is not null");
            Assert.AreEqual("Inserted", TestResults.GetResult("Root"), "obj was inserted");
            Assert.AreEqual("saved", root.Data, "data is 'saved'");
            Assert.AreEqual(false, root.IsNew, "is new is false");
            Assert.AreEqual(false, root.IsDeleted, "isdeleted is false");
            Assert.AreEqual(false, root.IsDirty, "isdirty is false");
        }
Example #2
0
        public void LessThanSetsErrorOnBothFields()
        {
            IDataPortal <RuleBaseClassesRoot> dataPortal = _testDIContext.CreateDataPortal <RuleBaseClassesRoot>();

            // StartDate less than
            string ruleSet = "Date";
            string err1, err2;
            var    actual = RuleBaseClassesRoot.NewEditableRoot(dataPortal, ruleSet);

            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
            actual.StartDate = "today";
            actual.EndDate   = "yesterday";

            err1 = ((IDataErrorInfo)actual)[RuleBaseClassesRoot.StartDateProperty.Name];
            err2 = ((IDataErrorInfo)actual)[RuleBaseClassesRoot.EndDateProperty.Name];

            Assert.IsFalse(actual.IsSelfValid); // object has broken rule
            Assert.IsTrue(err1.Length > 1);     // both fields have error message
            Assert.IsTrue(err2.Length > 1);

            actual.EndDate = "tomorrow";
            err1           = ((IDataErrorInfo)actual)[RuleBaseClassesRoot.StartDateProperty.Name];
            err2           = ((IDataErrorInfo)actual)[RuleBaseClassesRoot.EndDateProperty.Name];

            Assert.IsTrue(actual.IsSelfValid);   // object has no broken rules
            Assert.AreEqual(string.Empty, err1); // both fields are now OK
            Assert.AreEqual(string.Empty, err2);
        }
Example #3
0
        public async Task TestSaveWhileBusy()
        {
            IDataPortal <ItemWithAsynchRule> dataPortal = _testDIContext.CreateDataPortal <ItemWithAsynchRule>();

            TestResults.Reinitialise();

            UnitTestContext context = GetContext();
            var             item    = await dataPortal.FetchAsync("an id");

            item.RuleField = "some value";
            context.Assert.IsTrue(item.IsBusy);
            context.Assert.IsFalse(item.IsSavable);

            try
            {
                await item.SaveAsync();
            }
            catch (Exception ex)
            {
                var error = ex as InvalidOperationException;
                context.Assert.IsNotNull(error);
                context.Assert.IsTrue(error.Message.ToLower().Contains("busy"));
                context.Assert.IsTrue(error.Message.ToLower().Contains("save"));
                context.Assert.Success();
            }
            context.Complete();
        }
Example #4
0
        public void TestDefaultValue()
        {
            IDataPortal <PropertyInfoRoot> dataPortal = _testDIContext.CreateDataPortal <PropertyInfoRoot>();

            Assert.AreEqual("x", PropertyInfoRoot.NameDefaultValueProperty.DefaultValue);
            Assert.AreEqual("x", PropertyInfoRoot.NewPropertyInfoRoot(dataPortal).NameDefaultValue);
        }
Example #5
0
        public void TestDpCreate()
        {
            IDataPortal <SplitOverload> dataPortal = _testDIContext.CreateDataPortal <SplitOverload>();

            SplitOverload test = SplitOverload.NewObject(dataPortal);

            Assert.AreEqual("Created", TestResults.GetResult("SplitOverload"));
        }
Example #6
0
        public void CommandBase_AssertDefaultValues()
        {
            IDataPortal <CommandObject> dataPortal = _testDIContext.CreateDataPortal <CommandObject>();
            var cmd = dataPortal.Create();

            Assert.AreEqual(string.Empty, cmd.Name);
            Assert.AreEqual(0, cmd.Num);
        }
Example #7
0
        public void IdentityInitializedBusinessBase()
        {
            IDataPortal <Foo> dataPortal = _testDIContext.CreateDataPortal <Foo>();

            var obj = dataPortal.Create();

            Assert.IsTrue(((IBusinessObject)obj).Identity >= 0);
        }
Example #8
0
        public void ShortCircuitOnNew()
        {
            IDataPortal <ShortCircuit> dataPortal = _testDIContext.CreateDataPortal <ShortCircuit>();

            ShortCircuit root = dataPortal.Create();

            root.CheckRules();
            Assert.AreEqual(1, root.BrokenRulesCollection.ErrorCount, "Only one rule should be broken");
            Assert.AreEqual("Test required", root.BrokenRulesCollection.GetFirstBrokenRule("Test").Description, "'Test required' should be broken");
        }
Example #9
0
        public void FetchNoCriteria()
        {
            IDataPortal <Root> dataPortal = _testDIContext.CreateDataPortal <Root>();

            var root = dataPortal.Fetch();

            Assert.AreEqual("Fetch", root.Data, "Data should match");
            Assert.IsFalse(root.IsNew, "Should not be new");
            Assert.IsFalse(root.IsDirty, "Should not be dirty");
        }
Example #10
0
        public void TestUnauthorizedAccessToGet()
        {
            IDataPortal <PermissionsRoot> dataPortal = _anonymousDIContext.CreateDataPortal <PermissionsRoot>();

            TestResults.Reinitialise();

            PermissionsRoot pr = dataPortal.Create();

            //this should throw an exception, since only admins have access to this property
            string something = pr.FirstName;
        }
Example #11
0
        public void Test_DataPortal_Array()
        {
            IDataPortal <ArrayDataPortalClass> dataPortal = _testDIContext.CreateDataPortal <ArrayDataPortalClass>();

            TestResults.Reinitialise();
            _ = ArrayDataPortalClass.Get(dataPortal, new int[] { 1, 2, 3 });
            Assert.AreEqual("Fetch(int[] values)", TestResults.GetResult("Method"));

            TestResults.Reinitialise();
            _ = ArrayDataPortalClass.Get(dataPortal, new string[] { "a", "b", "c" });
            Assert.AreEqual("Fetch(string[] values)", TestResults.GetResult("Method"));
        }
Example #12
0
        public void TestNullableProperty()
        {
            IDataPortal <NullableObject> dataPortal = _testDIContext.CreateDataPortal <NullableObject>();

            TestResults.Reinitialise();
            NullableObject nullRoot = NullableObject.NewNullableObject(dataPortal);

            nullRoot.NullableInteger = null;
            nullRoot.Name            = null;
            Assert.AreEqual(null, nullRoot.Name);
            Assert.AreEqual(null, nullRoot.NullableInteger);
        }
Example #13
0
        public async Task TestBusy()
        {
            IDataPortal <ItemWithAsynchRule> dataPortal = _noCloneOnUpdateDIContext.CreateDataPortal <ItemWithAsynchRule>();

            UnitTestContext context = GetContext();
            var             item    = await dataPortal.FetchAsync("an id");

            item.RuleField = "some value";
            context.Assert.IsTrue(item.IsBusy, "Should be busy");
            context.Assert.IsFalse(item.IsSavable, "Should not be savable");
            context.Assert.Success();
            context.Complete();
        }
Example #14
0
        public void AddItem()
        {
            IDataPortal <ERlist> dataPortal = _testDIContext.CreateDataPortal <ERlist>();

            ERlist list = dataPortal.Create();
            ERitem item = list.AddNew();

            Assert.AreEqual(1, list.Count, "Count should be 1");
            Assert.IsTrue(list[0].IsNew, "Object should be new");
        }
Example #15
0
        public void CheckInnerExceptionsOnSave()
        {
            IDataPortal <DataPortal.TransactionalRoot> dataPortal = _testDIContext.CreateDataPortal <DataPortal.TransactionalRoot>();

            TestResults.Reinitialise();

            DataPortal.TransactionalRoot root = DataPortal.TransactionalRoot.NewTransactionalRoot(dataPortal);
            root.FirstName   = "Billy";
            root.LastName    = "lastname";
            root.SmallColumn = "too long for the database"; //normally would be prevented through validation

            string baseException           = string.Empty;
            string baseInnerException      = string.Empty;
            string baseInnerInnerException = string.Empty;
            string exceptionSource         = string.Empty;

            try
            {
                root = root.Save();
            }
            catch (Csla.DataPortalException ex)
            {
                baseException           = ex.Message;
                baseInnerException      = ex.InnerException.Message;
                baseInnerInnerException = ex.InnerException.InnerException?.Message;
                exceptionSource         = ex.InnerException.InnerException?.Source;
                Assert.IsNull(ex.BusinessObject, "Business object shouldn't be returned");
            }

            //check base exception
            Assert.IsTrue(baseException.StartsWith("DataPortal.Update failed"), "Exception should start with 'DataPortal.Update failed'");
            Assert.IsTrue(baseException.Contains("String or binary data would be truncated."),
                          "Exception should contain 'String or binary data would be truncated.'");
            //check inner exception
            Assert.AreEqual("TransactionalRoot.DataPortal_Insert method call failed", baseInnerException);
            //check inner exception of inner exception
            Assert.AreEqual("String or binary data would be truncated.\r\nThe statement has been terminated.", baseInnerInnerException);

            //check what caused inner exception's inner exception (i.e. the root exception)
#if (NETFRAMEWORK)
            Assert.AreEqual(".Net SqlClient Data Provider", exceptionSource);
#else
            Assert.AreEqual("Core .Net SqlClient Data Provider", exceptionSource);
#endif

            //verify that the implemented method, DataPortal_OnDataPortal
            //was called for the business object that threw the exception
            Assert.AreEqual("Called", TestResults.GetResult("OnDataPortalException"));
        }
Example #16
0
        private SimpleBO Fetch()
        {
            IDataPortal <SimpleBO> dataPortal = _testDIContext.CreateDataPortal <SimpleBO>();

            var result = dataPortal.Fetch();

            void HookEvents(SimpleBO bo)
            {
                bo.PropertyChanged += Result_PropertyChanged;
                bo.ChildChanged    += Result_ChildChanged;

                if (bo.Child != null)
                {
                    bo.ChildList.ChildChanged += ChildList_ChildChanged;

                    HookEvents(bo.Child);
                    bo.ChildList.ToList().ForEach(c => HookEvents(c));
                }
            }

            HookEvents(result);

            _SequenceID = 0;
            EventDetails.Clear();

            return(result);
        }
Example #17
0
        public async Task CreateAndSaveChildAsync()
        {
            IChildDataPortal <Child> childDataPortal = _testDIContext.CreateChildDataPortal <Child>();
            IDataPortal <Root>       dataPortal      = _testDIContext.CreateDataPortal <Root>();

            Root root = await dataPortal.CreateAsync();

            await root.FetchChildAsync(childDataPortal);

            Assert.IsFalse(root.Child.IsDirty, "Child should not be dirty");
            Assert.AreEqual("Fetched", root.Child.Status, "Child status incorrect after fetch");

            root = await root.SaveAsync();

            Assert.AreEqual("Fetched", root.Child.Status, "Child status incorrect after Save");
        }
        public void TestLogicalExecutionLocation()
        {
            IDataPortal <LocationBusinessBase> dataPortal = _testDIContext.CreateDataPortal <LocationBusinessBase>();
            var applicationContext = _testDIContext.CreateTestApplicationContext();

            Assert.AreEqual(ApplicationContext.LogicalExecutionLocations.Client, applicationContext.LogicalExecutionLocation, "Should be client");

#pragma warning disable CS0436 // Type conflicts with imported type
            LocationBusinessBase item = LocationBusinessBase.GetLocationBusinessBase(dataPortal);
#pragma warning restore CS0436 // Type conflicts with imported type

            Assert.AreEqual(Csla.ApplicationContext.LogicalExecutionLocations.Server.ToString(), item.Data, "Should be server");
            Assert.AreEqual(Csla.ApplicationContext.LogicalExecutionLocations.Server.ToString(), item.NestedData, "Nested should be server");

            Assert.AreEqual(Csla.ApplicationContext.LogicalExecutionLocations.Client, applicationContext.LogicalExecutionLocation, "Should be client");
        }
Example #19
0
        public void TestBypassReadWriteWithRightsTurnNotificationBackOn()
        {
            TestDIContext testDIContext = TestDIContextFactory.CreateContext(GetPrincipal("Admin"));
            IDataPortal <BypassBusinessBase> dataPortal = testDIContext.CreateDataPortal <BypassBusinessBase>();

            UnitTestContext    context = GetContext();
            bool               propertyChangedFired = false;
            BypassBusinessBase testObj = dataPortal.Fetch();

            testObj.PropertyChanged += (o, e) =>
            {
                propertyChangedFired = true;
            };
            testObj.LoadIdByPass(1);
            context.Assert.AreEqual(1, testObj.ReadIdByPass());
            context.Assert.AreEqual(false, propertyChangedFired);
            context.Assert.AreEqual(false, testObj.IsDirty);

            testObj.LoadIdByNestedPass(3);
            context.Assert.AreEqual(3, testObj.ReadIdByPass());
            context.Assert.AreEqual(false, propertyChangedFired);
            context.Assert.AreEqual(false, testObj.IsDirty);

            testObj.LoadId(2);
            context.Assert.AreEqual(true, propertyChangedFired);
            context.Assert.AreEqual(2, testObj.ReadId());
            context.Assert.AreEqual(true, testObj.IsDirty);

            context.Assert.Success();
            context.Complete();
        }
Example #20
0
        public void UpdateTransactionScopeUsingDefaultTransactionLevelAndTimeout()
        {
            TestDIContext testDIContext = TestDIContextFactory.CreateContext(
                options => options
                .Data(
                    cfg => cfg
                    .DefaultTransactionIsolationLevel(TransactionIsolationLevel.RepeatableRead)
                    .DefaultTransactionTimeoutInSeconds(45)
                    )
                .DataPortal(
                    dp => dp.AddServerSideDataPortal(cfg => cfg.RegisterObjectFactoryLoader <ObjectFactoryLoader <RootFactory5> >()))
                );
            IDataPortal <Root> dataPortal = testDIContext.CreateDataPortal <Root>();

            var root = dataPortal.Create();

            root.Data = "abc";


            root = dataPortal.Update(root);
            Assert.AreEqual(TransactionalTypes.TransactionScope, root.TransactionalType, "Transactional type should match");
            Assert.AreEqual("RepeatableRead", root.IsolationLevel, "Transactional isolation should match");
            Assert.AreEqual(45, root.TransactionTimeout, "Transactional timeout should match");

            Assert.AreEqual("Update", root.Data, "Data should match");
            Assert.IsFalse(root.IsNew, "Should not be new");
            Assert.IsFalse(root.IsDirty, "Should not be dirty");
        }
Example #21
0
        public async Task CleanupWhenAddBusinessRulesThrowsException()
        {
            IDataPortal <RootThrowsException> dataPortal = _testDIContext.CreateDataPortal <RootThrowsException>();

            RootThrowsException.Counter = 0;

            // AddBusinessRules throw an ArgumentException
            // In .NET the exception will occur serverside and returned i DatPortalEventArgs
            try
            {
                await dataPortal.CreateAsync();
            }
            catch (DataPortalException ex)
            {
                Assert.IsTrue(ex.InnerException is ArgumentException);
            }

            // should fail again as type rules should be cleaned up
            // AddBusinessRules throw an ArgumentException
            try
            {
                await dataPortal.CreateAsync();
            }
            catch (DataPortalException ex)
            {
                Assert.IsTrue(ex.InnerException is ArgumentException);
            }
        }
        public void InvalidGetValidationRulesOnProperties()
        {
            IDataPortal <EditableGetSetRuleValidation> dataPortal = _testDIContext.CreateDataPortal <EditableGetSetRuleValidation>();

            EditableGetSetRuleValidation egsv = EditableGetSetRuleValidation.NewEditableGetSetValidation(dataPortal);

            try
            {
                // get the required property and verify that it has the value that it was set to.
                var result = egsv.MemberBackedIdWithNoRelationshipTypes;
                Assert.Fail("This property has a backing feild and an exception should of been thrown.");
            }
            catch (Exception ex)
            {
                Assert.IsTrue(true, ex.Message);
            }
        }
Example #23
0
        public async Task SingleAttribute()
        {
            var context = GetContext();

            var dp   = _testDIContext.CreateDataPortal <Single>();
            var root = await dp.CreateAsync();

            var rules = root.GetRules();

            Assert.AreEqual(1, rules.Length, "Should be 1 rule");
            Assert.IsFalse(root.IsValid, "Obj shouldn't be valid");
            Assert.AreEqual(1, root.BrokenRulesCollection.Count, "Should be 1 broken rule");
            Assert.AreEqual("Name value required", root.BrokenRulesCollection[0].Description, "Desc should match");
            context.Assert.Success();

            context.Complete();
        }
Example #24
0
        public void TestCommandBase()
        {
            TestResults.Reinitialise();

            IDataPortal <CommandObject> dataPortal = _testDIContext.CreateDataPortal <CommandObject>();
            CommandObject obj = dataPortal.Create();

            obj = dataPortal.Execute(obj);
            Assert.AreEqual("Executed", obj.AProperty);
        }
Example #25
0
        public void TestAsyncRulesValid()
        {
            IDataPortal <HasAsyncRule> dataPortal = _testDIContext.CreateDataPortal <HasAsyncRule>();

            UnitTestContext context = GetContext();

            HasAsyncRule har = dataPortal.Create();

            context.Assert.IsTrue(har.IsValid, "IsValid 1");

            har.ValidationComplete += (o, e) =>
            {
                context.Assert.IsTrue(har.IsValid, "IsValid 2");
                context.Assert.Success();
            };
            har.Name = "success";
            context.Complete();
        }
Example #26
0
        public void SetLast()
        {
            IDataPortal <TestCollection> dataPortal      = _testDIContext.CreateDataPortal <TestCollection>();
            IDataPortal <TestItem>       childDataPortal = _testDIContext.CreateDataPortal <TestItem>();
            TestCollection list = dataPortal.Create();

            list.Add(childDataPortal.Create());
            list.Add(childDataPortal.Create());
            TestItem oldItem = childDataPortal.Create();

            list.Add(oldItem);
            TestItem newItem = childDataPortal.Create();

            list[2] = newItem;
            Assert.AreEqual(3, list.Count, "List should have 3 items");
            Assert.AreEqual(newItem, list[2], "Last item should be newItem");
            Assert.AreEqual(true, list.ContainsDeleted(oldItem), "Deleted list should have old item");
        }
Example #27
0
        public void DenyWritePerType()
        {
            TestDIContext testDIContext = TestDIContextFactory.CreateContext(new System.Security.Claims.ClaimsPrincipal());
            IDataPortal <PerTypeAuthorization> dataPortal = testDIContext.CreateDataPortal <PerTypeAuthorization>();

            PerTypeAuthorization root = dataPortal.Create();

            root.Test = "test";
        }
Example #28
0
        public void TestAuthorizationRulesAfterSerialization()
        {
            TestDIContext adminDIContext = TestDIContextFactory.CreateContext(GetPrincipal("Admin"));
            IDataPortal <Security.PermissionsRoot> dataPortal = _testDIContext.CreateDataPortal <Security.PermissionsRoot>();

            Security.PermissionsRoot root = dataPortal.Create();

            try
            {
                root.FirstName = "something";
                Assert.Fail("Exception didn't occur");
            }
            catch (Csla.Security.SecurityException ex)
            {
                Assert.AreEqual("Property set not allowed", ex.Message);
            }

            dataPortal = adminDIContext.CreateDataPortal <Security.PermissionsRoot>();
            root       = dataPortal.Create();

            try
            {
                root.FirstName = "something";
            }
            catch (Csla.Security.SecurityException)
            {
                Assert.Fail("exception occurred");
            }

            // TODO: Not sure how to recreate this test now; can't change context under the data portal mid flight
            //Csla.ApplicationContext.User = new ClaimsPrincipal();

            Csla.Test.Security.PermissionsRoot rootClone = root.Clone();

            try
            {
                rootClone.FirstName = "something else";
                Assert.Fail("Exception didn't occur");
            }
            catch (Csla.Security.SecurityException ex)
            {
                Assert.AreEqual("Property set not allowed", ex.Message);
            }

            // TODO: Not sure how to recreate this test now; can't change context under the data portal mid flight
            //Csla.ApplicationContext.User = GetPrincipal("Admin");

            try
            {
                rootClone.FirstName = "something new";
            }
            catch (Csla.Security.SecurityException)
            {
                Assert.Fail("exception occurred");
            }
        }
Example #29
0
        public void ExecuteCommandWithIntercept()
        {
            IDataPortal <InterceptorCommand> dataPortal = _testDIContext.CreateDataPortal <InterceptorCommand>();

            TestResults.Reinitialise();

            var obj = dataPortal.Create();

            TestResults.Reinitialise();
            obj = dataPortal.Execute(obj);

            Assert.AreEqual("Execute", TestResults.GetResult("InterceptorCommand"), "Execute should have run");
            Assert.AreEqual("Initialize", TestResults.GetResult("Intercept1+InterceptorCommand"), "Initialize should have run");
            Assert.AreEqual("Execute", TestResults.GetResult("InterceptOp1+InterceptorCommand"), "Initialize op should be Execute");
            Assert.AreEqual("Complete", TestResults.GetResult("Intercept2+InterceptorCommand"), "Complete should have run");
            Assert.AreEqual("Execute", TestResults.GetResult("InterceptOp2+InterceptorCommand"), "Complete op should be Execute");
            Assert.IsFalse(TestResults.ContainsResult("Activate1+InterceptorCommand"), "CreateInstance should not have run");
            Assert.AreEqual("InitializeInstance", TestResults.GetResult("Activate2+InterceptorCommand"), "InitializeInstance should have run");
        }
Example #30
0
        public void Blb2Loc_WhereOnly()
        {
            IDataPortal <TestList> dataPortal = _testDIContext.CreateDataPortal <TestList>();

            var source = dataPortal.Create();
            var synced = source.ToSyncList(c => c.Id > 100);

            Assert.AreEqual(3, synced.Count);
        }