示例#1
0
        public MainWindow()
        {
            InitializeComponent();

            ROS.Init(new string[0], "wpf_talker");
            nh = new NodeHandle();

            pub = nh.advertise<Messages.std_msgs.String>("/chatter", 1, false);

            pubthread = new Thread(() =>
            {
                int i = 0;
                Messages.std_msgs.String msg;
                while (ROS.ok && !closing)
                {
                    msg = new Messages.std_msgs.String("foo " + (i++));
                    pub.publish(msg); 
                    Dispatcher.Invoke(new Action(() =>
                    {
                        l.Content = "Sending: " + msg.data;
                    }),new TimeSpan(0,0,1));
                    Thread.Sleep(100);
                }
            });
            pubthread.Start();
        }
 public Publisher AddPublisher(Publisher publisher)
 {
     var query = Ninject.Get<InsertPublisherQuery>();
     query.Publisher = publisher;
     query.Execute();
     return publisher;
 }
示例#3
0
 public override void farewell(Publisher publisher, SubscriberStub subStub)
 {
     if (Greeter != null)
     {
         Greeter.Farewell(TypedPublisher, subStub);
     }
 }
示例#4
0
文件: Program.cs 项目: yksz/samples
        private static void Run()
        {
            using (var countdown = new CountdownEvent(2))
            {
                var subscriber = new Subscriber(MqttBrokerAddress, MqttBrokerPort);
                subscriber.Subscribe(Topic.Hello, Topic.Goodbye);
                subscriber.OnMessage += (topic, payload) =>
                {
                    if (topic == Topic.Hello)
                    {
                        var msg = JsonConvert.DeserializeObject<HelloMessage>(payload);
                        _log.Info("Topic: " + topic);
                        _log.Info("Message: " + msg);
                        countdown.Signal();
                    }
                    else if (topic == Topic.Goodbye)
                    {
                        var msg = JsonConvert.DeserializeObject<GoodbyeMessage>(payload);
                        _log.Info("Topic: " + topic);
                        _log.Info("Message: " + msg);
                        countdown.Signal();
                    }
                };

                var publisher = new Publisher(MqttBrokerAddress, MqttBrokerPort);
                publisher.Publish(Topic.Hello, new HelloMessage() { Name = "John Smith", Date = DateTime.Now });
                publisher.Publish(Topic.Goodbye, new GoodbyeMessage() { Name = "Jane Smith", Date = DateTime.Now });
                countdown.Wait();
            }
        }
 static void Main()
 {
     Publisher eventPublisher = new Publisher();
     new Subscriber("Pesho", eventPublisher);
     new Subscriber("Gosho", eventPublisher);
     eventPublisher.RaiseSampleEvent();
 }
示例#6
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="publisher">Frame publisher instance</param>
 /// <param name="dispatcher">Dispatcher instance used to show frame canvas thread</param>
 /// <param name="screen">Canvas to draw image on</param>
 public FrameUiMonitor(Publisher<IFrame> publisher, Dispatcher dispatcher, System.Windows.Controls.Canvas screen)
     : base(publisher)
 {
     _dispatcher = dispatcher;
     _canvas = screen;
     _imageBrush = new ImageBrush();
 }
        public void One_Publisher_One_Subscriber_Batch_Broadcast()
        {
            using (var publisher = new Publisher())
            using (var subscriber = new Subscriber())
            {
                var endpoint = GetEndpoint();
                publisher.Bind(endpoint);
                subscriber.Connect(endpoint);

                Thread.Sleep(100);

                var counterSignal = new CounterSignal(NumberOfMessagesToReceive);
                subscriber.MessageReceived += (s, m) => counterSignal.Increment();

                var messageSent = new TestMessage();

                var batch = new List<TestMessage>();
                for (var i = 0; i < NumberOfMessagesToReceive; i++)
                    batch.Add(messageSent);

                var sw = Stopwatch.StartNew();
                publisher.Broadcast(batch);
                Assert.IsTrue(counterSignal.Wait(TimeOut), "Timeout waiting for message");
                sw.Stop();

                Assert.Inconclusive("{0} elapsed reading {1} messages ({2:N0} per second)", sw.Elapsed, NumberOfMessagesToReceive, NumberOfMessagesToReceive / sw.Elapsed.TotalSeconds);
            }
        }
        public void Handlers_Can_Be_Unsubscribed()
        {
            var pub = new Publisher();
            var calledSubscribers = new List<int>();
            var sub1 = new InstanceSubscriber(1, pub, calledSubscribers.Add);
            var sub2 = new InstanceSubscriber(2, pub, calledSubscribers.Add);
            StaticSubscriber.FooWasRaised = false;
            StaticSubscriber.Subscribe(pub);

            // Make sure they really were subscribed
            pub.Raise();
            calledSubscribers.Should().Equal(1, 2);
            StaticSubscriber.FooWasRaised.Should().BeTrue();

            calledSubscribers.Clear();
            sub1.Unsubscribe(pub);
            pub.Raise();
            calledSubscribers.Should().Equal(2);

            StaticSubscriber.FooWasRaised = false;
            StaticSubscriber.Unsubscribe(pub);
            pub.Raise();
            StaticSubscriber.FooWasRaised.Should().BeFalse();

            calledSubscribers.Clear();
            sub2.Unsubscribe(pub);
            pub.Raise();
            calledSubscribers.Should().BeEmpty();

            // Make sure subscribers are not collected before the end of the test
            GC.KeepAlive(sub1);
            GC.KeepAlive(sub2);
        }
 /// <summary>
 /// Welcomes the specified publisher.
 /// </summary>
 /// <param name="pub">The publisher.</param>
 /// <param name="subStub">The subscriber stub.</param>
 public override void welcome(Publisher pub, SubscriberStub subStub)
 {
     Message greeting = Message.toSubscriber(subStub.getUUID());
     greeting.putMeta("participant", Username + ";" + Globals.Score.ToString());
     greeting.putMeta("subscriber", Globals.sub.getUUID());
     pub.send(greeting);
 }
 public Publisher DeletePublisher(Publisher publisher)
 {
     var query = Ninject.Get<DeletePublisherQuery>();
     query.Publisher = publisher;
     query.Execute();
     return publisher;
 }
示例#11
0
        public static void Main()
        {
            var serverAddress = ConfigurationManager.AppSettings.Get("ServerAddress");
            var serverPort = int.Parse(ConfigurationManager.AppSettings.Get("ServerPort"));

            var clientAddress = ConfigurationManager.AppSettings.Get("ClientAddress");
            var clientPort = int.Parse(ConfigurationManager.AppSettings.Get("ClientPort"));

            var cs = new UdpClientServer();
            var serverChannel = new UdpCommunicationChannel(cs, new ChannelConfig { Address = serverAddress, Port = serverPort });
            var clientChannel = new UdpCommunicationChannel(cs, new ChannelConfig { Address = clientAddress, Port = clientPort });

            _userService = new GitHubUserSearchService(new HttpClientFactory());
            _githubBrowser = new GithubBrowser(new HttpClientFactory());

            var userListener = new Listener<UserQuery, UserResponse>(clientChannel, serverChannel);
            userListener.ListenObservable(GetUser);

            var repoListener = new Listener<RepoQuery, RepoResponse>(clientChannel, serverChannel);
            repoListener.ListenObservable(GetRepo);

            var favListener = new Listener<FavQuery, FavResponse>(clientChannel, serverChannel);
            favListener.ListenObservable(AddToFav);

            var publisher = new Publisher<RepoNotification>(serverChannel);
            _githubBrowser.NewCommitsFeed
                .Select(c => new RepoNotification { Commit = c })
                .Subscribe(publisher);

            Console.ReadLine();
        }
示例#12
0
 static void Main(string[] args)
 {
     Publisher publish = new Publisher();
     Subscriber sub = new Subscriber(publish);
     CustemerEventArgs arg = new CustemerEventArgs(3000);
     publish.DoSomething(arg);
 }
示例#13
0
文件: Program.cs 项目: 0790486/umundo
        static void Main(string[] args)
        {
            /*
             * Make sure this path contains the umundoNativeCSharp.dll!
             */
            SetDllDirectory("C:\\Users\\sradomski\\Desktop\\build\\umundo\\lib");
            org.umundo.core.Node node = new org.umundo.core.Node();
            Publisher pub = new Publisher("pingpong");
            PingReceiver recv = new PingReceiver();
            Subscriber sub = new Subscriber("pingpong", recv);
            node.addPublisher(pub);
            node.addSubscriber(sub);

            while (true)
            {
                Message msg = new Message();
                String data = "data";
                System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                byte[] buffer = enc.GetBytes(data);
                msg.setData(buffer);
                msg.putMeta("foo", "bar");
                Console.Write("o");
                pub.send(msg);
                System.Threading.Thread.Sleep(1000);
            }
        }
示例#14
0
 public override void welcome(Publisher publisher, SubscriberStub subStub)
 {
     if (Greeter != null)
     {
         Greeter.Welcome(TypedPublisher, subStub);
     }
 }
        public void FireGenericEventArgs(
            Publisher publisher,
            Subscriber subscriber)
        {
            const int Value = 42;

            "establish a publisher firing an event with generic event args"._(() =>
                {
                    publisher = new Publisher();
                });

            "establish a subscriber listening to the event of the publisher"._(() =>
                {
                    subscriber = new Subscriber();

                    subscriber.RegisterEvent(publisher);
                });

            "when the publisher fires the event"._(() =>
                {
                    publisher.FireEvent(Value);
                });

            "it should pass value to event handler"._(() =>
                {
                    subscriber.ReceivedValue
                        .Should().Be(Value);
                });
        }
示例#16
0
 public void startListening(NodeHandle nh)
 {
     updater = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 0, 0, 100) };
     updater.Tick += Link;
     updater.Start();
     sub = nh.subscribe<m.Int32>("/camera1/tilt_info", 1, callback);
     pub = nh.advertise<m.Int32>("/camera1/tilt", 1);
 }
示例#17
0
    static void Main()
    {
        Publisher pub = new Publisher();
        Subscriber sub = new Subscriber(Message, pub);

        // Call the method that raises the event.
        pub.Execute(1000);
    }
示例#18
0
文件: Host.cs 项目: henkin/brisk
        public void Init()
        {
            // discover and wire up components

            // start inital controllers
            Publisher = new Publisher();
            Publisher.Init(_endPoint);
        }
示例#19
0
 public void publisher_can_bind_multiple_different_endpoints()
 {
     using (var publisher = new Publisher())
     {
         publisher.Bind(new RedFoxEndpoint("/path1"));
         publisher.Bind(new RedFoxEndpoint("/path2"));
     }
 }
示例#20
0
 public ActionResult Delete(int PublisherID)
 {
     myHandler = new BusinessLogicHandler();
     publisher = new Publisher();
     publisher.PublisherID = PublisherID;
     publisher = myHandler.GetPublisher(PublisherID);
     return View(publisher);
 }
示例#21
0
        static void Main()
        {
            Publisher eventPublisher = new Publisher();
            new Subscriber("Pesho", eventPublisher); //create subscribers for the event
            new Subscriber("Gosho", eventPublisher);

            eventPublisher.RaiseSampleEvent(); //sample event is raised by the publisher and handled by the subscribers
        }
示例#22
0
 public void publishers_bind_same_endpoint_twice_fails()
 {
     using (var publisher = new Publisher())
     {
         var endpoint = new RedFoxEndpoint("/path");
         publisher.Bind(endpoint);
         Assert.Throws<InvalidOperationException>(() => publisher.Bind(endpoint));
     }
 }
示例#23
0
 public void start()
 {
     if (!shutting_down && !started)
     {
         if (publisher == null)
             publisher = ROS.GlobalNodeHandle.advertise<Log>("/rosout", 0);
         publish_thread.Start();
     }
 }
        /// <summary>
        /// The default constructor.
        /// </summary>
        /// <param name="configuration">The application configuration.</param>
        public WebSyncEncodingProgressPusher(IConfigurationProvider configuration)
        {
            if (configuration == null)
                throw new ArgumentNullException("configuration");

            _channel = configuration.EncodingChannel;
            _publisher = new Publisher(new PublisherArgs { RequestUrl = configuration.WebSyncRequestUrl });
            _serializer = new JavaScriptSerializer();
        }
示例#25
0
        public void AddTopic_Success()
        {
            MRosTopicClient<std_msgs.String>.AllInstances.StartAsyncSocketBoolean = (t1, t2, t3) => Task<IObservable<byte[]>>.Factory.StartNew(Observable.Empty<byte[]>);

            var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            var pub = new Publisher<std_msgs.String>("test", "testnode");

            pub.AddTopic(sock).Wait();
        }
 public void OnConnected(Session p0)
 {
     if (_publisher == null) {
         _publisher = new Publisher(_activity, "publisher");
         _publisher.SetPublisherListener(this);
         AttachPublisherView(_publisher);
         _session.Publish(_publisher);
     }
 }
 public void OnConnected(Session p0)
 {
     if (mPublisher == null) {
         mPublisher = new Publisher(this, "publisher");
         mPublisher.SetPublisherListener(this);
         AttachPublisherView(mPublisher);
         mSession.Publish(mPublisher);
     }
 }
示例#28
0
        public void AddTopic_Error()
        {
            MRosTopicClient<std_msgs.String>.AllInstances.StartAsyncSocketBoolean =
                (t1, t2, t3) => Task<IObservable<byte[]>>.Factory.StartNew(() => { throw new InvalidOperationException("Start Error"); });

            var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            var pub = new Publisher<std_msgs.String>("test", "testnode");
            var ex = AssertEx.Throws<AggregateException>(() => pub.AddTopic(sock).Wait());
            //ex.InnerException.GetType().Is(typeof(InvalidOperationException));
        }
 static void Main()
 {
     Publisher myPublisher = new Publisher();
     Subscriber mySubscriber = new Subscriber(myPublisher);
     for (int i = 0; i < 10; i++)
     {
         myPublisher.RaiseEvent();
         Thread.Sleep(1500);
     }
 }
        public void Static_Handlers_Are_Called()
        {
            var pub = new Publisher();
            StaticSubscriber.FooWasRaised = false;
            StaticSubscriber.Subscribe(pub);

            pub.Raise();

            StaticSubscriber.FooWasRaised.Should().BeTrue();
        }
 public void Remove(Publisher Publisher)
 {
     // remove the publisher
     _bookContext.Publishers.Remove(Publisher);
     _bookContext.SaveChanges();
 }
示例#32
0
 public IEnumerable <Book> GetPublisherBooks(Publisher publisher)
 {
     return(_repository.GetPublisherBooks(publisher));
 }
示例#33
0
 public void Subscribe2(Publisher m)      //get the object of pubisher class
 {
     m.Tick += HeardIt;                   //attach listener class method to publisher class delegate object
 }
示例#34
0
 public Repository(Publisher publisher)
 {
     _handler = new MessageHandler(publisher);
 }
示例#35
0
 private void ChangeSelection()
 {
     Publisher.Publish(new SelectionChanged {
         Selection = Card
     });
 }
        public when_reporting_a_success_event_with_category()
        {
            SystemTime.Now = () => new DateTime(2013, 04, 20, 12, 13, 14);

            Publisher.Use(new TestPipelineAdapter(publisher), new PublishingContext("TEST_SYSTEM", "TEST"));
        }
 public void Remove(Publisher pubIn)
 {
     _publishers.DeleteOne(publisher => publisher.Id == pubIn.Id);
 }
示例#38
0
 public async Task UpdateAsync(Publisher publisher)
 {
     await repo.UpdateAsync(publisher);
 }
示例#39
0
 public async Task InsertAsync(Publisher publisher)
 {
     await repo.InsertAsync(publisher);
 }
示例#40
0
 public Repository(ServiceDbContext dbContext, Publisher publisher)
 {
     db       = dbContext;
     _handler = new MessageHandler(publisher);
 }
示例#41
0
        private Book get_item_from_form()
        {
            book_context = book_context ?? new Book();
            string   book_name     = book_name_textbox.Text;
            DateTime date_borrow   = new DateTime();
            DateTime date_returned = new DateTime();

            remove_id_from_changed_authors();
            //List<Author> authors = get_authors_from_string(authors_textbox.Text).ToList();
            book_context.authors = authors_list;
            Genre     genre           = new Genre(genre_textbox.Text);
            string    description     = description_textbox.Text;
            Publisher publisher       = new Publisher(publisher_textbox.Text);
            float     rating          = float.Parse(rating_textbox.Text);
            bool      was_been_readed = is_readed_checkbox.Checked;



            if (!return_date_checkbox.Checked)
            {
                date_returned = returned_date_picker.Value;
                book_context.date_returned = date_returned;
            }
            if (!borrow_date_checkbox.Checked)
            {
                date_borrow = borrow_date_picker.Value;
                book_context.date_borrowed = date_borrow;
            }



            using (var session = Database_controller.OpenSession())
            {
                using (session.BeginTransaction())
                {
                    IList <Genre> tmp = session.CreateCriteria(typeof(Genre))
                                        .List <Genre>().Where(g => g.name.Equals(genre_textbox.Text)).ToList();
                    if (tmp.Count == 0)
                    {
                        book_context.genre = new Genre(genre_textbox.Text);
                    }
                    else
                    {
                        book_context.genre = new Genre(tmp.First().id, genre_textbox.Text);
                    }
                }
            }


            using (var session = Database_controller.OpenSession())
            {
                using (session.BeginTransaction())
                {
                    IList <Publisher> tmp = session.CreateCriteria(typeof(Publisher))
                                            .List <Publisher>().Where(g => g.name.Equals(publisher_textbox.Text)).ToList();
                    if (tmp.Count == 0)
                    {
                        book_context.publisher = new Publisher(publisher_textbox.Text);
                    }
                    else
                    {
                        book_context.publisher = new Publisher(tmp.First().id, tmp.First().name);
                    }
                }
            }



            book_context.rating          = rating;
            book_context.has_been_readed = was_been_readed;
            book_context.book_name       = book_name;
            book_context.description     = description;



            return(book_context);
        }
示例#42
0
 public void Setup()
 {
     publisher = new Publisher();
 }
示例#43
0
        public async Task <IActionResult> Create(BookVM book)
        {
            if (book.Photo == null)
            {
                ModelState.AddModelError("", "Zəhmət olmasa şəkil seçin");
                List <Author>    authors    = _db.Authors.ToList();
                List <Category>  categories = _db.Categories.ToList();
                List <Publisher> publishers = _db.Publishers.ToList();
                BookVM           model      = new BookVM
                {
                    Authors    = authors,
                    Categories = categories,
                    Publishers = publishers
                };
                return(View(model));
            }
            if (!book.Photo.IsImage())
            {
                ModelState.AddModelError("", "Zəhmət olmasa şəkil seçin");
                List <Author>    authors    = _db.Authors.ToList();
                List <Category>  categories = _db.Categories.ToList();
                List <Publisher> publishers = _db.Publishers.ToList();
                BookVM           model      = new BookVM
                {
                    Authors    = authors,
                    Categories = categories,
                    Publishers = publishers
                };
                return(View(model));
            }
            if (!book.Photo.MaxLength(1024))
            {
                ModelState.AddModelError("", "Faylın ölçüsü 1 MB-dan az olmalıdır");
                List <Author>    authors    = _db.Authors.ToList();
                List <Category>  categories = _db.Categories.ToList();
                List <Publisher> publishers = _db.Publishers.ToList();
                BookVM           model      = new BookVM
                {
                    Authors    = authors,
                    Categories = categories,
                    Publishers = publishers
                };
                return(View(model));
            }
            string price = Request.Form["Price"];

            price = price.Replace('.', ',');
            decimal originalPrice = 0;

            originalPrice = decimal.Round(Convert.ToDecimal(price) * 1, 2);
            Book newBook = new Book
            {
                Name        = book.Name,
                Slug        = book.Slug,
                Description = book.Description,
                Price       = originalPrice,
                Count       = book.Count
            };
            Book existBook = _db.Books.FirstOrDefault(b => b.Name.ToLower().Trim() == book.Name.ToLower().Trim());

            if (existBook != null)
            {
                ModelState.AddModelError("", "Bu kitab mövcuddur");
                List <Author>    authors    = _db.Authors.ToList();
                List <Category>  categories = _db.Categories.ToList();
                List <Publisher> publishers = _db.Publishers.ToList();
                BookVM           model      = new BookVM
                {
                    Authors    = authors,
                    Categories = categories,
                    Publishers = publishers
                };
                return(View(model));
            }
            newBook.ImagePath = await book.Photo.SaveImg(_env.WebRootPath, "image");

            string authorsList = Request.Form["authors"];

            if (authorsList == null)
            {
                ModelState.AddModelError("", "Zəhmət olmasa yazar seçin");
                List <Author>    authors    = _db.Authors.ToList();
                List <Category>  categories = _db.Categories.ToList();
                List <Publisher> publishers = _db.Publishers.ToList();
                BookVM           model      = new BookVM
                {
                    Authors    = authors,
                    Categories = categories,
                    Publishers = publishers
                };
                return(View(model));
            }
            List <BookAuthor> bookAuthors = new List <BookAuthor>();

            string[]   authorArr = authorsList.Split(",");
            List <int> authorIds = new List <int>();

            foreach (string authorId in authorArr)
            {
                authorIds.Add(int.Parse(authorId));
            }

            foreach (int id in authorIds)
            {
                bookAuthors.Add(new BookAuthor
                {
                    BookId   = newBook.Id,
                    AuthorId = id
                });
            }

            string categoryList = Request.Form["categories"];

            if (categoryList == null)
            {
                ModelState.AddModelError("", "Zəhmət olmasa kateqoriya seçin");
                List <Author>    authors    = _db.Authors.ToList();
                List <Category>  categories = _db.Categories.ToList();
                List <Publisher> publishers = _db.Publishers.ToList();
                BookVM           model      = new BookVM
                {
                    Authors    = authors,
                    Categories = categories,
                    Publishers = publishers
                };
                return(View(model));
            }
            List <BookCategory> bookCategories = new List <BookCategory>();

            string[]   categoryArr = categoryList.Split(",");
            List <int> categoryIds = new List <int>();

            foreach (string categoryId in categoryArr)
            {
                categoryIds.Add(int.Parse(categoryId));
            }

            foreach (int id in categoryIds)
            {
                bookCategories.Add(new BookCategory
                {
                    BookId     = newBook.Id,
                    CategoryId = id
                });
            }
            BookFeature bookFeature = new BookFeature
            {
                PublishingPlace    = book.PublishingPlace,
                PublishingDate     = book.PublishingDate,
                PublishingLanguage = book.PublishingLanguage,
                OriginalLanguage   = book.OriginalLanguage,
                Translator         = book.Translator
            };
            string    publisherId = Request.Form["publishers"];
            Publisher publisher   = _db.Publishers.FirstOrDefault(p => p.Id == int.Parse(publisherId));

            if (publisher == null)
            {
                ModelState.AddModelError("", "Zəhmət olmasa yayın evi seçin");
                List <Author>    authors    = _db.Authors.ToList();
                List <Category>  categories = _db.Categories.ToList();
                List <Publisher> publishers = _db.Publishers.ToList();
                BookVM           model      = new BookVM
                {
                    Authors    = authors,
                    Categories = categories,
                    Publishers = publishers
                };
                return(View(model));
            }
            publisher.BookCount++;
            newBook.PublisherId    = publisher.Id;
            newBook.BookAuthors    = bookAuthors;
            newBook.BookCategories = bookCategories;
            newBook.BookFeature    = bookFeature;
            _db.Books.Add(newBook);
            await _db.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
示例#44
0
 public void Update(Publisher publisher)
 {
     repo.Update(publisher);
 }
 public Publisher Add(Publisher Publisher)
 {
     _bookContext.Publishers.Add(Publisher);
     _bookContext.SaveChanges();
     return(Publisher);
 }
示例#46
0
 public void Insert(Publisher publisher)
 {
     repo.Insert(publisher);
 }
        public void Update(string id, Publisher pubIn)
        {
            var pubId = new ObjectId(id);

            _publishers.ReplaceOne(publisher => publisher.Id == pubId, pubIn);
        }
        public IList <ImportLogEntry> Publish(Guid root, PublishMode mode = PublishMode.Smart,
                                              bool publishRelatedItems    = true,
                                              bool republishAll           = false)
        {
            var logs     = new List <ImportLogEntry>();
            var rootItem = this.SitecoreContext.Database?.GetItem(new ID(root));

            if (rootItem == null)
            {
                logs.Add(new ImportLogEntry {
                    Level = MessageLevel.Error, Message = $"Item {root} cannot be found"
                });
                return(logs);
            }

            try
            {
                logs.Add(new ImportLogEntry
                {
                    Level   = MessageLevel.Info,
                    Message =
                        $"Publishing item \"{rootItem.Paths.FullPath}\" [ID:{rootItem.ID}], pulishing mode: {mode}..."
                });
                var targetDatabase = Factory.GetDatabase(Constants.Sitecore.Databases.Web);
                var options        =
                    new PublishOptions(rootItem.Database, targetDatabase, mode, rootItem.Language, DateTime.Now)
                {
                    RootItem            = rootItem,
                    Deep                = true,
                    PublishRelatedItems = publishRelatedItems,
                    RepublishAll        = republishAll,
                };
                var sw = new Stopwatch();
                sw.Start();
                var publisher     = new Publisher(options);
                var publishResult = publisher.PublishWithResult();
                sw.Stop();
                var sb = new StringBuilder();
                sb.AppendLine($"Item  \"{rootItem.Name}\" [ID:{rootItem.ID}] has been published.\r\n");
                sb.AppendLine("Statistics:");
                sb.AppendLine($"Items skipped: {publishResult.Statistics.Skipped}");
                sb.AppendLine($"Items created: {publishResult.Statistics.Created}");
                sb.AppendLine($"Items updated: {publishResult.Statistics.Updated}");
                sb.AppendLine($"Items deleted: {publishResult.Statistics.Deleted}");
                sb.AppendLine($"Time taken: {sw.ElapsedMilliseconds} ms");
                logs.Add(new ImportLogEntry {
                    Level = MessageLevel.Info, Message = sb.ToString()
                });
            }
            catch (Exception exception)
            {
                logs.Add(new ImportLogEntry
                {
                    Level   = MessageLevel.Error,
                    Message =
                        $"An error has occurred while publishing an item \"{rootItem.Name}\" [ID:{rootItem.ID}]. Message: {exception.GetAllMessages()}"
                });
            }

            return(logs);
        }
 public Publisher Create(Publisher publisher)
 {
     _publishers.InsertOne(publisher);
     return(publisher);
 }
示例#50
0
        public async Task <IActionResult> Edit(int?id, BookVM editedBook)
        {
            if (id == null)
            {
                return(NotFound());
            }
            Book book = _db.Books.Include(b => b.BookAuthors).ThenInclude(ba => ba.Author).Include(b => b.Publisher).Include(b => b.BookCategories).ThenInclude(bc => bc.Category).Include(b => b.BookFeature).FirstOrDefault(b => b.Id == id);

            if (book == null)
            {
                return(NotFound());
            }
            if (editedBook.Photo == null)
            {
                Book existBook = _db.Books.FirstOrDefault(b => b.Name.ToLower().Trim() == editedBook.Book.Name.ToLower().Trim());
                if (existBook != null)
                {
                    if (book.Name.ToLower().Trim() != existBook.Name.ToLower().Trim())
                    {
                        ModelState.AddModelError("", "Bu kitab mövcuddur");
                        List <Author>    authors    = _db.Authors.ToList();
                        List <Category>  categories = _db.Categories.ToList();
                        List <Publisher> publishers = _db.Publishers.ToList();
                        BookVM           model      = new BookVM
                        {
                            Book       = book,
                            Authors    = authors,
                            Categories = categories,
                            Publishers = publishers
                        };
                        return(View(model));
                    }
                }
                string price = Request.Form["Book.Price"];
                price = price.Replace('.', ',');
                decimal originalPrice = 0;
                originalPrice    = decimal.Round(Convert.ToDecimal(price) * 1, 2);
                book.Name        = editedBook.Book.Name;
                book.Slug        = editedBook.Book.Slug;
                book.Count       = editedBook.Book.Count;
                book.Price       = originalPrice;
                book.Description = editedBook.Book.Description;
                string authorsList = Request.Form["authors"];
                if (authorsList == null)
                {
                    ModelState.AddModelError("", "Zəhmət olmasa yazar seçin");
                    List <Author>    authors    = _db.Authors.ToList();
                    List <Category>  categories = _db.Categories.ToList();
                    List <Publisher> publishers = _db.Publishers.ToList();
                    BookVM           model      = new BookVM
                    {
                        Book       = book,
                        Authors    = authors,
                        Categories = categories,
                        Publishers = publishers
                    };
                    return(View(model));
                }
                List <BookAuthor> bookAuthors = new List <BookAuthor>();
                string[]          authorArr   = authorsList.Split(",");
                List <int>        authorIds   = new List <int>();
                foreach (string authorId in authorArr)
                {
                    authorIds.Add(int.Parse(authorId));
                }

                foreach (int authorId in authorIds)
                {
                    bookAuthors.Add(new BookAuthor
                    {
                        BookId   = book.Id,
                        AuthorId = authorId
                    });
                }

                string categoryList = Request.Form["categories"];
                if (categoryList == null)
                {
                    ModelState.AddModelError("", "Zəhmət olmasa kateqoriya seçin");
                    List <Author>    authors    = _db.Authors.ToList();
                    List <Category>  categories = _db.Categories.ToList();
                    List <Publisher> publishers = _db.Publishers.ToList();
                    BookVM           model      = new BookVM
                    {
                        Book       = book,
                        Authors    = authors,
                        Categories = categories,
                        Publishers = publishers
                    };
                    return(View(model));
                }
                List <BookCategory> bookCategories = new List <BookCategory>();
                string[]            categoryArr    = categoryList.Split(",");
                List <int>          categoryIds    = new List <int>();
                foreach (string categoryId in categoryArr)
                {
                    categoryIds.Add(int.Parse(categoryId));
                }

                foreach (int categoryId in categoryIds)
                {
                    bookCategories.Add(new BookCategory
                    {
                        BookId     = book.Id,
                        CategoryId = categoryId
                    });
                }
                BookFeature bookFeature = new BookFeature
                {
                    PublishingPlace    = editedBook.Book.BookFeature.PublishingPlace,
                    PublishingDate     = editedBook.Book.BookFeature.PublishingDate,
                    PublishingLanguage = editedBook.Book.BookFeature.PublishingLanguage,
                    OriginalLanguage   = editedBook.Book.BookFeature.OriginalLanguage,
                    Translator         = editedBook.Book.BookFeature.Translator
                };
                Publisher oldPublisher = new Publisher();
                Publisher newPublisher = new Publisher();
                string    publisherId  = Request.Form["publishers"];
                if (book.PublisherId != int.Parse(publisherId))
                {
                    oldPublisher = _db.Publishers.FirstOrDefault(p => p.Id == book.PublisherId);
                    oldPublisher.BookCount--;
                    newPublisher = _db.Publishers.FirstOrDefault(p => p.Id == int.Parse(publisherId));
                    newPublisher.BookCount++;
                    book.PublisherId = newPublisher.Id;
                }
                book.BookAuthors    = bookAuthors;
                book.BookCategories = bookCategories;
                book.BookFeature    = bookFeature;
                await _db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            else
            {
                if (!editedBook.Photo.IsImage())
                {
                    ModelState.AddModelError("", "Zəhmət olmasa şəkil seçin");
                    List <Author>    authors    = _db.Authors.ToList();
                    List <Category>  categories = _db.Categories.ToList();
                    List <Publisher> publishers = _db.Publishers.ToList();
                    BookVM           model      = new BookVM
                    {
                        Book       = book,
                        Authors    = authors,
                        Categories = categories,
                        Publishers = publishers
                    };
                    return(View(model));
                }
                if (!editedBook.Photo.MaxLength(1024))
                {
                    ModelState.AddModelError("", "Faylın ölçüsü 1 MB-dan az olmalıdır");
                    List <Author>    authors    = _db.Authors.ToList();
                    List <Category>  categories = _db.Categories.ToList();
                    List <Publisher> publishers = _db.Publishers.ToList();
                    BookVM           model      = new BookVM
                    {
                        Book       = book,
                        Authors    = authors,
                        Categories = categories,
                        Publishers = publishers
                    };
                    return(View(model));
                }
                Book existBook = _db.Books.FirstOrDefault(b => b.Name.ToLower().Trim() == editedBook.Book.Name.ToLower().Trim());
                if (existBook != null)
                {
                    if (book.Name.ToLower().Trim() != existBook.Name.ToLower().Trim())
                    {
                        ModelState.AddModelError("", "Bu kitab mövcuddur");
                        List <Author>    authors    = _db.Authors.ToList();
                        List <Category>  categories = _db.Categories.ToList();
                        List <Publisher> publishers = _db.Publishers.ToList();
                        BookVM           model      = new BookVM
                        {
                            Book       = book,
                            Authors    = authors,
                            Categories = categories,
                            Publishers = publishers
                        };
                        return(View(model));
                    }
                }
                Helpers.Helper.DeleteImg(_env.WebRootPath, "image", book.ImagePath);
                book.ImagePath = await editedBook.Photo.SaveImg(_env.WebRootPath, "image");

                string price = Request.Form["Book.Price"];
                price = price.Replace('.', ',');
                decimal originalPrice = 0;
                originalPrice    = decimal.Round(Convert.ToDecimal(price) * 1, 2);
                book.Name        = editedBook.Book.Name;
                book.Slug        = editedBook.Book.Slug;
                book.Count       = editedBook.Book.Count;
                book.Price       = originalPrice;
                book.Description = editedBook.Book.Description;
                string authorsList = Request.Form["authors"];
                if (authorsList == null)
                {
                    ModelState.AddModelError("", "Zəhmət olmasa yazar seçin");
                    List <Author>    authors    = _db.Authors.ToList();
                    List <Category>  categories = _db.Categories.ToList();
                    List <Publisher> publishers = _db.Publishers.ToList();
                    BookVM           model      = new BookVM
                    {
                        Book       = book,
                        Authors    = authors,
                        Categories = categories,
                        Publishers = publishers
                    };
                    return(View(model));
                }
                List <BookAuthor> bookAuthors = new List <BookAuthor>();
                string[]          authorArr   = authorsList.Split(",");
                List <int>        authorIds   = new List <int>();
                foreach (string authorId in authorArr)
                {
                    authorIds.Add(int.Parse(authorId));
                }

                foreach (int authorId in authorIds)
                {
                    bookAuthors.Add(new BookAuthor
                    {
                        BookId   = book.Id,
                        AuthorId = authorId
                    });
                }

                string categoryList = Request.Form["categories"];
                if (categoryList == null)
                {
                    ModelState.AddModelError("", "Zəhmət olmasa kateqoriya seçin");
                    List <Author>    authors    = _db.Authors.ToList();
                    List <Category>  categories = _db.Categories.ToList();
                    List <Publisher> publishers = _db.Publishers.ToList();
                    BookVM           model      = new BookVM
                    {
                        Book       = book,
                        Authors    = authors,
                        Categories = categories,
                        Publishers = publishers
                    };
                    return(View(model));
                }
                List <BookCategory> bookCategories = new List <BookCategory>();
                string[]            categoryArr    = categoryList.Split(",");
                List <int>          categoryIds    = new List <int>();
                foreach (string categoryId in categoryArr)
                {
                    categoryIds.Add(int.Parse(categoryId));
                }

                foreach (int categoryId in categoryIds)
                {
                    bookCategories.Add(new BookCategory
                    {
                        BookId     = book.Id,
                        CategoryId = categoryId
                    });
                }
                BookFeature bookFeature = new BookFeature
                {
                    PublishingPlace    = editedBook.Book.BookFeature.PublishingPlace,
                    PublishingDate     = editedBook.Book.BookFeature.PublishingDate,
                    PublishingLanguage = editedBook.Book.BookFeature.PublishingLanguage,
                    OriginalLanguage   = editedBook.Book.BookFeature.OriginalLanguage,
                    Translator         = editedBook.Book.BookFeature.Translator
                };
                Publisher oldPublisher = new Publisher();
                Publisher newPublisher = new Publisher();
                string    publisherId  = Request.Form["publishers"];
                if (book.PublisherId != int.Parse(publisherId))
                {
                    oldPublisher = _db.Publishers.FirstOrDefault(p => p.Id == book.PublisherId);
                    oldPublisher.BookCount--;
                    newPublisher = _db.Publishers.FirstOrDefault(p => p.Id == int.Parse(publisherId));
                    newPublisher.BookCount++;
                    book.PublisherId = newPublisher.Id;
                }
                book.BookAuthors    = bookAuthors;
                book.BookCategories = bookCategories;
                book.BookFeature    = bookFeature;
                await _db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
        }
示例#51
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new IdentityUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    var publisher = new Publisher
                    {
                        Email = user.Email,
                        Name  = Input.Name,
                    };

                    dataContext.Add(publisher);

                    dataContext.SaveChanges();
                    var roleExistsResult = await _roleManager.RoleExistsAsync("publisher");

                    if (!roleExistsResult)
                    {
                        var roleReuslt = await _roleManager.CreateAsync(new IdentityRole("publisher"));

                        if (roleReuslt.Succeeded)
                        {
                            await _userManager.AddToRoleAsync(user, "publisher");
                        }
                    }
                    else
                    {
                        await _userManager.AddToRoleAsync(user, "publisher");
                    }



                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
示例#52
0
        static void Main(string[] args)
        {
            SetupEnviroment();
            var publisher = new Publisher("Publisher-1", ConsoleColor.White);

            publisher.WhenPublish = (sender, channel) =>
            {
                for (int i = 1; i <= 15; i++)
                {
                    var properties = channel.CreateBasicProperties();

                    string message = $"Message {i}";
                    var    body    = Encoding.UTF8.GetBytes(message);
                    channel.BasicPublish(exchange: "",
                                         routingKey: "DeadLetterExample.Queue1",
                                         basicProperties: null,
                                         body: body);
                    WriteLine(sender, $"[{sender.Name}] Sent: {message}");
                    Thread.Sleep(1000);
                }
            };

            var consumer1 = new Consumer("Consumer-1", "DeadLetterExample.Queue1", ConsoleColor.Green, false);

            consumer1.OnReceive = (sender, eventBasicConsumer, ev) =>
            {
                var body    = ev.Body;
                var message = Encoding.UTF8.GetString(body);
                try
                {
                    int n = int.Parse(message.Replace("Message ", "").Trim());
                    if (n == 13)
                    {
                        throw new Exception("Fail on 13");
                    }
                    if (n % 4 == 0)  //fail 4,8,12...
                    {
                        WriteLine(sender, $" [{sender.Name}] rejected {message}");
                        eventBasicConsumer.Model.BasicReject(ev.DeliveryTag, false);
                    }
                    else
                    {
                        //confirm
                        WriteLine(sender, $" [{sender.Name}] Received {message}");
                        eventBasicConsumer.Model.BasicAck(ev.DeliveryTag, false);
                    }
                }
                catch (Exception ex)
                {
                    WriteLine(sender, $" [{sender.Name}] failed with exception '{ex.Message}' on message {message}");
                    Thread.Sleep(5000);
                }
            };


            //var consumer2 = new Consumer("Consumer-2", "HeadersExample.Queue2", ConsoleColor.Cyan);
            var consumer2 = new Consumer("Consumer-Errors", "DeadLetterExample.ErrorsQueue", ConsoleColor.Red, false);

            consumer2.OnReceive = (sender, eventBasicConsumer, ev) =>
            {
                var body    = ev.Body;
                var message = Encoding.UTF8.GetString(body);
                try
                {
                    if (ev.BasicProperties.Headers.ContainsKey("retry-count"))
                    {
                        int retryCount = (int)ev.BasicProperties.Headers["retry-count"];
                        if (retryCount >= 2)
                        {
                            WriteLine(sender, $" [{sender.Name}] REJECTED DEFINITELY {message}");
                            eventBasicConsumer.Model.BasicReject(ev.DeliveryTag, false);
                            return;
                        }
                    }



                    var factory = new ConnectionFactory()
                    {
                        HostName = "localhost", UserName = "******", Password = "******"
                    };
                    using (var connection = factory.CreateConnection())
                        using (var channel = connection.CreateModel())
                        {
                            var basicProperties = channel.CreateBasicProperties();
                            if (ev.BasicProperties.IsMessageIdPresent())
                            {
                                basicProperties.MessageId = ev.BasicProperties.MessageId;
                            }

                            basicProperties.Persistent = ev.BasicProperties.Persistent;
                            if (ev.BasicProperties.IsTimestampPresent())
                            {
                                basicProperties.Timestamp = ev.BasicProperties.Timestamp;
                            }
                            if (ev.BasicProperties.IsExpirationPresent())
                            {
                                basicProperties.Expiration = ev.BasicProperties.Expiration;
                            }
                            if (ev.BasicProperties.IsDeliveryModePresent())
                            {
                                basicProperties.DeliveryMode = ev.BasicProperties.DeliveryMode;
                            }
                            if (ev.BasicProperties.IsContentTypePresent())
                            {
                                basicProperties.ContentType = ev.BasicProperties.ContentType;
                            }
                            if (ev.BasicProperties.IsContentEncodingPresent())
                            {
                                basicProperties.ContentEncoding = ev.BasicProperties.ContentEncoding;
                            }
                            if (ev.BasicProperties.IsClusterIdPresent())
                            {
                                basicProperties.ClusterId = ev.BasicProperties.ClusterId;
                            }
                            basicProperties.Headers = new Dictionary <string, object>();// ev.BasicProperties.Headers);
                            int i = 0;
                            if (ev.BasicProperties.Headers.ContainsKey("retry-count"))
                            {
                                i = (int)ev.BasicProperties.Headers["retry-count"];
                            }
                            i = i + 1;
                            basicProperties.Headers.Add("retry-count", i);
                            var newBody = new byte[ev.Body.Length];
                            ev.Body.CopyTo(newBody, 0);
                            channel.BasicPublish("", "DeadLetterExample.Queue1", basicProperties, newBody);
                            eventBasicConsumer.Model.BasicAck(ev.DeliveryTag, false);
                            WriteLine(sender, $" [{sender.Name}] REPUBLISHED {message} TO QUEUE1");
                        }
                }
                catch (Exception ex)
                {
                    WriteLine(sender, $" [{sender.Name}] failed with exception '{ex.Message}' on message {message}");
                    Thread.Sleep(5000);
                }
            };


            consumer1.Start();
            consumer2.Start();
            publisher.Start();
            Console.WriteLine(" Press [enter] to exit.");
        }
示例#53
0
 private void HeardIt(Publisher m, EventArgs e)       //subscriber class method
 {
     System.Console.WriteLine("Heard It by Listener2");
 }
        private void RunExample(
            int domainId       = 0,
            uint lotsToProcess = 10)
        {
            // Exercise #1.1: Add QoS provider

            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // Exercise #1.2: Load DomainParticipant QoS profile
            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(domainId);

            // A Topic has a name and a datatype. Create a Topic named
            // "ChocolateLotState" with type ChocolateLotState.
            Topic <ChocolateLotState> lotStateTopic = participant.CreateTopic <ChocolateLotState>(
                CHOCOLATE_LOT_STATE_TOPIC.Value);
            // Add a Topic for Temperature to this application
            Topic <Temperature> temperatureTopic = participant.CreateTopic <Temperature>(
                CHOCOLATE_TEMPERATURE_TOPIC.Value);

            // A Publisher allows an application to create one or more DataWriters
            // Publisher QoS is configured in USER_QOS_PROFILES.xml
            Publisher publisher = participant.CreatePublisher();

            // This DataWriter writes data on Topic "ChocolateLotState"
            // Exercise #4.1: Load ChocolateLotState DataWriter QoS profile after
            // debugging incompatible QoS
            DataWriter <ChocolateLotState> lotStateWriter =
                publisher.CreateDataWriter(lotStateTopic);

            // A Subscriber allows an application to create one or more DataReaders
            // Subscriber QoS is configured in USER_QOS_PROFILES.xml
            Subscriber subscriber = participant.CreateSubscriber();

            // Create DataReader of Topic "ChocolateLotState".
            // Exercise #1.3: Update the lotStateReader and temperatureReader
            // to use correct QoS
            DataReader <ChocolateLotState> lotStateReader =
                subscriber.CreateDataReader(lotStateTopic);

            // Add a DataReader for Temperature to this application
            DataReader <Temperature> temperatureReader =
                subscriber.CreateDataReader(temperatureTopic);

            // Obtain the DataReader's Status Condition
            StatusCondition temperatureStatusCondition = temperatureReader.StatusCondition;

            temperatureStatusCondition.EnabledStatuses = StatusMask.DataAvailable;

            // Associate a handler with the status condition. This will run when the
            // condition is triggered, in the context of the dispatch call (see below)
            temperatureStatusCondition.Triggered += _ => MonitorTemperature(temperatureReader);

            // Do the same with the lotStateReader's StatusCondition
            StatusCondition lotStateStatusCondition = lotStateReader.StatusCondition;

            lotStateStatusCondition.EnabledStatuses = StatusMask.DataAvailable;

            int lotsProcessed = 0;

            lotStateStatusCondition.Triggered +=
                _ => lotsProcessed            += MonitorLotState(lotStateReader);

            // Create a WaitSet and attach the StatusCondition
            var waitset = new WaitSet();

            waitset.AttachCondition(lotStateStatusCondition);

            // Add the new DataReader's StatusCondition to the Waitset
            waitset.AttachCondition(temperatureStatusCondition);

            // Start publishing in a separate thread
            var startLotTask = Task.Run(() => PublishStartLot(lotStateWriter, lotsToProcess));

            while (!shutdownRequested && lotsProcessed < lotsToProcess)
            {
                waitset.Dispatch(Duration.FromSeconds(4));
            }

            startLotTask.Wait();
        }
示例#55
0
        public async Task DropReconnectTest()
        {
            if (TestRunnerInfo.IsBuildAgent())
            {
                // TODO: Fix intermittent failures on GitHub
                return;
            }

            var serving = await WebSocketHost.ServeAsync();

            var tp = Services.GetRequiredService <ITimeService>();

            Debug.WriteLine("0");
            var pub = await Publisher.PublishAsync(_ => tp.GetTimeAsync());

            var rep = Replicator.GetOrAdd <DateTime>(pub.Ref);

            Debug.WriteLine("1");
            await rep.RequestUpdateAsync().AsAsyncFunc()
            .Should().CompleteWithinAsync(TimeSpan.FromMinutes(1));

            Debug.WriteLine("2");
            var state = Replicator.GetPublisherConnectionState(pub.Publisher.Id);

            state.Computed.IsConsistent().Should().BeTrue();
            Debug.WriteLine("3");
            await state.Computed.UpdateAsync(false);

            Debug.WriteLine("4");
            state.Should().Be(Replicator.GetPublisherConnectionState(pub.Publisher.Id));
            state.Value.Should().BeTrue();

            Debug.WriteLine("WebServer: stopping.");
            await serving.DisposeAsync();

            Debug.WriteLine("WebServer: stopped.");

            // First try -- should fail w/ WebSocketException or ChannelClosedException
            Debug.WriteLine("5");
            await rep.RequestUpdateAsync().AsAsyncFunc()
            .Should().ThrowAsync <Exception>();

            Debug.WriteLine("6");
            state.Should().Be(Replicator.GetPublisherConnectionState(pub.Publisher.Id));
            await state.Computed.UpdateAsync(false);

            Debug.WriteLine("7");
            state.Should().Be(Replicator.GetPublisherConnectionState(pub.Publisher.Id));
            state.Error.Should().BeAssignableTo <Exception>();

            // Second try -- should fail w/ WebSocketException
            Debug.WriteLine("8");
            await rep.Computed.UpdateAsync(false).AsAsyncFunc()
            .Should().ThrowAsync <WebSocketException>();

            Debug.WriteLine("9");
            rep.UpdateError.Should().BeOfType <WebSocketException>();
            await state.Computed.UpdateAsync(false);

            Debug.WriteLine("10");
            state.Error.Should().BeOfType <WebSocketException>();

            Debug.WriteLine("WebServer: starting.");
            serving = await WebSocketHost.ServeAsync();

            await Task.Delay(1000);

            Debug.WriteLine("WebServer: started.");

            Debug.WriteLine("11");
            await rep.RequestUpdateAsync().AsAsyncFunc()
            .Should().CompleteWithinAsync(TimeSpan.FromMinutes(1));

            Debug.WriteLine("12");
            await state.Computed.UpdateAsync(false);

            Debug.WriteLine("13");
            state.Value.Should().BeTrue();

            Debug.WriteLine("100");
            await serving.DisposeAsync();

            Debug.WriteLine("101");
        }
示例#56
0
        // Exercise #4.4: Add monitor_temperature function

        private void RunExample(
            int domainId       = 0,
            uint lotsToProcess = 10)
        {
            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(domainId);

            // A Topic has a name and a datatype. Create a Topic named
            // "ChocolateLotState" with type ChocolateLotState.
            Topic <ChocolateLotState> lotStateTopic = participant.CreateTopic <ChocolateLotState>(
                "ChocolateLotState");
            // Exercise #4.1: Add a Topic for Temperature to this application

            // A Publisher allows an application to create one or more DataWriters
            // Publisher QoS is configured in USER_QOS_PROFILES.xml
            Publisher publisher = participant.CreatePublisher();

            // This DataWriter writes data on Topic "ChocolateLotState"
            // DataWriter QoS is configured in USER_QOS_PROFILES.xml
            DataWriter <ChocolateLotState> lotStateWriter =
                publisher.CreateDataWriter(lotStateTopic);

            // A Subscriber allows an application to create one or more DataReaders
            // Subscriber QoS is configured in USER_QOS_PROFILES.xml
            Subscriber subscriber = participant.CreateSubscriber();

            // Create DataReader of Topic "ChocolateLotState".
            // DataReader QoS is configured in USER_QOS_PROFILES.xml
            DataReader <ChocolateLotState> lotStateReader =
                subscriber.CreateDataReader(lotStateTopic);

            // Exercise #4.2: Add a DataReader for Temperature to this application

            // Obtain the DataReader's Status Condition
            StatusCondition lotStateStatusCondition = lotStateReader.StatusCondition;

            // Enable the 'data available' status.
            lotStateStatusCondition.EnabledStatuses = StatusMask.DataAvailable;

            int lotsProcessed = 0;

            lotStateStatusCondition.Triggered +=
                _ => lotsProcessed            += MonitorLotState(lotStateReader);

            // Create a WaitSet and attach the StatusCondition
            WaitSet waitset = new WaitSet();

            waitset.AttachCondition(lotStateStatusCondition);

            // Exercise #4.3: Add the new DataReader's StatusCondition to the Waitset

            // Start publishing in a separate thread
            var startLotTask = Task.Run(() => PublishStartLot(lotStateWriter, lotsToProcess));

            while (!shutdownRequested && lotsProcessed < lotsToProcess)
            {
                waitset.Dispatch(Duration.FromSeconds(4));
            }

            startLotTask.Wait();
        }
示例#57
0
文件: Test.cs 项目: 751620780/Peach
 void publishers_AddEvent(OrderedDictionary <string, Publisher> sender, string key, Publisher value)
 {
     value.Test = this;
 }
示例#58
0
        public static async Task Run(
            [ServiceBusTrigger("q-notifications", Connection = "SB-Queue-In-AppSettings")]
            string notificationMsg,
            ILogger log,
            ExecutionContext context)
        {
            log.LogInformation("Incoming message from queue q-notifications");
            // TODO: This should be done with a DURABLE function
            // or implement compensation

            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            var sbConnectionString = config["Values:SB-Queue-In-AppSettings"];

            var jsonFormatter = new JsonEventFormatter();
            var inboundEvent  = jsonFormatter.DecodeStructuredEvent(Encoding.UTF8.GetBytes(notificationMsg));

            log.LogInformation($" message type : { inboundEvent.Type}");
            var     notification = JsonConvert.DeserializeObject <ObjectStatus>((string)inboundEvent.Data);
            dynamic jPatch       = new JObject();

            jPatch.op    = "replace";
            jPatch.path  = "/status";
            jPatch.value = notification.Status;
            var patchArray = new JArray(jPatch);

            log.LogInformation($" Status to be changed for the object {notification.Id}  value: { notification.Status}");
            var text = new AsciiArt(notification.Status);

            log.LogInformation(text.ToString());

            var httpContent = new StringContent(patchArray.ToString(), Encoding.UTF8, "application/json-patch+json");
            var url         = string.Format(config["Values:ApiUpdateOrderUrl"], notification.Id);

            //TODO add authentication
            //_httpClient.DefaultRequestHeaders.Authorization =new AuthenticationHeaderValue("Bearer", "to be added");

            log.LogInformation(" Call the web api ...");
            var response = await Policy
                           .HandleResult <HttpResponseMessage>(message => !message.IsSuccessStatusCode)
                           .WaitAndRetryAsync(new[]
            {
                TimeSpan.FromSeconds(1),
                TimeSpan.FromSeconds(2),
                TimeSpan.FromSeconds(5)
            }, (result, timeSpan, retryCount, ctx) =>
            {
                log.LogWarning($"Request failed with {result.Result.StatusCode}. Waiting {timeSpan} before next retry. Attempt #{retryCount}");
            })
                           .ExecuteAsync(() => _httpClient.PatchAsync(url, httpContent));

            if (!response.IsSuccessStatusCode)
            {
                var pub    = new Publisher("q-errors", sbConnectionString);
                var result = pub.SendMessagesAsync(notificationMsg);
            }

            return;
        }
示例#59
0
 public override void OnBridgeSetup(BridgeInstance bridge)
 {
     Bridge  = bridge;
     Publish = bridge.AddPublisher <UltrasonicData>(Topic);
 }
示例#60
0
 public void TearDown()
 {
     publisher = null;
 }