Esempio n. 1
0
        public Bridge(Event.IMediator eventMediator, With.Messaging.Client.IEndpoint clientEndpoint)
        {
            _eventMediator = eventMediator;
            _clientEndpoint = clientEndpoint;

            _messages = new Subject<Message.IMessage>();
        }
Esempio n. 2
0
        public Harmonizer(With.Messaging.Service.IEndpoint serviceEndpoint)
        {
            _serviceEndpoint = serviceEndpoint;
            _messages = new Subject<With.Message.IMessage>();

            _messageObservable = _messages.Publish();
        }
Esempio n. 3
0
            public void Updates()
            {
                var source = new With<BaseClass>();
                var target = new With<BaseClass>();
                using (Synchronize.PropertyValues(source, target, ReferenceHandling.Structural))
                {
                    source.Value = new Derived1 { BaseValue = 1, Derived1Value = 2 };
                    Assert.AreEqual(null, source.Name);
                    Assert.AreEqual(null, target.Name);
                    Assert.IsInstanceOf<Derived1>(source.Value);
                    Assert.IsInstanceOf<Derived1>(target.Value);
                    Assert.AreEqual(1, source.Value.BaseValue);
                    Assert.AreEqual(1, target.Value.BaseValue);

                    Assert.AreEqual(2, ((Derived1)source.Value).Derived1Value);
                    Assert.AreEqual(2, ((Derived1)target.Value).Derived1Value);

                    source.Value = new Derived2 {BaseValue = 1, Derived2Value = 2};
                    Assert.AreEqual(null, source.Name);
                    Assert.AreEqual(null, target.Name);
                    Assert.IsInstanceOf<Derived2>(source.Value);
                    Assert.IsInstanceOf<Derived2>(target.Value);
                    Assert.AreEqual(1, source.Value.BaseValue);
                    Assert.AreEqual(1, target.Value.BaseValue);

                    Assert.AreEqual(2, ((Derived2)source.Value).Derived2Value);
                    Assert.AreEqual(2, ((Derived2)target.Value).Derived2Value);
                }
            }
Esempio n. 4
0
 public Service(WifiLink.IBridge bridge, Entity.IFactory entityFactory, Configuration.IProvider configurationProvider, With.Messaging.Client.IEndpoint clientEndpoint)
 {
     _entityFactory = entityFactory;
     _clientEndpoint = clientEndpoint;
     _configurationProvider = configurationProvider;
     _bridge = bridge;
 }
Esempio n. 5
0
        public HarmonizeConnector(Registration.IFactory registrationFactory, With.Messaging.Client.IEndpoint messagingEndpoint)
        {
            _registrationFactory = registrationFactory;
            _messagingEndpoint = messagingEndpoint;

            _registrations = new Registration.Collection();
        }
Esempio n. 6
0
        internal static void Publish(string exchangeName, string routingKey, With.Message.ISerializer messageSerializer, RabbitMQ.Client.IModel model, With.Message.IMessage message)
        {
            string content = messageSerializer.Serialize(message);
            byte[] body = Encoding.Encode(content);
            IBasicProperties properties = model.CreateBasicProperties();

            model.BasicPublish(exchangeName, routingKey, properties, body);
        }
Esempio n. 7
0
        public Bootstrapper(IKernel kernel, With.Messaging.Client.IEndpoint clientEndpoint)
        {
            _clientEndpoint = clientEndpoint;

            _configurationProvider = new Configuration.Provider();
            _gatewayFactory = new Gateway.Factory(kernel);

            _connector = new Connector(_clientEndpoint, _configurationProvider.GetSettings(), _gatewayFactory);
        }
Esempio n. 8
0
        public async Task Register(With.Component.IIdentity client, With.Component.IEntity entity, IObserver<Message.IMessage> consumer)
        {
            Registration.IInstance registration = _registrationFactory.For(client, entity, consumer);

            _registrations.Add(registration);

            await _hub.Register(registration.Client, registration.Entity);

            System.Diagnostics.Debug.WriteLine(string.Format("Client Registered '{0}'", registration.Key));
        }
Esempio n. 9
0
        public Instance(With.Component.IIdentity registrar, With.Component.IEntity entity, Action<With.Message.IMessage> processor)
        {
            Registrar = registrar;
            Entity = entity;

            Key = Registration.Key.For(registrar, entity.Identity);

            _consumer = new Subject<With.Message.IMessage>();
            _subscription = _consumer.Subscribe(processor);
        }
Esempio n. 10
0
        public EventData Translate(With.Message.IRegister message)
        {
            Registered value = _mapper.Map(message);

            string text = _serializer.Serialize(value);

            byte[] data = _encoder.Encode(text);

            return new EventData(Guid.NewGuid(), typeof(Registered).FullName, true, data, new byte[0]);
        }
 public void DirtyWhenDifferentTypes()
 {
     var x = new With<BaseClass>();
     var y = new With<BaseClass>();
     using (var tracker = Track.IsDirty(x, y))
     {
         x.Value = new Derived2();
         y.Value = new Derived1();
         Assert.AreEqual(true, tracker.IsDirty);
     }
 }
 public void NotDirtyWhenSameType()
 {
     var x = new With<BaseClass>();
     var y = new With<BaseClass>();
     using (var tracker = Track.IsDirty(x, y))
     {
         x.Value = new Derived2();
         y.Value = new Derived2();
         Assert.AreEqual(false, tracker.IsDirty);
     }
 }
            public void DoesNotLeakTrackedProperty()
            {
                var source = new With<ComplexType> { Value = new ComplexType() };
                using (Track.Changes(source, ReferenceHandling.Structural))
                {
                    var weakReference = new WeakReference(source.Value);
                    source.Value = null;
                    GC.Collect();
                    Assert.IsFalse(weakReference.IsAlive);
                }

                Assert.NotNull(source); // touching it here so it is not optimized away.
            }
Esempio n. 14
0
        public ILightwaveEntity Build(Configuration.IDevice device, WifiLink.IBridge bridge, With.Messaging.Client.IEndpoint clientEndpoint)
        {
            Configuration.Dimmer dimmer = device as Configuration.Dimmer;

            if (dimmer != null)
            {
                return new Entity(dimmer, bridge, clientEndpoint);
            }
            else
            {
                throw new InvalidOperationException(string.Format("Could not create dimmer from device '{0}'", device));
            }
        }
Esempio n. 15
0
        public ILightwaveEntity Create(Configuration.IDevice device, WifiLink.IBridge bridge, With.Messaging.Client.IEndpoint clientEndpoint)
        {
            IBuilder builder;

            if (_builders.TryGetValue(device.Type, out builder))
            {
                return builder.Build(device, bridge, clientEndpoint);
            }
            else
            {
                throw new InvalidOperationException(string.Format("No builder for device type '{0}' found", device.Type));
            }
        }
            public void ReplaceCollection()
            {
                var source = new With<ObservableCollection<ComplexType>> { Value = new ObservableCollection<ComplexType>() };
                var propertyChanges = new List<string>();
                var changes = new List<EventArgs>();
                var expectedChanges = new List<EventArgs>();
                using (var tracker = Track.Changes(source, ReferenceHandling.Structural))
                {
                    var sourceNode = ChangeTrackerNode.GetOrCreate(source, tracker.Settings, false)
                                                      .Value;
                    tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName);
                    tracker.Changed += (_, e) => changes.Add(e);
                    Assert.AreEqual(0, tracker.Changes);
                    CollectionAssert.IsEmpty(propertyChanges);
                    CollectionAssert.IsEmpty(changes);

                    var observableCollection = source.Value;
                    source.Value = new ObservableCollection<ComplexType> { new ComplexType() };
                    Assert.AreEqual(1, tracker.Changes);
                    CollectionAssert.AreEqual(new[] { "Changes" }, propertyChanges);
                    expectedChanges.Add(RootChangeEventArgs.Create(sourceNode, new PropertyChangeEventArgs(source, source.GetProperty("Value"))));
                    CollectionAssert.AreEqual(expectedChanges, changes, EventArgsComparer.Default);

                    source.Value[0].Value++;
                    Assert.AreEqual(2, tracker.Changes);
                    CollectionAssert.AreEqual(new[] { "Changes", "Changes" }, propertyChanges);
                    expectedChanges.Add(
                        new PropertyGraphChangedEventArgs<ChangeTrackerNode>(
                            sourceNode,
                            source.GetProperty("Value"),
                            new ItemGraphChangedEventArgs<ChangeTrackerNode>(
                                ChangeTrackerNode.GetOrCreate(
                                    (INotifyCollectionChanged)source.Value,
                                    tracker.Settings,
                                    false)
                                                 .Value,
                                0,
                                RootChangeEventArgs.Create(
                                    ChangeTrackerNode.GetOrCreate(source.Value[0], tracker.Settings, false)
                                                     .Value,
                                    new PropertyChangeEventArgs(source.Value[0], source.Value[0].GetProperty("Value"))))));
                    CollectionAssert.AreEqual(expectedChanges, changes, EventArgsComparer.Default);

                    observableCollection.Add(new ComplexType());
                    Assert.AreEqual(2, tracker.Changes);
                    CollectionAssert.AreEqual(new[] { "Changes", "Changes" }, propertyChanges);
                    CollectionAssert.AreEqual(expectedChanges, changes, EventArgsComparer.Default);
                }
            }
            public void CreateAndDisposeWithComplexType()
            {
                var source = new With<ComplexType> { Value = new ComplexType(1, 2) };

                using (Track.Changes(source, ReferenceHandling.Structural))
                {
                }

                var wrx = new System.WeakReference(source);
                var wrxc = new System.WeakReference(source.Value);
                source = null;
                System.GC.Collect();
                Assert.AreEqual(false, wrx.IsAlive);
                Assert.AreEqual(false, wrxc.IsAlive);
            }
Esempio n. 18
0
 public void BetweenParentOffsetBondries()
 {
     With.Mocks(_mockRepository).Expecting(delegate
     {
         _parentAsfObject.Stub(x => x.IsRoot).Return(false);
         _parentAsfObject.Stub(x => x.Offset).Return(0L);
         _parentAsfObject.Stub(x => x.RelativeEndOffset).Return(200L);
         _asfObject.Stub(x => x.Offset).Return(10L);
         _asfObject.Stub(x => x.RelativeEndOffset).Return(100L);
         _asfObject.Stub(x => x.HeaderName).Return(AsfObjectName.HeaderObject);
         _asfObject.Stub(x => x.IsUnknown).Return(false);
     }).Verify(delegate
     {
         Assert.IsTrue(_asfObject.IsSuitableParent(_parentAsfObject));
     });
 }
 public void WriteCancelledBetweenReads()
 {
     With.Mocks(_mockRepository).Expecting(delegate
     {
         bool read = false;
         _dataReader.Stub(x => x.Position).PropertyBehavior();
         _dataReader.Stub(x => x.Length).Return(DataReaderLength1);
         _dataReader.Stub(x => x.State).Return(DataReaderState.Ready)
         .WhenCalled(i => i.ReturnValue = read ? DataReaderState.Cancelled : DataReaderState.Ready);
         _dataReader.Expect(x => x.Read(Arg <byte[]> .Is.NotNull, Arg <int> .Is.Anything, Arg <int> .Is.Anything)).Return(1)
         .WhenCalled(i => read = true);
     }).Verify(delegate
     {
         _dataWriter.Write(_dataReader);
     });
 }
Esempio n. 20
0
        public void WillReturnDebugLogEntryMessagesAndAbove()
        {
            ILog log = LogManager.GetLogger("SomeLog");

            string         debugMessage = "Some debug message";
            string         fatalMessage = "Some fatal message";
            IList <string> logMessages  = With.Log(log.Logger.Name, delegate
            {
                log.Debug(debugMessage);
                log.Fatal(fatalMessage);
            });

            Assert.AreEqual(2, logMessages.Count);
            Assert.AreEqual(debugMessage, logMessages[0]);
            Assert.AreEqual(fatalMessage, logMessages[1]);
        }
Esempio n. 21
0
        public void UsingTheWithMocksExceptingVerifyConstruct_GiveCorrectExceptionWhenMocking()
        {
            MockRepository mocks = new MockRepository();
            IDemo          demo  = mocks.StrictMock <IDemo>();

            Assert.Throws <IndexOutOfRangeException>("foo", () =>
                                                     With.Mocks(mocks)
                                                     .Expecting(delegate
            {
                Expect.Call(demo.ReturnIntNoArgs()).Return(5);
            })
                                                     .Verify(delegate
            {
                throw new IndexOutOfRangeException("foo");
            }));
        }
Esempio n. 22
0
        public void GetSchemaCommand()
        {
            var mocks = new MockRepository();
            var conn  = mocks.StrictMock <ISolrConnection>();

            With.Mocks(mocks).Expecting(delegate
            {
                Expect.Call(conn.Get("/admin/file", new List <KeyValuePair <string, string> > {
                    new KeyValuePair <string, string>("file", "schema.xml")
                })).Repeat.Once().Return("");
            }).Verify(delegate
            {
                var cmd = new GetSchemaCommand();
                cmd.Execute(conn);
            });
        }
Esempio n. 23
0
        public void Override <T>(With what)
        {
            switch (what)
            {
            case With.Stub:
                Override(Mocks.Stub <T>());
                break;

            case With.StrictMock:
                Override(Mocks.StrictMock <T>());
                break;

            default:
                throw new Exception("Unknown With");
            }
        }
Esempio n. 24
0
        private Person Call(With options = With.StronglyTypedResult)
        {
            _arguments.id = 1;
            if (options == With.NoResult)
            {
                _client.Call(Verb.PUT, RelativeUri, new[] { "application/json" }, new[] { "application/json" }, _arguments, Person);
                return(null);
            }

            if (options == With.MultipartBody)
            {
                return(_client.Call <Person>(Verb.PUT, RelativeUri, new[] { "application/json" }, new[] { "application/json" }, _arguments, Person, Person));
            }

            return(_client.Call <Person>(Verb.PUT, RelativeUri, new[] { "application/json" }, new[] { "application/json" }, _arguments, Person));
        }
Esempio n. 25
0
        /// <summary>
        /// 관리되지 않는 리소스의 확보, 해제 또는 다시 설정과 관련된 응용 프로그램 정의 작업을 수행합니다.
        /// </summary>
        public void Dispose()
        {
            if (IsDisposed)
            {
                return;
            }

            With.TryAction(() => _doDisposeCommand());

            if (IsDebugEnabled)
            {
                log.Debug("AdoDataAdapter 인스턴스의 리소스를 해제했습니다.");
            }

            IsDisposed = true;
        }
        public void Create_sets_error_if_MaxSubscriptions_has_been_reached_test()
        {
            SubscriptionModel model  = new SubscriptionModel();
            ActionResult      actual = null;

            With.Mocks(_mocks).Expecting(delegate
            {
                _subscriptionPersistenceService.Expect(x => x.GetMaxSubscriptionsForUser(_controller.HubConfiguration.HubUsername)).Return(10);
                _subscriptionPersistenceService.Expect(x => x.GetSubscriptionCountForUser(_controller.HubConfiguration.HubUsername)).Return(10);
            }).Verify(delegate
            {
                actual = _controller.Create(model);
            });
            Assert.IsNotNull(actual);
            Assert.IsNotNull(_controller.ViewData["ErrorDescription"]);
        }
        public void SElementSearchWithCss()
        {
            // search using wrapped driver methods
            String      cssSelector = @"h1[name = ""greeting""]";
            IWebDriver  driver      = Selene.GetWebDriver();
            IWebElement element     = driver.FindElement(By.CssSelector(cssSelector));

            StringAssert.IsMatch("greeting", element.GetAttribute("name"));

            // search using NSelene methods
            Selene.S(With.Css(cssSelector), driver).Should(Be.InDom);
            Selene.S(With.Css(cssSelector)).Should(Have.Attribute("name", element.GetAttribute("name")));

            // compare old style and new style search results
            StringAssert.IsMatch(Selene.S(cssSelector).GetAttribute("outerHTML"), Selene.S(With.Css(cssSelector)).GetAttribute("outerHTML"));
        }
        public void WaitForValue_WhenWaitingForValueAndValueChangeAfter2Second_ShouldReturnTrue()
        {
            var uiObject = _testHelper.CreateUiObject(With.Class("testClass"), 0);

            _testHelper.UiServiceMock.Setup(u => u.FindNode(It.IsAny <int>(), It.IsAny <With[]>()))
            .Returns(new Node(new XElement("node", new XAttribute("clickable", "false")), null));

            Task.Run(() =>
            {
                Thread.Sleep(2000);
                _testHelper.UiServiceMock.Setup(u => u.FindNode(It.IsAny <int>(), It.IsAny <With[]>()))
                .Returns(new Node(new XElement("node", new XAttribute("clickable", "true")), null));
            });

            Assert.IsTrue(uiObject.WaitForValue(n => n.Clickable));
        }
Esempio n. 29
0
        public void PostLoginShouldReturnViewWithLockout()
        {
            var model = new LoginViewModel
            {
                Email    = SignInManagerMock.LockedOutUser,
                Password = SignInManagerMock.LockedOutUser
            };

            MyMvc
            .Controller <AccountController>()
            .Calling(c => c.Login(
                         model,
                         With.No <string>()))
            .ShouldReturn()
            .View("Lockout");
        }
Esempio n. 30
0
        public void DeleteByQuery()
        {
            const string q     = "id:123456";
            var          mocks = new MockRepository();
            var          conn  = mocks.StrictMock <ISolrConnection>();

            With.Mocks(mocks).Expecting(() => {
                if (conn != null)
                {
                    Expect.Call(conn.Post("/update", string.Format("<delete><query>{0}</query></delete>", q))).Return("");
                }
            }).Verify(() => {
                Solr.Connection = conn;
                Solr.Delete.ByQuery(new SolrQuery(q));
            });
        }
            public void DoesNotLeakTrackedProperty()
            {
                var source = new With <ComplexType> {
                    Value = new ComplexType()
                };

                using (Track.Changes(source, ReferenceHandling.Structural))
                {
                    var weakReference = new WeakReference(source.Value);
                    source.Value = null;
                    GC.Collect();
                    Assert.IsFalse(weakReference.IsAlive);
                }

                Assert.NotNull(source); // touching it here so it is not optimized away.
            }
Esempio n. 32
0
        public void QueryWithPagination()
        {
            var mocks = new MockRepository();
            var conn  = mocks.StrictMock <ISolrConnection>();

            With.Mocks(mocks)
            .Expecting(() => Expect.Call(conn.Get(null, null))
                       .IgnoreArguments()
                       .Repeat.Once()
                       .Return(response))
            .Verify(() => {
                Solr.Connection = conn;
                var r           = Solr.Query <TestDocument>("", 10, 20);
                Assert.AreEqual(1, r.NumFound);
            });
        }
Esempio n. 33
0
        public void UsingTheWithMocksExceptingVerifyConstruct_ThrowsIfExpectationIsMissed()
        {
            MockRepository mocks = new MockRepository();
            IDemo          demo  = mocks.StrictMock <IDemo>();

            Assert.Throws <ExpectationViolationException>("IDemo.ReturnIntNoArgs(); Expected #1, Actual #0.",
                                                          () =>
                                                          With.Mocks(mocks)
                                                          .Expecting(delegate
            {
                Expect.Call(demo.ReturnIntNoArgs()).Return(5);
            })
                                                          .Verify(delegate
            {
            }));
        }
Esempio n. 34
0
 public void PostLoginShouldReturnDefaultViewWithInvalidModel()
 {
     MyMvc
     .Controller <AccountController>()
     .Calling(c => c.Login(
                  With.Default <LoginViewModel>(),
                  With.No <string>()))
     .ShouldHave()
     .ModelState(modelState => modelState
                 .For <LoginViewModel>()
                 .ContainingErrorFor(m => m.Email)
                 .ContainingErrorFor(m => m.Password))
     .AndAlso()
     .ShouldReturn()
     .View();
 }
        /// <summary>
        /// <paramref name="spName"/>를 비동기 방식으로 실행하여, 결과 셋을 <see cref="Task{DataTable}"/>로 반환합니다.
        /// </summary>
        public static Task <DataTable> ExecuteDataTableAsyncByProcedure(this NpgsqlDatabase db,
                                                                        string spName,
                                                                        int firstResult,
                                                                        int maxResults,
                                                                        params IAdoParameter[] parameters)
        {
            var cmd = db.GetProcedureNpgsqlCommand(spName, AdoTool.DEFAULT_DISCOVER_PARAMETER);

            return
                (ExecuteDataTableAsync(db, cmd, firstResult, maxResults, parameters)
                 .ContinueWith(task => {
                With.TryAction(() => cmd.Dispose());
                return task.Result;
            },
                               TaskContinuationOptions.ExecuteSynchronously));
        }
Esempio n. 36
0
 public UiObjects CreateUiObjects(With with, int delayInMiliSec, bool shouldThrowExeception = false)
 {
     if (shouldThrowExeception)
     {
         UiServiceMock.Setup(u => u.FindNode(It.IsAny <int>(), with))
         .Callback(() => Thread.Sleep(delayInMiliSec))
         .Throws <UiNodeNotFoundException>();
     }
     else
     {
         UiServiceMock.Setup(u => u.FindNode(It.IsAny <int>(), with))
         .Callback(() => Thread.Sleep(delayInMiliSec))
         .Returns(new Node(new XElement("mm"), null));
     }
     return(_uiService.CreateUiObjects(with));
 }
Esempio n. 37
0
        public static void ReactsNested()
        {
            var changes    = new List <EventPattern <ItemPropertyChangedEventArgs <Fake, string?> > >();
            var collection = new ObservableCollection <Fake>
            {
                new Fake {
                    Next = new Level {
                        Name = "Johan"
                    }
                },
                new Fake {
                    Next = new Level {
                        Name = "Reed"
                    }
                },
            };
            var fake = new With <ObservableCollection <Fake> > {
                Value = collection
            };

            using (fake.ObservePropertyChangedWithValue(x => x.Value, signalInitial: true)
                   .ItemPropertyChanged(x => x.Next.Name)
                   .Subscribe(changes.Add))
            {
                Assert.AreEqual(2, changes.Count);
                EventPatternAssert.AreEqual(collection[0], collection, collection[0].Next, Maybe.Some <string?>("Johan"), string.Empty, changes[0]);
                EventPatternAssert.AreEqual(collection[1], collection, collection[1].Next, Maybe.Some <string?>("Reed"), string.Empty, changes[1]);

                fake.Value[0].Next !.Name = "Erik";
                Assert.AreEqual(3, changes.Count);
                EventPatternAssert.AreEqual(collection[0], collection[0].Next, collection[0].Next, Maybe.Some <string?>("Erik"), "Name", changes.Last());

                fake.Value.Add(fake.Value[0]);
                Assert.AreEqual(4, changes.Count);
                EventPatternAssert.AreEqual(collection[0], collection, collection[0].Next, Maybe.Some <string?>("Erik"), string.Empty, changes.Last());

                fake.Value[0].Next !.Name = "Max";
                Assert.AreEqual(5, changes.Count);
                EventPatternAssert.AreEqual(collection[0], collection[0].Next, collection[0].Next, Maybe.Some <string?>("Max"), "Name", changes.Last());

                fake.Value[1].Next !.Name = "Tom";
                Assert.AreEqual(6, changes.Count);
                EventPatternAssert.AreEqual(collection[1], collection[1].Next, collection[1].Next, Maybe.Some <string?>("Tom"), "Name", changes.Last());
            }

            Assert.AreEqual(6, changes.Count);
        }
Esempio n. 38
0
        /// <summary>
        /// <paramref name="reader"/>의 내용을 읽어, <see cref="DataTable"/> 로 빌드합니다. <b>다 읽은 DataReader는 닫아버립니다.</b>
        /// </summary>
        /// <param name="db">DAAB Database instance</param>
        /// <param name="reader">읽을 IDataReader</param>
        /// <param name="dataTableFactory">DataTable 생성용 델리게이트</param>
        /// <param name="firstResult">첫번째 인덱스 (0부터 시작)</param>
        /// <param name="maxResults">읽을 최대 레코드 수</param>
        /// <returns>DataReader의 내용으로 채워진 DataTable</returns>
        /// <seealso cref="AdoDataAdapter"/>
        public static DataTable BuildDataTableFromDataReader(this Database db, IDataReader reader,
                                                             Func <DataTable> dataTableFactory = null, int firstResult = 0,
                                                             int maxResults = 0)
        {
            if (IsDebugEnabled)
            {
                log.Debug("AdoDataAdapter를 이용하여, IDataReader 내용을 읽어, DataTable로 빌드합니다");
            }

            if (dataTableFactory == null)
            {
                dataTableFactory = () => new DataTable {
                    Locale = CultureInfo.InvariantCulture
                }
            }
            ;

            var dataTable = dataTableFactory();

            if (reader != null)
            {
                var adapter = new AdoDataAdapter(db.GetDataAdapter());
                try {
                    adapter.Fill(new[] { dataTable }, reader, firstResult, maxResults);
                }
                catch (Exception ex) {
                    if (log.IsErrorEnabled)
                    {
                        log.Error("DataReader로부터 DataTable로 Fill하는 동안 예외가 발생했습니다.");
                        log.Error(ex);
                    }
                    throw;
                }
                finally {
                    With.TryAction(reader.Dispose);
                    With.TryAction(adapter.Dispose);
                }

                if (IsDebugEnabled)
                {
                    log.Debug("DataReader를 읽어 DataTable에 Load 했습니다!!! firstResult=[{0}], maxResults=[{1}]", firstResult, maxResults);
                }
            }

            return(dataTable);
        }
    }
Esempio n. 39
0
        public void PostAddressAndPaymentShouldBeRoutedCorrectly()
        {
            var firstName  = "FirstNameTest";
            var lastName   = "LastNameTest";
            var address    = "AddressTest";
            var city       = "CityTest";
            var state      = "StateTest";
            var postalCode = "PostalTest";
            var country    = "CountryTest";
            var phone      = "PhoneTest";
            var email      = "*****@*****.**";

            MyMvc
            .Routing()
            .ShouldMap(request => request
                       .WithMethod(HttpMethod.Post)
                       .WithLocation("/Checkout/AddressAndPayment")
                       .WithFormFields(new
            {
                FirstName  = firstName,
                LastName   = lastName,
                Address    = address,
                City       = city,
                State      = state,
                PostalCode = postalCode,
                Country    = country,
                Phone      = phone,
                Email      = email
            }))
            .To <CheckoutController>(c => c.AddressAndPayment(
                                         With.Any <MusicStoreContext>(),
                                         new Order
            {
                FirstName  = firstName,
                LastName   = lastName,
                Address    = address,
                City       = city,
                State      = state,
                PostalCode = postalCode,
                Country    = country,
                Phone      = phone,
                Email      = email
            },
                                         With.Any <CancellationToken>()))
            .AndAlso()
            .ToValidModelState();
        }
        public void LoginException()
        {
            With.Mocks(
                delegate
            {
                IWebRequestHelper mockedRequestHelper;
                string success;
                using (Mocker.Current.Record())
                {
                    mockedRequestHelper = Mocker.Current.StrictMock <IWebRequestHelper>();
                    RhinoHelper.AddLoginExceptionExpectation(mockedRequestHelper, new ArgumentException("A generic exception"));
                }

                MainProgram testThread = new MainProgram(_config);
                Assert.Throws <ArgumentException>(() => testThread.LoginHttp(mockedRequestHelper));
            });
        }
        public void ServiceRequest()
        {
            With.Mocks(
                delegate
            {
                IWebServiceHelper mockedServiceHelper;
                using (Mocker.Current.Record())
                {
                    mockedServiceHelper = Mocker.Current.StrictMock <IWebServiceHelper>();
                    RhinoHelper.AddServiceRequestExpectation(mockedServiceHelper);
                }

                MainProgram testThread = new MainProgram(_config);
                var returnString       = testThread.MakeWebServiceCall(mockedServiceHelper);
                Assert.That(returnString == "This Was Mocked");
            });
        }
Esempio n. 42
0
        public void ItShouldBePossibleToDoARecursiveCommonTableExpression()
        {
            var expr =
                With.Table <RecursivePerson>(
                    SetOperations.UnionAll(
                        Select.Column <Person>(p => new { Level = 0, p.Name, p.ParentId, })
                        .From <Person>()
                        .Where <Person>(p => p.Name == "Kalle"),
                        Select.Column <RecursivePerson>(rp => new { Level = rp.Level + 1 })
                        .Column <Person>(p => new { p.Name, p.ParentId })
                        .From <Person>()
                        .InnerJoin <Person, RecursivePerson>((p, rp) => p.Id == rp.ParentId)))
                .Query(Select.Star <RecursivePerson>().From <RecursivePerson>());
            var result = expr.ToSqlExpression();

            Assert.That(result, Is.EqualTo(TokenGeneration_CommonTableExpressions_Results.recursiveCommonTableExpression));
        }
Esempio n. 43
0
        public void WithWithSimpleHappyPath(ReferenceHandling referenceHandling)
        {
            var x = new With <WithSimpleProperties>(new WithSimpleProperties());
            var y = new With <WithSimpleProperties>(new WithSimpleProperties());

            foreach (var expected in new[] { true, false })
            {
                var comparerMock = new Mock <IEqualityComparer <WithSimpleProperties> >(MockBehavior.Strict);
                comparerMock.Setup(c => c.Equals(x.Value, y.Value))
                .Returns(expected);
                var result = this.EqualByMethod(x, y, comparerMock.Object, referenceHandling);
                Assert.AreEqual(expected, result);
                comparerMock.Verify(
                    c => c.Equals(It.IsAny <WithSimpleProperties>(), It.IsAny <WithSimpleProperties>()),
                    Times.Once);
            }
        }
Esempio n. 44
0
        public void DeleteDocumentWithoutUniqueKey_ShouldThrow()
        {
            var mocks             = new MockRepository();
            var basicServer       = mocks.StrictMock <ISolrBasicOperations <TestDocumentWithoutUniqueKey> >();
            var mapper            = mocks.StrictMock <IReadOnlyMappingManager>();
            var validationManager = mocks.StrictMock <IMappingValidator>();

            With.Mocks(mocks)
            .Expecting(() => {
                Expect.On(mapper)
                .Call(mapper.GetUniqueKey(typeof(TestDocumentWithoutUniqueKey)))
                .Return(null);
            }).Verify(() => {
                var ops = new SolrServer <TestDocumentWithoutUniqueKey>(basicServer, mapper, validationManager);
                ops.Delete(new TestDocumentWithoutUniqueKey());
            });
        }
 public void ToShouldResolveCorrectControllerAndActionWithRequestModelAsString()
 {
     MyMvc
     .Routes()
     .ShouldMap(request => request
                .WithLocation("/Normal/ActionWithMultipleParameters/1")
                .WithMethod(HttpMethod.Post)
                .WithJsonBody(@"{""Integer"":1,""String"":""Text""}"))
     .To <NormalController>(c => c.ActionWithMultipleParameters(
                                1,
                                With.No <string>(),
                                new RequestModel
     {
         Integer = 1,
         String  = "Text"
     }));
 }
Esempio n. 46
0
        /// <summary>
        /// <paramref name="query"/>를 비동기 방식으로 실행하여, 결과 셋을 <see cref="Task{DataTable}"/>로 반환합니다.
        /// </summary>
        /// <param name="db">DAAB의 SQLite 용 Database 인스턴스</param>
        /// <param name="query">실행할 SQL String 또는 Procedure 명</param>
        /// <param name="firstResult">조회할 첫번째 인덱스 (0부터 시작)</param>
        /// <param name="maxResults">조회할 최대 레코드 수 (0이면 최대)</param>
        /// <param name="parameters">파리미터 정보</param>
        public static Task <DataTable> ExecuteDataTableAsync(this SQLiteDatabase db,
                                                             string query,
                                                             int firstResult,
                                                             int maxResults,
                                                             params IAdoParameter[] parameters)
        {
            var cmd = db.GetSQLiteCommand(query);

            return
                (ExecuteDataTableAsync(db, cmd, firstResult, maxResults, parameters)
                 .ContinueWith(task => {
                With.TryAction(() => cmd.Dispose());
                return task;
            },
                               TaskContinuationOptions.ExecuteSynchronously)
                 .Unwrap());
        }
 public void WithTimeouts()
 {
     With
     .Wait(1)
     .Wait(TimeSpan.FromMilliseconds(50))
     .WaitInterval(1)
     .WaitInterval(TimeSpan.FromMilliseconds(50))
     .WaitOnAllActions(false)
     .WaitOnAllAsserts(false)
     .WaitOnAllExpects(false)
     .WindowSize(800, 600)
     .ScreenshotOnFailedAction(false)
     .ScreenshotOnFailedAssert(false)
     .ScreenshotOnFailedExpect(false)
     .ScreenshotPath("")
     .ScreenshotPrefix("");
 }
            public void WithImmutable(ReferenceHandling referenceHandling)
            {
                var source = new With<Immutable>();

                var propertyChanges = new List<string>();
                var changes = new List<EventArgs>();

                using (var tracker = Track.Changes(source, referenceHandling))
                {
                    tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName);
                    tracker.Changed += (_, e) => changes.Add(e);
                    CollectionAssert.IsEmpty(propertyChanges);
                    CollectionAssert.IsEmpty(changes);

                    source.Value = new Immutable();
                    Assert.AreEqual(1, tracker.Changes);
                    CollectionAssert.AreEqual(new[] { "Changes" }, propertyChanges);
                    var node = ChangeTrackerNode.GetOrCreate(source, tracker.Settings, false).Value;
                    var expected = new[] { RootChangeEventArgs.Create(node, new PropertyChangeEventArgs(source, source.GetProperty(nameof(source.Value)))) };
                    CollectionAssert.AreEqual(expected, changes, EventArgsComparer.Default);
                }
            }
            public void CreateAndDispose()
            {
                var source = new With<ObservableCollection<ComplexType>> { Value = new ObservableCollection<ComplexType> { new ComplexType() } };
                var propertyChanges = new List<string>();
                var changes = new List<EventArgs>();
                var tracker = Track.Changes(source, ReferenceHandling.Structural);
                tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName);
                tracker.Changed += (_, e) => changes.Add(e);
                Assert.AreEqual(0, tracker.Changes);
                CollectionAssert.IsEmpty(propertyChanges);
                CollectionAssert.IsEmpty(changes);
                tracker.Dispose();

                source.Value[0].Value++;
                Assert.AreEqual(0, tracker.Changes);
                CollectionAssert.IsEmpty(propertyChanges);
                CollectionAssert.IsEmpty(changes);

                source.Value = new ObservableCollection<ComplexType>();
                Assert.AreEqual(0, tracker.Changes);
                CollectionAssert.IsEmpty(propertyChanges);
                CollectionAssert.IsEmpty(changes);
            }
Esempio n. 50
0
 public void Perform(With.Component.IIdentity actor, With.Component.IIdentity entity, With.Component.IIdentity actionable, IEnumerable<With.Component.IParameterValue> parameterValues)
 {
     _connectionInstance.Publish(_configurationSettings.ExchangeName, _routingKey.ForActionBy(entity, actionable), new Message.Action(entity, actionable, actor, parameterValues));
 }
            public void WithExplicitImmutableAndComparer()
            {
                var x = new With<IntCollection> { Value = new IntCollection(1) };
                var y = new With<IntCollection> { Value = new IntCollection(1) };
                var propertyChanges = new List<string>();
                var expectedChanges = new List<string>();
                var settings = PropertiesSettings.Build()
                                                 .AddImmutableType<IntCollection>()
                                                 .AddComparer(IntCollection.Comparer)
                                                 .CreateSettings();
                using (var tracker = Track.IsDirty(x, y, settings))
                {
                    tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName);
                    Assert.AreEqual(false, tracker.IsDirty);
                    Assert.AreEqual(null, tracker.Diff);
                    CollectionAssert.IsEmpty(propertyChanges);

                    x.Value = new IntCollection(2);
                    Assert.AreEqual(true, tracker.IsDirty);
                    var expected = "With<IntCollection> Value x: Gu.State.Tests.DirtyTrackerTypes+IntCollection y: Gu.State.Tests.DirtyTrackerTypes+IntCollection";
                    var actual = tracker.Diff.ToString("", " ");
                    Assert.AreEqual(expected, actual);
                    expectedChanges.AddRange(new[] { "Diff", "IsDirty" });
                    CollectionAssert.AreEqual(expectedChanges, propertyChanges);

                    y.Value = new IntCollection(2);
                    Assert.AreEqual(false, tracker.IsDirty);
                    Assert.AreEqual(null, tracker.Diff?.ToString("", " "));
                    expectedChanges.AddRange(new[] { "Diff", "IsDirty" });
                    CollectionAssert.AreEqual(expectedChanges, propertyChanges);
                }
            }
            public void WithImmutableArrayOfInts()
            {
                var x = new With<ImmutableArray<int>> { Value = ImmutableArray<int>.Empty };
                var y = new With<ImmutableArray<int>> { Value = ImmutableArray<int>.Empty };
                var propertyChanges = new List<string>();
                var expectedChanges = new List<string>();
                using (var tracker = Track.IsDirty(x, y))
                {
                    tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName);
                    Assert.AreEqual(false, tracker.IsDirty);
                    Assert.AreEqual(null, tracker.Diff);
                    CollectionAssert.IsEmpty(propertyChanges);

                    x.Value = ImmutableArray.Create(1);
                    Assert.AreEqual(true, tracker.IsDirty);
                    Assert.AreEqual("With<ImmutableArray<int>> Value [0] x: 1 y: missing item", tracker.Diff.ToString("", " "));
                    expectedChanges.AddRange(new[] { "Diff", "IsDirty" });
                    CollectionAssert.AreEqual(expectedChanges, propertyChanges);

                    y.Value = ImmutableArray.Create(1);
                    Assert.AreEqual(false, tracker.IsDirty);
                    Assert.AreEqual(null, tracker.Diff?.ToString("", " "));
                    expectedChanges.AddRange(new[] { "Diff", "IsDirty" });
                    CollectionAssert.AreEqual(expectedChanges, propertyChanges);
                }
            }
            public void WithBool()
            {
                var x = new With<bool> { Value = true };
                var y = new With<bool> { Value = true };
                var propertyChanges = new List<string>();
                var expectedChanges = new List<string>();
                using (var tracker = Track.IsDirty(x, y))
                {
                    tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName);
                    Assert.AreEqual(false, tracker.IsDirty);
                    Assert.AreEqual(null, tracker.Diff);
                    CollectionAssert.IsEmpty(propertyChanges);

                    x.Value = false;
                    Assert.AreEqual(true, tracker.IsDirty);
                    Assert.AreEqual("With<bool> Value x: false y: true", tracker.Diff.ToString("", " "));
                    expectedChanges.AddRange(new[] { "Diff", "IsDirty" });
                    CollectionAssert.AreEqual(expectedChanges, propertyChanges);

                    y.Value = false;
                    Assert.AreEqual(false, tracker.IsDirty);
                    Assert.AreEqual(null, tracker.Diff?.ToString("", " "));
                    expectedChanges.AddRange(new[] { "Diff", "IsDirty" });
                    CollectionAssert.AreEqual(expectedChanges, propertyChanges);
                }
            }
            public void WithLength()
            {
                var x = new With<Length> { Value = Length.Zero };
                var y = new With<Length> { Value = Length.Zero };
                var propertyChanges = new List<string>();
                var expectedChanges = new List<string>();
                using (var tracker = Track.IsDirty(x, y))
                {
                    tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName);
                    Assert.AreEqual(false, tracker.IsDirty);
                    Assert.AreEqual(null, tracker.Diff);
                    CollectionAssert.IsEmpty(propertyChanges);

                    x.Value = Length.FromCentimetres(1);
                    Assert.AreEqual(true, tracker.IsDirty);
                    Assert.AreEqual("With<Length> Value x: 0.01\u00A0m y: 0\u00A0m", tracker.Diff.ToString("", " "));
                    expectedChanges.AddRange(new[] { "Diff", "IsDirty" });
                    CollectionAssert.AreEqual(expectedChanges, propertyChanges);

                    y.Value = Length.FromCentimetres(1);
                    Assert.AreEqual(false, tracker.IsDirty);
                    Assert.AreEqual(null, tracker.Diff?.ToString("", " "));
                    expectedChanges.AddRange(new[] { "Diff", "IsDirty" });
                    CollectionAssert.AreEqual(expectedChanges, propertyChanges);
                }
            }
Esempio n. 55
0
            internal static stmt Convert(Statement stmt) {
                stmt ast;

                if (stmt is FunctionDefinition)
                    ast = new FunctionDef((FunctionDefinition)stmt);
                else if (stmt is ReturnStatement)
                    ast = new Return((ReturnStatement)stmt);
                else if (stmt is AssignmentStatement)
                    ast = new Assign((AssignmentStatement)stmt);
                else if (stmt is AugmentedAssignStatement)
                    ast = new AugAssign((AugmentedAssignStatement)stmt);
                else if (stmt is DelStatement)
                    ast = new Delete((DelStatement)stmt);
                else if (stmt is PrintStatement)
                    ast = new Print((PrintStatement)stmt);
                else if (stmt is ExpressionStatement)
                    ast = new Expr((ExpressionStatement)stmt);
                else if (stmt is ForStatement)
                    ast = new For((ForStatement)stmt);
                else if (stmt is WhileStatement)
                    ast = new While((WhileStatement)stmt);
                else if (stmt is IfStatement)
                    ast = new If((IfStatement)stmt);
                else if (stmt is WithStatement)
                    ast = new With((WithStatement)stmt);
                else if (stmt is RaiseStatement)
                    ast = new Raise((RaiseStatement)stmt);
                else if (stmt is TryStatement)
                    ast = Convert((TryStatement)stmt);
                else if (stmt is AssertStatement)
                    ast = new Assert((AssertStatement)stmt);
                else if (stmt is ImportStatement)
                    ast = new Import((ImportStatement)stmt);
                else if (stmt is FromImportStatement)
                    ast = new ImportFrom((FromImportStatement)stmt);
                else if (stmt is ExecStatement)
                    ast = new Exec((ExecStatement)stmt);
                else if (stmt is GlobalStatement)
                    ast = new Global((GlobalStatement)stmt);
                else if (stmt is ClassDefinition)
                    ast = new ClassDef((ClassDefinition)stmt);
                else if (stmt is BreakStatement)
                    ast = new Break();
                else if (stmt is ContinueStatement)
                    ast = new Continue();
                else if (stmt is EmptyStatement)
                    ast = new Pass();
                else
                    throw new ArgumentTypeException("Unexpected statement type: " + stmt.GetType());

                ast.GetSourceLocation(stmt);
                return ast;
            }
Esempio n. 56
0
 public Instance(With.Messaging.Client.IEndpoint clientEndpoint)
 {
     _clientEndpoint = clientEndpoint;
     _messages = new Subject<With.Message.IMessage>();
 }
Esempio n. 57
0
 public void Register(With.Component.IIdentity registrar, With.Component.IEntity entity, IObserver<With.Message.IMessage> consumer)
 {
     _connectionInstance.BuildQueue(_queueName.For(entity.Identity));
     _connectionInstance.BindConsumer(_queueName.For(entity.Identity), consumer);
     _connectionInstance.Publish(_configurationSettings.ExchangeName, _routingKey.ForRegistrationOf(entity.Identity), new Message.Register(registrar, entity));
 }
Esempio n. 58
0
 public void Publish(With.Component.IIdentity entity, With.Component.IIdentity observable, DateTimeOffset date, With.Component.IMeasurement measurement)
 {
     _connectionInstance.Publish(_configurationSettings.ExchangeName, _routingKey.ForObservation(entity, observable), new Message.Observation(entity, observable, date, measurement));
 }
Esempio n. 59
0
 public void Observe(With.Component.IIdentity observer, With.Component.IIdentity entity, With.Component.IIdentity observable)
 {
     _connectionInstance.Publish(_configurationSettings.ExchangeName, _routingKey.ForObserving(entity, observable), new Message.Observe(entity, observable, observer));
 }
Esempio n. 60
0
 public void Deregister(With.Component.IIdentity registrar, With.Component.IEntity entity)
 {
     _connectionInstance.Publish(_configurationSettings.ExchangeName, _routingKey.ForDeregistrationOf(entity.Identity), new Message.Deregister(registrar, entity.Identity));
     _connectionInstance.RemoveQueue(_queueName.For(entity.Identity));
 }