Esempio n. 1
0
        private HttpSessionState GetSession()
        {
            Fail.IfFalse(this.IsAvailable(), Violation.Of("HttpContext.Current.Session is not available"));

            return(this.GetContext()
                   .Session);
        }
Esempio n. 2
0
        private User GetUserBy(string userId)
        {
            var user = this.FindUserBy(userId);

            Fail.IfNull(user, Violation.Of("There is no user with id '{0}'", userId));
            return(user !);
        }
        /// <inheritdoc />
        public void Start(Library rootLibrary)
        {
            Fail.IfArgumentNull(rootLibrary, nameof(rootLibrary));
            Fail.IfNotNull(this.container, Violation.Of($"{nameof(WindsorEngine)} already started"));

            var librarian = new Librarian(rootLibrary);

            Library[] allLibraries = librarian.GetLibraries();
            var       extensions   = allLibraries.SelectMany(library => library.GetWindsorEngineExtensions()).ToArray();

            this.container = new WindsorContainer();

            this.container.Kernel.Resolver.AddSubResolver(new ComponentCollectionResolver(this.container.Kernel));

            this.container.Register(Component.For <IWindsorContainer>()
                                    .Instance(this.container));
            this.container.Register(Component.For <IWindsorEngine>()
                                    .Instance(this));
            this.container.Register(Component.For <ILibrarian>()
                                    .Instance(librarian));

            foreach (Library library in allLibraries)
            {
                this.RegisterComponentsFrom(library, extensions);
            }
        }
        public void IfCollectionContainsSuccess([NotNull] Tuple <IEnumerable <object>, object> pair)
        {
            var collection = pair.Item1;
            var element    = pair.Item2;

            Fail.IfCollectionContains(collection, e => object.Equals(e, element), Violation.Of("this collection contains '{0}'", element));
        }
Esempio n. 5
0
        /// <inheritdoc />
        public IDatabase Get(Type databaseType)
        {
            Fail.IfArgumentNull(databaseType, nameof(databaseType));
            Fail.IfFalse(typeof(IDatabase).IsAssignableFrom(databaseType), Violation.Of("{0} is not " + nameof(IDatabase), databaseType));

            return(this.databases.SingleOrDefault(db => databaseType.IsInstanceOfType(db)));
        }
        public int StartTransactionBecauseThereIsAttributeOnInterface()
        {
            Fail.IfFalse(this.myDatabase.CurrentSession.Transaction.IsActive, Violation.Of("Transaction not started"));

            return(this.myRepository.GetAll()
                   .Length);
        }
Esempio n. 7
0
        public static JToken?ReadJson([CanBeNull] this HttpContent?content)
        {
            if (content == null)
            {
                return(null);
            }

            Task <string> task = content.ReadAsStringAsync();

            task?.Wait();
            var str = task?.Result;

            if (string.IsNullOrWhiteSpace(str))
            {
                return(null);
            }

            var contentType = content.Headers.ContentType.MediaType;

            if (contentType != MediaTypeNames.Application.Json && contentType != "application/problem+json")
            {
                throw Fail.Because(Violation.Of("Content-Type is not JSON. It is \"{0}\"", contentType));
            }

            return(JToken.Parse(str));
        }
            internal Weak([NotNull] Type type)
            {
                Fail.IfArgumentNull(type, nameof(type));
                Fail.IfFalse(type.IsEnum, Violation.Of("Type '{0}' is not an enum", type));

                this.type = type;
            }
        public int GetMyEntitiesCount()
        {
            Fail.IfFalse(this.myDatabase.CurrentSession.Transaction.IsActive, Violation.Of("Transaction not started"));

            return(this.myRepository.GetAll()
                   .Length);
        }
        public List <Contractor> GetContractorsAged(DateTime minDate, DateTime?maxDate)
        {
            Fail.IfNotDate(minDate, Violation.Of("minDate must be a midnight"));
            Fail.IfNotDate(maxDate, Violation.Of("maxDate must be a midnight"));

            // WARN: Below is sample code with no sense at all
            return(new List <Contractor>(0));
        }
        public void IfEmptyWithMessageSuccess()
        {
            // ARRANGE
            Guid notEmptyGuid = Guid.NewGuid();

            // ACT
            Fail.IfEmpty(notEmptyGuid, Violation.Of("guid is empty and it shouldn't be"));
        }
Esempio n. 12
0
        public void IfFalseSuccess()
        {
            // ARRANGE
            var someTrueValue = true;

            // ACT
            Fail.IfFalse(someTrueValue, Violation.Of("this should be true"));
        }
Esempio n. 13
0
        protected ThreadStaticContextScope()
        {
            // WARN: nested scopes are not supported as it it to erroneous
            Fail.IfNotNull(ThreadStaticContextScope <T> .Sack,
                           Violation.Of(nameof(ThreadStaticContextScope <T>) + " was not cleared properly - are you trying to nest the scope? It is forbidden."));

            ThreadStaticContextScope <T> .Sack = new SackOf <T>();
        }
Esempio n. 14
0
        public void IfTrueSuccess()
        {
            // ARRANGE
            var someFalseValue = false;

            // ACT
            Fail.IfTrue(someFalseValue, Violation.Of("this should be false"));
        }
        public void OrFailIfEmptyWithMessage([CanBeNull] IEnumerable collection)
        {
            var exception = Assert.Throws <DesignByContractViolationException>(
                () => collection.OrFailIfCollectionEmpty(Violation.Of("collection cannot be null or empty"))
                );

            // ASSERT
            Assert.That(exception.Message, Is.EqualTo("collection cannot be null or empty"));
        }
Esempio n. 16
0
        public void IfEqualWithMessage(Pair obj)
        {
            // ACT
            var exception = Assert.Throws <DesignByContractViolationException>(
                () => Fail.IfEqual(obj.Value1, obj.Value2, Violation.Of("{0} is equal to {1} and shouldn't {2}. {3}", "first", "second", "be", "Seriously?"))
                );

            // ASSERT
            Assert.That(exception.Message, Is.EqualTo("first is equal to second and shouldn't be. Seriously?"));
        }
        public void IfEmptyWithMessage()
        {
            // ACT
            var exception = Assert.Throws <DesignByContractViolationException>(
                () => Fail.IfEmpty(Guid.Empty, Violation.Of("guid is empty and it shouldn't be"))
                );

            // ASSERT
            Assert.That(exception.Message, Is.EqualTo("guid is empty and it shouldn't be"));
        }
Esempio n. 18
0
        public void WeaklyTypedIfNotCastable()
        {
            // ACT
            var exception = Assert.Throws <DesignByContractViolationException>(
                () => Fail.IfNotCastable(new object(), typeof(IQueryable), Violation.Of("wrong type"))
                );

            // ASSERT
            Assert.That(exception.Message, Is.EqualTo("wrong type"));
        }
        public void IfNotMidnightWithMessage(DateTime dateTime)
        {
            // ACT
            var exception = Assert.Throws <DesignByContractViolationException>(
                () => Fail.IfNotDate(dateTime, Violation.Of("date should have no hour nor second"))
                );

            // ASSERT
            Assert.That(exception.Message, Is.EqualTo("date should have no hour nor second"));
        }
Esempio n. 20
0
        public void IfNotEqualWithMessage(Pair obj)
        {
            // ACT
            var exception = Assert.Throws <DesignByContractViolationException>(
                () => Fail.IfNotEqual(obj.Value1, obj.Value2, Violation.Of("values differ and should be equal"))
                );

            // ASSERT
            Assert.That(exception.Message, Is.EqualTo("values differ and should be equal"));
        }
            public FieldInfo GetFieldInfo([NotNull] Enum @enum)
            {
                Fail.IfArgumentNull(@enum, nameof(@enum));

                string name = Enum.GetName(this.type, @enum);

                Fail.IfNull(name, Violation.Of("Enum value {0} not found in enum {1}", @enum, this.type));
                FieldInfo field = this.type.GetField(name);

                return(field.OrFail(nameof(field)));
            }
Esempio n. 22
0
        public void FailIfNullWithViolationMessage(object someNullObject)
        {
            // ACT
            var exception = Assert.Throws <DesignByContractViolationException>(
                // ReSharper disable once ExpressionIsAlwaysNull
                () => someNullObject.FailIfNull(Violation.Of("this is null: {0}", nameof(someNullObject)))
                );

            // ASSERT
            Assert.That(exception.Message, Is.EqualTo("this is null: someNullObject"));
        }
Esempio n. 23
0
        public void IfNullWithMessage(object thisIsNull)
        {
            // ACT
            var exception = Assert.Throws <DesignByContractViolationException>(
                // ReSharper disable once ExpressionIsAlwaysNull
                // ReSharper disable once HeapView.BoxingAllocation
                () => Fail.IfNull(thisIsNull, Violation.Of("this is null and it shouldn't be {0} {1} {2} {3}", 1, "never", "maybe", "wow"))
                );

            // ASSERT
            Assert.That(exception.Message, Is.EqualTo("this is null and it shouldn't be 1 never maybe wow"));
        }
Esempio n. 24
0
        /// <inheritdoc />
        public void Apply([NotNull] IPropertyInstance instance)
        {
            Fail.IfArgumentNull(instance, nameof(instance));

            if (instance.Type.GetUnderlyingSystemType() != typeof(string))
            {
                return;
            }

            int length = ((IPropertyInspector)instance).Length;

            Fail.IfEqual(0, length, Violation.Of("{0}.{1} length is 0", instance.EntityType.Name, instance.Name));
        }
Esempio n. 25
0
        public static T Read <T>([NotNull] this HttpContent?content, string jsonPath)
        {
            Fail.IfNull(content, nameof(content));
            JToken?json = content.ReadJson();
            var    node = json !.SelectToken(jsonPath).FailIfNull(Violation.Of($"Cannot find JSON node '{jsonPath}'"));

            if (node is JObject)
            {
                return(node.ToObject <T>());
            }

            return(node.Value <T>());
        }
Esempio n. 26
0
        public void IfNotCastable()
        {
            // ARRANGE
            var somethingNotCastable = new object();

            // ACT
            var exception = Assert.Throws <DesignByContractViolationException>(
                () => Fail.IfNotCastable <IQueryable>(somethingNotCastable, Violation.Of("wrong type"))
                );

            // ASSERT
            Assert.That(exception.Message, Is.EqualTo("wrong type"));
        }
        public List <Contractor> FilterContractors(ContractorFilterParameters paramaters)
        {
            paramaters.OrFail(nameof(paramaters));
            paramaters.EstablishedBetween.FailIfNull(Violation.Of("'{0}' is null and it shouldn't be", nameof(paramaters.EstablishedBetween)));
            paramaters.EstablishedBetween.Max.OrFail(nameof(paramaters.EstablishedBetween.Max));

            if (paramaters.EstablishedBetween == null)
            {
            }

            // WARN: Below is sample code with no sense at all
            return(new List <Contractor>(0));
        }
Esempio n. 28
0
        public void IfTrueWithMessage()
        {
            // ARRANGE
            var someTrueValue = true;

            // ACT
            var exception = Assert.Throws <DesignByContractViolationException>(
                // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                () => Fail.IfTrue(someTrueValue, Violation.Of("this should be false {0}", 1))
                );

            // ASSERT
            Assert.That(exception.Message, Is.EqualTo("this should be false 1"));
        }
Esempio n. 29
0
        private void FailIfTransactionStartedDespiteDisablingIt(TransactionsContainer transactionsContainer, [NotNull] ConnectToAttribute[] disabledTransactions)
        {
            Fail.IfArgumentNull(disabledTransactions, nameof(disabledTransactions));

            foreach (ConnectToAttribute disabledTransaction in disabledTransactions)
            {
                IDatabase database = this.GetDatabaseForAutoTransaction(disabledTransaction);
                ISession  session  = transactionsContainer.StartSession(database);
                Fail.IfTrue(
                    session.Transaction.IsActive,
                    Violation.Of("Transaction is started to database {0} and it shouldn't be due to attribute {1}",
                                 database,
                                 disabledTransaction)
                    );
            }
        }
Esempio n. 30
0
        private IDatabase GetDatabaseForAutoTransaction([NotNull] ConnectToAttribute transactionalAttribute)
        {
            Fail.IfArgumentNull(transactionalAttribute, nameof(transactionalAttribute));

            Type databaseType = transactionalAttribute.Database;

            Fail.IfNull(databaseType, Violation.Of("There is no database pointed in {0}", transactionalAttribute));

            IDatabase database = this.databaseProvider.Get(databaseType);

            Fail.IfNull(database,
                        Violation.Of("Could not find database used in {0}. Did you point {1} in the '{2}' argument?",
                                     transactionalAttribute,
                                     nameof(IDatabase),
                                     nameof(ConnectToAttribute.Database))
                        );

            return(database);
        }