コード例 #1
0
ファイル: OrderSn.cs プロジェクト: wpmyj/DotNet.QCTERP.Base
        /// <summary>
        /// 订单流水数据+1
        /// </summary>
        public void NextNumber()
        {
            IncreasingNumber++;
            var publisher = PublisherFactory.Create();

            publisher.PublishAsync(string.Format("Qct.LocalPos.NextIncreasingNumber.{0}.{1}.{2}", CompanyId, StoreId, MachineSn), IncreasingNumber, true);
        }
コード例 #2
0
        public static void RegisterServices(IContainer container)
        {
            Preconditions.CheckNotNull(container, "container");

            // Note: IConnectionConfiguration gets registered when RabbitHutch.CreateBus(..) is run.

            // default service registration
            container
            .Register(_ => container)
            .Register <IEasyNetQLogger, ConsoleLogger>()
            .Register <ISerializer, JsonSerializer>()
            .Register <IConventions, Conventions>()
            .Register <IEventBus, EventBus>()
            .Register <ITypeNameSerializer, TypeNameSerializer>()
            .Register <ICorrelationIdGenerationStrategy, DefaultCorrelationIdGenerationStrategy>()
            .Register <IMessageSerializationStrategy, DefaultMessageSerializationStrategy>()
            .Register <IMessageDeliveryModeStrategy, MessageDeliveryModeStrategy>()
            .Register <IClusterHostSelectionStrategy <ConnectionFactoryInfo>, DefaultClusterHostSelectionStrategy <ConnectionFactoryInfo> >()
            .Register <IConsumerDispatcherFactory, ConsumerDispatcherFactory>()
            .Register <IPublishExchangeDeclareStrategy, PublishExchangeDeclareStrategy>()
            .Register(sp => PublisherFactory.CreatePublisher(sp.Resolve <IConnectionConfiguration>(), sp.Resolve <IEasyNetQLogger>(), sp.Resolve <IEventBus>()))
            .Register <IConsumerErrorStrategy, DefaultConsumerErrorStrategy>()
            .Register <IHandlerRunner, HandlerRunner>()
            .Register <IInternalConsumerFactory, InternalConsumerFactory>()
            .Register <IConsumerFactory, ConsumerFactory>()
            .Register <IConnectionFactory, ConnectionFactoryWrapper>()
            .Register <IPersistentChannelFactory, PersistentChannelFactory>()
            .Register <IClientCommandDispatcherFactory, ClientCommandDispatcherFactory>()
            .Register <IHandlerCollectionFactory, HandlerCollectionFactory>()
            .Register <IAdvancedBus, RabbitAdvancedBus>()
            .Register <IRpc, Rpc>()
            .Register <ISendReceive, SendReceive>()
            .Register <IBus, RabbitBus>();
        }
コード例 #3
0
        public void Build_ShouldReturnEventPublisher()
        {
            var publisher = PublisherFactory.Build(this.mockedBus.Object);

            Assert.NotNull(publisher);
            Assert.IsType <EventPublisher>(publisher);
        }
コード例 #4
0
        public void Register_ShouldRegisterAsReactiveBus()
        {
            var bus = PublisherFactory.Register(this.mockedSubscribers);

            Assert.NotNull(bus);
            Assert.IsType <ReactiveBus>(bus);
        }
コード例 #5
0
        /// <summary>
        /// 提交订单
        /// </summary>
        /// <returns></returns>
        public Order SubmitOrder(IEnumerable <IOrderMarketingResult> marketingResults)
        {
            var order     = new Order(this, marketingResults);
            var publisher = PublisherFactory.Create();

            publisher.PublishAsync(string.Format("PharosRetailing.POSOrderCommited.{0}.{1}.{2}", Cashier.CompanyId, Cashier.StoreId, Cashier.MachineSn), order, true);
            return(order);
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: alesvi/Ve.Messaging
        private static PublisherFactory GetPublisher(IVeStatsDClient client)
        {
            var publisherFactory = new PublisherFactory(
                client,
                new TopicClientCreator(new TopicCreator())
                );

            return(publisherFactory);
        }
コード例 #7
0
        /// <summary>
        /// 设置订单完成
        /// </summary>
        public void SetOrderComplete()
        {
            //必须先锁定流水号
            OrderId.SetLockIncreasingNumber();

            var publisher = PublisherFactory.Create();

            publisher.PublishAsync(string.Format("Qct.LocalPos.OrderCompleted.{0}.{1}.{2}", Cashier.CompanyId, Cashier.StoreId, Cashier.MachineSn), this, true);
        }
コード例 #8
0
        private LogStashForwarderService(PublisherFactory publisherFactory)
        {
            const string connectionStringName = "logstashConnecctionString";
            var          publisher            =
                publisherFactory.GetPublisherByAddOnConnection(ConfigurationManager.AppSettings[connectionStringName]);
            var publisherThread = new Thread(publisher.Publish);

            publisherThread.Start();
        }
コード例 #9
0
 public FakeFantasyCriticRepo(FakeFantasyCriticUserStore userStore, FakeMasterGameRepo fakeMasterGameRepo)
 {
     _userStore          = userStore;
     _fakeMasterGameRepo = fakeMasterGameRepo;
     _leagues            = LeagueFactory.GetLeagues();
     _leagueYears        = LeagueFactory.GetLeagueYears();
     _usersInLeagues     = LeagueFactory.GetUsersInLeagues();
     _publishers         = PublisherFactory.GetPublishers();
     _publisherGames     = PublisherFactory.GetPublisherGames();
 }
コード例 #10
0
        private static PublisherFactory GetPublisher(VeStatsDClient client)
        {
            var publisherFactory = new PublisherFactory(
                client,
                new FailoverResolver(),
                new SimpleSerializer(),
                new TopicClientCreator(new TopicCreator())
                );

            return(publisherFactory);
        }
コード例 #11
0
        /// <summary>
        /// 设置支付完成
        /// </summary>
        /// <param name="orderPays"></param>
        public void SetOrderPayComplete(IEnumerable <OrderPay> orderPays)
        {
            if (orderPays == null)
            {
                throw new OrderException("支付信息为空,设置失败!");
            }
            OrderPays  = orderPays;
            OrderState = OrderState.Paid;
            var publisher = PublisherFactory.Create();

            publisher.PublishAsync(string.Format("Qct.LocalPos.OrderPaid.{0}.{1}.{2}", Cashier.CompanyId, Cashier.StoreId, Cashier.MachineSn), this, true);
        }
コード例 #12
0
        public void RemoteCallback(SocketClient client, SockectPackageMessage package)
        {
            EventJsonWrapper eventJson;

            if (package.TryReadFromJsonStream(out eventJson))
            {
                var publisher = PublisherFactory.Create();
                if (publisher.PublisherId != eventJson.PublisherId)
                {
                    publisher.PublishAsync(eventJson);
                }
            }
        }
コード例 #13
0
ファイル: ServiceWrapper.cs プロジェクト: 2garryn/wpay
        public void Execute()
        {
            var def                = new TServDef();
            var routes             = new Routes(_deps.Prefix, def.Label());
            var publFactoryBuilder = new PublisherFactoryBuilder(routes, _deps, def.Label(), "none");

            def.Configure(new ExecuteConfigurator(null !, publFactoryBuilder));
            _publisherFactory = publFactoryBuilder.Build();
            var contextFactory = new MessageContextFactory(_publisherFactory);
            var consumeCatalog = new ConsumeCatalogBuilder(routes, contextFactory, _impl.GetConsumerFactory(), _deps);

            def.Configure(new ExecuteConfigurator(consumeCatalog, null !));
            consumeCatalog.Register(_consumer);
        }
コード例 #14
0
        public void SetUp()
        {
            eventBus = new EventBus();

            var connectionConfiguration = new ConnectionConfiguration
            {
                PublisherConfirms = true,
                Timeout           = 1000
            };

            var logger = MockRepository.GenerateStub <IEasyNetQLogger>();

            publisherConfirms = PublisherFactory.CreatePublisher(connectionConfiguration, logger, eventBus);
        }
コード例 #15
0
        public void Should_return_instance_of_publisher_basic()
        {
            var eventBus = MockRepository.GenerateStub <IEventBus>();
            var logger   = MockRepository.GenerateStub <IEasyNetQLogger>();

            var connectionConfiguration = new ConnectionConfiguration
            {
                PublisherConfirms = false
            };

            publisher = PublisherFactory.CreatePublisher(connectionConfiguration, logger, eventBus);

            Assert.IsAssignableFrom <PublisherBasic>(publisher);
        }
コード例 #16
0
        public async Task GenerateGod()
        {
            var Factory = new PublisherFactory();
            var dto     = Factory.GetDataObject(50000, 60000);

            dto.Publisher.PublisherName = "GOD";
            await _context.Publishers.AddAsync(dto.Publisher);

            foreach (var article in dto.Articles)
            {
                await _context.Articles.AddAsync(article);
            }
            await _context.SaveChangesAsync();
        }
コード例 #17
0
        public static void Main(string[] args)
        {
            var publisher = PublisherFactory
                            .Register(GetSubscribers())
                            .Build();

            var console = new Console();

            var app = new AppBuilder(publisher, console, PublisherName);

            while (true)
            {
                app.Run();
            }
        }
コード例 #18
0
        [Fact] public void CorrectGeneratedPublisher()
        {
            var factory    = new PublisherFactory();
            var publishers = new List <PublisherArticlesDTO>();

            for (var i = 0; i < 10; i++)
            {
                publishers.Add(factory.GetDataObject());
            }

            Assert.Equal(10, publishers.Count);
            Assert.Contains(publishers, dto => dto.Articles.Count > 20);
            Assert.Contains(publishers, dto => dto.Articles.Any(a => a.Url.Contains("www.") && a.Url.Contains(".com")));
            Assert.Contains(publishers, dto => dto.Articles.Any(a => (int)a.Category >= 0 && (int)a.Category <= 3));
        }
コード例 #19
0
        private static IMessagePublisher GetSender(PublisherFactory publisherFactory)
        {
            var sender = publisherFactory.CreatePublisher(new ServiceBusPublisherConfiguration()
            {
                PrimaryConfiguration = new TopicConfiguration()
                {
                    ConnectionString =
                        "Endpoint=sb://v-dv-dtrc-failover.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=bmTetnCQLAH5+cJqTnlNj+ZtpEkafIcIWw5NQUnSIAU=",
                    TopicName = "testtopic2",
                },
                ServiceBusPublisherStrategy = ServiceBusPublisherStrategy.Simple
            });

            return(sender);
        }
コード例 #20
0
ファイル: Program.cs プロジェクト: alesvi/Ve.Messaging
        private static IMessagePublisher GetSender(PublisherFactory publisherFactory)
        {
            string primaryConnectionString = ConfigurationManager.AppSettings[YOUR_PRIMARY_CONNECTION_STRING];
            var    sender = publisherFactory.CreatePublisher(new ServiceBusPublisherConfiguration()
            {
                PrimaryConfiguration = new TopicConfiguration()
                {
                    ConnectionString = primaryConnectionString,
                    TopicName        = "testtopic3",
                },
                ServiceBusPublisherStrategy = ServiceBusPublisherStrategy.Simple
            });

            return(sender);
        }
コード例 #21
0
ファイル: GenerateData.cs プロジェクト: kaep7n/bifr-st
        public GenerateData(ILogger <GenerateData> logger, PublisherFactory publisherFactory)
        {
            if (logger is null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (publisherFactory is null)
            {
                throw new ArgumentNullException(nameof(publisherFactory));
            }

            this.timer.Elapsed += this.Timer_Elapsed;
            this.logger         = logger;
            this.publisher      = publisherFactory.Create();
        }
コード例 #22
0
        [Fact] public async void TestSuccesfullAddArticles()
        {
            var articleContext   = new ArticlesContext(options);
            var controller       = new ArticlesController(articleContext);
            var articleFactory   = new ArticleFactory();
            var publisherFactory = new PublisherFactory();
            var pub = publisherFactory.GetDataObject(0, 0).Publisher;
            await articleContext.Publishers.AddAsync(pub);

            await controller.AddArticles(articleFactory.GenerateArticle(pub.Id));

            var articles = await controller.GetArticles();

            Assert.True(await articleContext.Publishers.CountAsync() == 1);
            Assert.True(articles.Value.Count == 1);
        }
コード例 #23
0
        public async Task GenerateData(int nr)
        {
            var Factory = new PublisherFactory();

            for (var i = 0; i < nr; i++)
            {
                var dto = Factory.GetDataObject();
                await _context.Publishers.AddAsync(dto.Publisher);

                foreach (var article in dto.Articles)
                {
                    await _context.Articles.AddAsync(article);
                }
                await _context.SaveChangesAsync();
            }
        }
コード例 #24
0
ファイル: Logger.cs プロジェクト: arikanmehmet/Nhea
        internal static bool LogCore(LogLevel logLevel, PublishTypes publishType, string source, string userName, string message, Exception exception, bool autoInform)
        {
            try
            {
                Publisher publisher = PublisherFactory.CreatePublisher(publishType);
                publisher.Message    = message;
                publisher.Level      = logLevel;
                publisher.Source     = source;
                publisher.UserName   = userName;
                publisher.Exception  = exception;
                publisher.AutoInform = autoInform;

                if (LogPublishing != null)
                {
                    var subs = LogPublishing.GetInvocationList();
                    foreach (LogPublishingEventHandler sub in subs)
                    {
                        sub.Invoke(publisher);
                    }
                }

                var result = publisher.Publish();

                if (LogPublished != null)
                {
                    var subs = LogPublished.GetInvocationList();
                    foreach (LogPublishedEventHandler sub in subs)
                    {
                        sub.Invoke(publisher, result);
                    }
                }

                return(result);
            }
            catch
            {
                return(false);
            }
        }
コード例 #25
0
        public static IServiceCollection ConfigureEventStore(
            this IServiceCollection services,
            IConfiguration configuration,
            ILoggerFactory loggerFactory)
        {
            var con         = configuration.GetSection("Postgres").Get <string>();
            var connections = new DbConnections(con, con);

            var kafkaBrokers = configuration.GetSection("Kafka:Brokers").Get <string>();

            const string serviceName = "cards";
            var          topic       = $"amethyst_{serviceName}_{typeof(Card).Name.ToLowerInvariant()}";

            var publisherFactory = new PublisherFactory(
                new RecordedEventSerializer(),
                new PublisherConfiguration(kafkaBrokers),
                loggerFactory);

            var settings = new AggregateSettingsBuilder()
                           .AddAggregate <Card, CardId, CardFactory>(services, topic, 5)
                           .Build(connections, publisherFactory, new EventSerializer());

            return(services.AddEventStore(settings, loggerFactory));
        }
コード例 #26
0
        // This function will get triggered/executed when a new message is written
        // on an Azure Queue called queue.
//		public static async Task ProcessQueueMessage([TimerTrigger("0 */10 * * * *")]TimerInfo timer)
        public static async void ProcessQueueMessage([TimerTrigger("0 0 12 1/3 * *")] TimerInfo timer)
        {
            var issueCommandRepository = new IssueCommandRepository();
            var issueQueryRepository   = new IssueQueryRepository();
            var issueContext           = new IssueContext(issueQueryRepository, issueCommandRepository);
            var issueFactory           = new IssueFactory(issueContext);

            var titleCommandRepository = new TitleCommandRepository();
            var titleQueryRepository   = new TitleQueryRepository();
            var titleContext           = new TitleContext(titleQueryRepository, titleCommandRepository);
            var titleFactory           = new TitleFactory(titleContext);

            var publisherQueryRepository = new PublisherQueryRepository();
            var publisherContext         = new PublisherContext(publisherQueryRepository);
            var publisherFactory         = new PublisherFactory(publisherContext);

            var catalogContext = new CatalogContext(publisherFactory, titleFactory, issueFactory);

            var Catalog = new CatalogObject(catalogContext);

            await Catalog.Commands.NewReleases(0);

            var end = string.Empty;
        }
コード例 #27
0
 public void Setup()
 {
     _factory = new PublisherFactory();
 }
コード例 #28
0
        public void TestMethod1()
        {
            IPage pp = PublisherFactory.CreatePage(@"http://rd2.zhaopin.com/portal/myrd/regnew.asp?za=2");

            pp.setWebBrowser(null);
        }
コード例 #29
0
 internal MessageContextFactory(PublisherFactory publisherFactory)
 {
     _publisherFactory = publisherFactory;
 }
コード例 #30
0
        private static void SeedDatabase(IApplicationBuilder app)
        {
            using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetService <ZLibraryContext>();

                if (context.Users.Any())
                {
                    return;
                }

                var users = UserFactory.CreateUsers();
                context.Users.AddRange(users);

                var authors = AuthorFactory.CreateAuthors();
                context.Authors.AddRange(authors);

                var publishers = PublisherFactory.CreatePublishers();
                context.Publishers.AddRange(publishers);

                context.SaveChanges();

                /***********************************/
                /**** ONLY FOR TESTS PURPOSES   ****/
                /***********************************/


                var andrewTroelsen = context.Authors.Single(a => a.Name == "Andrew Troelsen");
                var jackPhillips   = context.Authors.Single(a => a.Name == "Jack Phillips");
                var simonSarris    = context.Authors.Single(a => a.Name == "Simon Sarris");
                var martinFowler   = context.Authors.Single(a => a.Name == "Martin Fowler");
                var bruceEckel     = context.Authors.Single(a => a.Name == "Bruce Eckel");


                var book = new Book()
                {
                    Isbn            = Isbn.FromValue("9780321127426"),
                    PublicationYear = 2014,
                    Publisher       = publishers.Where <Publisher>(p => p.Name == "Editora Futura").SingleOrDefault(),
                    Synopsis        = "HTML5 Unleashed is the authoritative guide that covers the key web components driving the future of the Web",
                    Title           = "HTML 5 - Unleashed",
                    NumberOfCopies  = 3,
                    CoverImageKey   = Guid.Parse("80ae1455-8f43-4a40-aa41-39e486fd61d1")
                };
                context.Books.Add(book);
                context.SaveChanges();

                book.Authors = new List <BookAuthor>()
                {
                    new BookAuthor()
                    {
                        Book     = book,
                        BookId   = book.Id,
                        Author   = simonSarris,
                        AuthorId = simonSarris.Id
                    }
                };
                context.SaveChanges();

                var book2 = new Book()
                {
                    Isbn            = Isbn.FromValue("9780672336270"),
                    PublicationYear = 2014,
                    Publisher       = publishers.FirstOrDefault(),
                    Synopsis        = "Java 2 for professional development and best practices.",
                    Title           = "Effective Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java Javaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                    NumberOfCopies  = 2,
                    CoverImageKey   = Guid.Parse("5b0cf369-a0b2-4643-ac84-36058e729a21")
                };
                context.Books.Add(book2);
                context.SaveChanges();

                book2.Authors = new List <BookAuthor>()
                {
                    new BookAuthor()
                    {
                        Book     = book2,
                        BookId   = book2.Id,
                        Author   = jackPhillips,
                        AuthorId = jackPhillips.Id
                    },
                    new BookAuthor()
                    {
                        Book     = book2,
                        BookId   = book2.Id,
                        Author   = andrewTroelsen,
                        AuthorId = andrewTroelsen.Id
                    },
                    new BookAuthor()
                    {
                        Book     = book2,
                        BookId   = book2.Id,
                        Author   = bruceEckel,
                        AuthorId = bruceEckel.Id
                    }
                };
                context.SaveChanges();

                var book3 = new Book()
                {
                    Isbn            = Isbn.FromValue("9780316037723"),
                    PublicationYear = 2014,
                    Publisher       = publishers.Where <Publisher>(p => p.Name == "Addison - Wesley").SingleOrDefault(),
                    Synopsis        = "The practice of enterprise application development has benefited from the emergence of many new enabling technologies.",
                    Title           = "Enterprise Application Architecture",
                    NumberOfCopies  = 1,
                    CoverImageKey   = Guid.Parse("5b0cf369-a0b2-4643-ac84-36058e729a22")
                };

                context.Books.Add(book3);
                context.SaveChanges();

                book3.Authors = new List <BookAuthor>()
                {
                    new BookAuthor()
                    {
                        Book     = book3,
                        BookId   = book3.Id,
                        Author   = jackPhillips,
                        AuthorId = jackPhillips.Id
                    },
                    new BookAuthor()
                    {
                        Book     = book3,
                        BookId   = book3.Id,
                        Author   = andrewTroelsen,
                        AuthorId = andrewTroelsen.Id
                    }
                };
                context.SaveChanges();

                var book4 = new Book()
                {
                    Isbn            = Isbn.FromValue("9780316037723"),
                    PublicationYear = 2014,
                    Publisher       = publishers.Where <Publisher>(p => p.Name == "Addison - Wesley").SingleOrDefault(),
                    Synopsis        = "The practice of enterprise application development has benefited from the emergence of many new enabling technologies.",
                    Title           = "Enterprise Application Architecture",
                    NumberOfCopies  = 1,
                    CoverImageKey   = Guid.Parse("5b0cf369-a0b2-4643-ac84-36058e729a23")
                };

                context.Books.Add(book4);
                context.SaveChanges();

                book4.Authors = new List <BookAuthor>()
                {
                    new BookAuthor()
                    {
                        Book     = book4,
                        BookId   = book4.Id,
                        Author   = jackPhillips,
                        AuthorId = jackPhillips.Id
                    },
                    new BookAuthor()
                    {
                        Book     = book4,
                        BookId   = book4.Id,
                        Author   = andrewTroelsen,
                        AuthorId = andrewTroelsen.Id
                    }
                };
                context.SaveChanges();

                var book5 = new Book()
                {
                    Isbn            = Isbn.FromValue("9780316037723"),
                    PublicationYear = 2014,
                    Publisher       = publishers.Where <Publisher>(p => p.Name == "Addison - Wesley").SingleOrDefault(),
                    Synopsis        = "The practice of enterprise application development has benefited from the emergence of many new enabling technologies.",
                    Title           = "Enterprise Application Architecture",
                    NumberOfCopies  = 1,
                    CoverImageKey   = Guid.Parse("5b0cf369-a0b2-4643-ac84-36058e729a24")
                };

                context.Books.Add(book5);
                context.SaveChanges();

                book5.Authors = new List <BookAuthor>()
                {
                    new BookAuthor()
                    {
                        Book     = book5,
                        BookId   = book5.Id,
                        Author   = jackPhillips,
                        AuthorId = jackPhillips.Id
                    },
                    new BookAuthor()
                    {
                        Book     = book5,
                        BookId   = book5.Id,
                        Author   = andrewTroelsen,
                        AuthorId = andrewTroelsen.Id
                    }
                };
                context.SaveChanges();

                var book6 = new Book()
                {
                    Isbn            = Isbn.FromValue("9780672336270"),
                    PublicationYear = 2014,
                    Publisher       = publishers.FirstOrDefault(),
                    Synopsis        = "Java 2 for professional development and best practices.",
                    Title           = "Effective Java",
                    NumberOfCopies  = 2,
                    CoverImageKey   = Guid.Parse("5b0cf369-a0b2-4643-ac84-36058e729a25")
                };
                context.Books.Add(book6);
                context.SaveChanges();

                book6.Authors = new List <BookAuthor>()
                {
                    new BookAuthor()
                    {
                        Book     = book6,
                        BookId   = book6.Id,
                        Author   = jackPhillips,
                        AuthorId = jackPhillips.Id
                    },
                    new BookAuthor()
                    {
                        Book     = book6,
                        BookId   = book6.Id,
                        Author   = andrewTroelsen,
                        AuthorId = andrewTroelsen.Id
                    }
                };
                context.SaveChanges();

                var book7 = new Book()
                {
                    Isbn            = Isbn.FromValue("9780672336270"),
                    PublicationYear = 2014,
                    Publisher       = publishers.FirstOrDefault(),
                    Synopsis        = "Java 2 for professional development and best practices.",
                    Title           = "Effective Java",
                    NumberOfCopies  = 2,
                    CoverImageKey   = Guid.Parse("5b0cf369-a0b2-4643-ac84-36058e729a26")
                };
                context.Books.Add(book7);
                context.SaveChanges();

                book7.Authors = new List <BookAuthor>()
                {
                    new BookAuthor()
                    {
                        Book     = book7,
                        BookId   = book7.Id,
                        Author   = jackPhillips,
                        AuthorId = jackPhillips.Id
                    },
                    new BookAuthor()
                    {
                        Book     = book7,
                        BookId   = book7.Id,
                        Author   = andrewTroelsen,
                        AuthorId = andrewTroelsen.Id
                    }
                };
                context.SaveChanges();

                var book8 = new Book()
                {
                    Isbn            = Isbn.FromValue("9780672336270"),
                    PublicationYear = 2014,
                    Publisher       = publishers.FirstOrDefault(),
                    Synopsis        = "Java 2 for professional development and best practices.",
                    Title           = "Effective Java",
                    NumberOfCopies  = 2,
                    CoverImageKey   = Guid.Parse("5b0cf369-a0b2-4643-ac84-36058e729a27")
                };
                context.Books.Add(book8);
                context.SaveChanges();

                book8.Authors = new List <BookAuthor>()
                {
                    new BookAuthor()
                    {
                        Book     = book8,
                        BookId   = book8.Id,
                        Author   = jackPhillips,
                        AuthorId = jackPhillips.Id
                    },
                    new BookAuthor()
                    {
                        Book     = book8,
                        BookId   = book8.Id,
                        Author   = andrewTroelsen,
                        AuthorId = andrewTroelsen.Id
                    }
                };
                context.SaveChanges();

                var book9 = new Book()
                {
                    Isbn            = Isbn.FromValue("9780672336270"),
                    PublicationYear = 2014,
                    Publisher       = publishers.FirstOrDefault(),
                    Synopsis        = "Java 2 for professional development and best practices.",
                    Title           = "Effective Java",
                    NumberOfCopies  = 2,
                    CoverImageKey   = Guid.Parse("5b0cf369-a0b2-4643-ac84-36058e729a28")
                };
                context.Books.Add(book9);
                context.SaveChanges();

                book9.Authors = new List <BookAuthor>()
                {
                    new BookAuthor()
                    {
                        Book     = book9,
                        BookId   = book9.Id,
                        Author   = jackPhillips,
                        AuthorId = jackPhillips.Id
                    },
                    new BookAuthor()
                    {
                        Book     = book9,
                        BookId   = book9.Id,
                        Author   = andrewTroelsen,
                        AuthorId = andrewTroelsen.Id
                    }
                };
                context.SaveChanges();

                var book10 = new Book()
                {
                    Isbn            = Isbn.FromValue("9780672336270"),
                    PublicationYear = 2014,
                    Publisher       = publishers.FirstOrDefault(),
                    Synopsis        = "Java 2 for professional development and best practices.",
                    Title           = "Effective Java",
                    NumberOfCopies  = 2,
                    CoverImageKey   = Guid.Parse("5b0cf369-a0b2-4643-ac84-36058e729a29")
                };
                context.Books.Add(book10);
                context.SaveChanges();

                book10.Authors = new List <BookAuthor>()
                {
                    new BookAuthor()
                    {
                        Book     = book10,
                        BookId   = book10.Id,
                        Author   = jackPhillips,
                        AuthorId = jackPhillips.Id
                    },
                    new BookAuthor()
                    {
                        Book     = book10,
                        BookId   = book10.Id,
                        Author   = andrewTroelsen,
                        AuthorId = andrewTroelsen.Id
                    }
                };
                context.SaveChanges();

                var book11 = new Book()
                {
                    Isbn            = Isbn.FromValue("9780672336270"),
                    PublicationYear = 2014,
                    Publisher       = publishers.FirstOrDefault(),
                    Synopsis        = "Java 2 for professional development and best practices.",
                    Title           = "Effective Java",
                    NumberOfCopies  = 2,
                    CoverImageKey   = Guid.Parse("5b0cf369-a0b2-4643-ac84-36058e729a30")
                };
                context.Books.Add(book11);
                context.SaveChanges();

                book11.Authors = new List <BookAuthor>()
                {
                    new BookAuthor()
                    {
                        Book     = book11,
                        BookId   = book11.Id,
                        Author   = jackPhillips,
                        AuthorId = jackPhillips.Id
                    },
                    new BookAuthor()
                    {
                        Book     = book11,
                        BookId   = book11.Id,
                        Author   = andrewTroelsen,
                        AuthorId = andrewTroelsen.Id
                    }
                };
                context.SaveChanges();

                var book12 = new Book()
                {
                    Isbn            = Isbn.FromValue("9780672336270"),
                    PublicationYear = 2014,
                    Publisher       = publishers.FirstOrDefault(),
                    Synopsis        = "Java 2 for professional development and best practices.",
                    Title           = "Effective Java",
                    NumberOfCopies  = 2,
                    CoverImageKey   = Guid.Parse("5b0cf369-a0b2-4643-ac84-36058e729a31")
                };
                context.Books.Add(book12);
                context.SaveChanges();

                book12.Authors = new List <BookAuthor>()
                {
                    new BookAuthor()
                    {
                        Book     = book12,
                        BookId   = book12.Id,
                        Author   = jackPhillips,
                        AuthorId = jackPhillips.Id
                    },
                    new BookAuthor()
                    {
                        Book     = book12,
                        BookId   = book12.Id,
                        Author   = andrewTroelsen,
                        AuthorId = andrewTroelsen.Id
                    }
                };
                context.SaveChanges();

                // var book3 = new Book()
                // {
                //     Authors = new List<Author>() { martinFowler },
                //     Isbn = Isbn.FromValue("9780316037723"),
                //     PublicationYear = 2014,
                //     Publisher = publishers.Where<Publisher>(p => p.Name == "Addison - Wesley").SingleOrDefault(),
                //     Synopsis = "The practice of enterprise application development has benefited from the emergence of many new enabling technologies.",
                //     Title = "Patterns of Enterprise Application Architecture"
                // };
                // martinFowler.Books = new List<Book>() { book3 };
                // context.Books.Add(book3);
                // context.SaveChanges();

                // var book4 = new Book()
                // {
                //     Authors = new List<Author>() { andrewTroelsen },
                //     Isbn = Isbn.FromValue("9780201738292"),
                //     PublicationYear = 2014,
                //     Publisher = publishers.FirstOrDefault(),
                //     Synopsis = "Java 2 for professional development and best practices.",
                //     Title = "Java"
                // };
                // andrewTroelsen.Books = new List<Book>() { book2, book4 };
                // context.Books.Add(book4);
                // context.SaveChanges();

                // var book5 = new Book()
                // {
                //     Authors = context.Authors.Where(a => a.Name == "Andrew Troelsen" || a.Name == "Martin Fowler").ToList(),
                //     Isbn = Isbn.FromValue("9780316380508"),
                //     PublicationYear = 2014,
                //     Publisher = publishers.FirstOrDefault(),
                //     Synopsis = "Java 2 for professional development and best practices.",
                //     Title = "Java Cool"
                // };
                // context.Books.Add(book5);
                // context.SaveChanges();

                // var book6 = new Book()
                // {
                //     Authors = context.Authors.Where(a => a.Name == "Andrew Troelsen" || a.Name == "Martin Fowler").ToList(),
                //     Isbn = Isbn.FromValue("9780764542800"),
                //     PublicationYear = 2014,
                //     Publisher = publishers.Where(p => p.Name == "Addison - Wesley").SingleOrDefault(),
                //     Synopsis = "Java 2 for professional development and best practices.",
                //     Title = "Java F**k Cool"
                // };
                // context.Books.Add(book6);
                // context.SaveChanges();

                // var book7 = new Book()
                // {
                //     Authors = new List<Author>() { context.Authors.Single(a => a.Name == "Andrew Troelsen") },
                //     Isbn = Isbn.FromValue("9780764542800"),
                //     PublicationYear = 2014,
                //     Publisher = context.Publishers.Where(p => p.Name == "Addison - Wesley").SingleOrDefault(),
                //     Synopsis = "Java 2 for professional development and best practices.",
                //     Title = "Java Awesome Cool"
                // };
                // context.Books.Add(book7);
                // context.SaveChanges();

                var bookId     = 1;
                var firstUser  = users.SingleOrDefault(u => u.Id == 17);
                var secondUser = users.SingleOrDefault(u => u.Id == 16);

                var reservation1 = new Reservation(bookId, secondUser);
                reservation1.Reason.Status = ReservationStatus.Requested;
                context.Reservations.Add(reservation1);
                context.SaveChanges();

                var reservation2 = new Reservation(2, firstUser);
                reservation2.Reason.Status = ReservationStatus.Requested;
                context.Reservations.Add(reservation2);
                context.SaveChanges();

                var reservation3 = new Reservation(3, firstUser);
                reservation3.Reason.Status = ReservationStatus.Requested;
                context.Reservations.Add(reservation3);
                context.SaveChanges();

                var reservation4 = new Reservation(3, firstUser);
                reservation4.Reason.Status = ReservationStatus.Approved;
                context.Reservations.Add(reservation4);
                context.SaveChanges();

                /*
                 * var loan1 = new Loan(reservation1);
                 * loan1.Status = LoanStatus.Borrowed;
                 * //loan1.ExpirationDate = DateTime.Now.AddDays(-1);
                 * context.Loans.Add(loan1);
                 * context.SaveChanges();
                 *
                 * var loan2 = new Loan(reservation2);
                 * loan2.Status = LoanStatus.Returned;
                 * context.Loans.Add(loan2);
                 * context.SaveChanges();
                 *
                 * var loan3 = new Loan(reservation3);
                 * context.Loans.Add(loan3);
                 * context.SaveChanges();
                 *
                 * var loan4 = new Loan(reservation4);
                 * context.Loans.Add(loan4);
                 * context.SaveChanges();
                 */
            }
        }
コード例 #31
0
        public async Task <bool[]> CreateMonitoredItemsAsync(string serverUrl, MonitorableNode[] monitorableNodes,
                                                             string brokerUrl, string topic)
        {
            var session = await GetSessionAsync(serverUrl);

            MonitorPublishInfo monitorInfo;

            const string pattern  = @"^(mqtt|signalr):(.*)$";
            var          match    = Regex.Match(brokerUrl, pattern);
            var          protocol = match.Groups[1].Value;
            var          url      = match.Groups[2].Value;

            var publisher = PublisherFactory.GetPublisherForProtocol(protocol, url);

            //Set publishInterval to minimum samplinginterval
            var publishInterval = monitorableNodes.Select(elem => elem.SamplingInterval).Min();

            lock (_monitorPublishInfo)
            {
                //Check if a Subscription for the
                if (_monitorPublishInfo.ContainsKey(serverUrl))
                {
                    monitorInfo = _monitorPublishInfo[serverUrl].FirstOrDefault(info => info.Topic == topic && info.BrokerUrl == url);
                    if (monitorInfo == null)
                    {
                        monitorInfo = new MonitorPublishInfo()
                        {
                            Topic        = topic,
                            BrokerUrl    = url,
                            Subscription = CreateSubscription(session, publishInterval, 0),
                            Publisher    = publisher
                        };
                        _monitorPublishInfo[serverUrl].Add(monitorInfo);
                    }
                    else if (monitorInfo.Subscription.PublishingInterval > publishInterval)
                    {
                        monitorInfo.Subscription.PublishingInterval = publishInterval;
                        monitorInfo.Subscription.Modify();
                    }
                }
                else
                {
                    monitorInfo = new MonitorPublishInfo()
                    {
                        Topic        = topic,
                        BrokerUrl    = url,
                        Subscription = CreateSubscription(session, publishInterval, 0),
                        Publisher    = publisher
                    };
                    var list = new List <MonitorPublishInfo> {
                        monitorInfo
                    };
                    _monitorPublishInfo.Add(serverUrl, list);
                }
            }

            var createdMonitoredItems = new List <MonitoredItem>();

            foreach (var monitorableNode in monitorableNodes)
            {
                var mi = new MonitoredItem()
                {
                    StartNodeId      = PlatformUtils.ParsePlatformNodeIdString(monitorableNode.NodeId),
                    DisplayName      = monitorableNode.NodeId,
                    SamplingInterval = monitorableNode.SamplingInterval
                };

                if (monitorableNode.DeadBand != "none")
                {
                    mi.Filter = new DataChangeFilter()
                    {
                        Trigger       = DataChangeTrigger.StatusValue,
                        DeadbandType  = (uint)(DeadbandType)Enum.Parse(typeof(DeadbandType), monitorableNode.DeadBand, true),
                        DeadbandValue = monitorableNode.DeadBandValue
                    };
                }

                mi.Notification += OnMonitorNotification;
                monitorInfo.Subscription.AddItem(mi);
                var monitoredItems = monitorInfo.Subscription.CreateItems();
                createdMonitoredItems.AddRange(monitoredItems);
            }

            var results = createdMonitoredItems.Distinct().Select(m => m.Created).ToArray();

            foreach (var monitoredItem in createdMonitoredItems.Where(m => !m.Created))
            {
                monitorInfo.Subscription.RemoveItem(monitoredItem);
            }

            return(results);
        }