Esempio n. 1
0
        public void ConnectPortUdpSync()
        {
            Byte[] sendBytes = Encoding.ASCII.GetBytes("?");
            while (true)
            {
                PublisherClass itemList = new PublisherClass();
                Parallel.ForEach(SynchronePortUdp.Keys, updateRate =>
                {
                    foreach (Tag tag in SynchronePortUdp[updateRate])
                    {
                        Item element      = new Item();
                        DateTime DateD    = DateTime.Now;
                        element.Address   = tag.Ip_Address + ":" + tag.Port;
                        element.TagName   = tag.TagKey;
                        element.TimeStamp = DateD;
                        PingUdpPort(tag, sendBytes).Wait();
                        if (tag.is_open == true)
                        {
                            element.is_open = true;
                        }
                        else
                        {
                            element.is_open = false;
                        }
                        element.Description = tag.PortDescription;

                        itemList.Payload.Add(element);
                    }
                    itemList.SchemaId = IOHelper.AgentConfig.Agent_SchemaID;
                    Publisherqueue.Add(itemList);
                    Thread.Sleep(updateRate);
                });
            }
        }
Esempio n. 2
0
        public AddBookForm(int?bookclassnum, string bookname, PublisherClass publisher, TypeClass type, List <AuthorClass> authors)
        {
            isSave = false;
            InitializeComponent();
            UpdateCombo();

            if (bookclassnum == null)
            {
                cb_NoUchLit.Checked = true;
            }
            else
            {
                NUD_Class.Value = Convert.ToInt32(bookclassnum);
            }
            //вывод названия книги из импорта в соответствующее окно
            tb_bookname.Text = bookname;

            //заполнение соответствующего окошка издательством из импорта
            int pI = cb_publisher.Items.Add(publisher);

            cb_publisher.SelectedIndex = pI;
            cb_publisher.Enabled       = false;

            //То же, что и издательство
            int tI = cb_type.Items.Add(type);

            cb_type.SelectedIndex = tI;
            cb_type.Enabled       = false;

            //Автор также
            lb_author.Items.AddRange(authors.ToArray());
            lb_author.Enabled    = false;
            bt_add_autor.Enabled = false;
            cb_Author.Enabled    = false;
        }
Esempio n. 3
0
    public static void Main(string[] args)
    {
        // Subscribe to the event by assigning the method you want called when the event is fired ( CallBack() ) to the event delegate
        PublisherClass pub = new PublisherClass();

        pub.TheEvent += OnDisplay;

        // Call
        pub.DisplayData();
    }
        static void Main(string[] args)
        {
            var subscriber = new SubscriberClass();
            var publisher  = new PublisherClass();

            publisher.DoWork();
            publisher.DoAnotherWork();

            Console.Read();
        }
Esempio n. 5
0
        public void ConnectPortTcpASync()
        {
            Parallel.ForEach(ASynchronePortTcp.Keys, updateRate =>
            {
                while (true)
                {
                    DateTime DateD          = DateTime.Now;
                    PublisherClass itemList = new PublisherClass();
                    foreach (Tag tag in ASynchronePortTcp[updateRate])
                    {
                        Item element       = new Item();
                        element.Address    = tag.Ip_Address;
                        element.TagName    = tag.TagName;
                        DateTime localDate = DateTime.Now;
                        element.TimeStamp  = localDate;

                        s_cts.CancelAfter(tag.Connection_Timeout);
                        Task.Run(() => PingTcpPort(tag));
                        if (tag.is_open == true)
                        {
                            tag.PortDescription = tag.Ip_Address + ":: " + tag.Port + ":: is open";
                            element.is_open     = true;
                        }
                        else
                        {
                            element.is_open = false;
                            if (tag.PortDescription == null)
                            {
                                tag.PortDescription = "Cannot establish Tcp Connection to " + tag.Ip_Address + ":" + tag.Port;
                            }
                        }
                        element.Description = tag.PortDescription;


                        itemList.Payload.Add(element);
                    }
                    itemList.SchemaId = IOHelper.AgentConfig.Agent_SchemaID;
                    Publisherqueue.Add(itemList);
                    Thread.Sleep(updateRate);
                }
            });
        }
Esempio n. 6
0
        public static void PingSynchHost(Tag tag, PublisherClass itemList)
        {
            Ping        pingSender = new Ping();
            PingOptions options    = new PingOptions();

            // Use the default Ttl value which is 128,
            // but change the fragmentation behavior.
            options.DontFragment = tag.DontFragment;

            // Create a buffer of 32 bytes of data to be transmitted.

            byte[] buffer = Encoding.ASCII.GetBytes(tag.Data);
            try
            {
                Item     element   = new Item();
                DateTime localDate = DateTime.Now;
                element.TimeStamp = localDate;
                element.TagName   = tag.TagKey;
                PingReply reply = pingSender.Send(tag.Ip_Address, tag.Connection_Timeout, buffer, options);
                if (reply.Status == IPStatus.Success)
                {
                    WorkerLogger.TraceLog(MessageType.Debug, tag.Ip_Address + " is connected");
                    element.is_open     = true;
                    tag.is_open         = true;
                    element.Description = "Host with ip: " + tag.Ip_Address + "is open";
                }
                else
                {
                    WorkerLogger.TraceLog(MessageType.Debug, tag.Ip_Address + " is not connected");
                    element.is_open     = false;
                    tag.is_open         = false;
                    element.Description = "Host with ip: " + tag.Ip_Address + "is down or cannot be reachable";
                }
                itemList.Payload.Add(element);
            }
            catch (Exception ex)
            {
                WorkerLogger.TraceLog(MessageType.Error, ex.Message);
            }
        }
Esempio n. 7
0
        public void ConnectPortTcpSync()
        {
            Parallel.ForEach(SynchronePortTcp.Keys, updateRate =>
            {
                while (true)
                {
                    PublisherClass itemList = new PublisherClass();
                    foreach (Tag tag in SynchronePortTcp[updateRate])
                    {
                        Item element    = new Item();
                        element.Address = tag.Ip_Address + ":" + tag.Port;
                        element.TagName = tag.TagKey;

                        s_cts.CancelAfter(tag.Connection_Timeout);
                        PingTcpPort(tag).Wait();
                        if (tag.is_open == true)
                        {
                            tag.PortDescription = tag.Ip_Address + ":: " + tag.Port + ":: is open";
                            tag.is_open         = true;
                            element.is_open     = true;
                        }
                        else
                        {
                            tag.is_open = false;
                            if (tag.PortDescription == null)
                            {
                                tag.PortDescription = "Cannot establish a Tcp connection with " + element.Address;
                            }
                        }
                        element.Description = tag.PortDescription;
                        itemList.Payload.Add(element);
                    }
                    itemList.SchemaId = IOHelper.AgentConfig.Agent_SchemaID;
                    Publisherqueue.Add(itemList);
                    Thread.Sleep(updateRate);
                }
            });
        }
Esempio n. 8
0
        /// <summary>This method load the devices configuration from the config file into a dictionary that contains all the information needed to read and write data


        /// <summary> this method Check whether the Hosts are connected or not///<example>
        /// For example:///<code>/// ConnectToBACnetDevices();///results///Device BasicServer is not connected, Device RoomSimulator is connected
        /// ConnectToBACnetDevices():Check the connectivity for the first time
        ///this method check periodicaly the connectivity of multiple hosts
        public void CheckSyncHostStatus()
        {
            try
            {
                Parallel.ForEach(SynchroneHost.Keys, item =>
                {
                    while (true)
                    {
                        PublisherClass itemList = new PublisherClass();
                        foreach (Tag tag in SynchroneHost[item])
                        {
                            WorkerManager.PingSynchHost(tag, itemList);
                        }
                        itemList.SchemaId = IOHelper.AgentConfig.Agent_SchemaID;
                        Publisherqueue.Add(itemList);
                        Thread.Sleep(item);
                    }
                });
            }
            catch (Exception ex)
            {
                WorkerLogger.TraceLog(MessageType.Error, ex.Message);
            }
        }
Esempio n. 9
0
        private void bt_import_Purchase_Click(object sender, EventArgs e)
        {
            if (ofd_load_Purchase.ShowDialog() == DialogResult.OK)//Вызываем диалог выбора файла и проверяем, что полльзователь выбрал файл
            {
                DataTable table;
                if (ExcelClass.loadExcel(ofd_load_Purchase.FileName, out table))//Если загрузка данных(ИмяФайла,ТаблицаСРезультатом) прошел успешно
                {
                    PurchaseListClass purchaseList = new PurchaseListClass {
                        datePurchase = DateTime.Now
                    };
                    foreach (DataRow row in table.Rows)//перебираем полученные строки
                    {
                        StringBuilder builder = new StringBuilder();
                        //Проверка на наличие такого типа литературы с такими данными
                        string    typename = row["Тип"].ToString();
                        TypeClass type     = DbModel.init().Types.Where(t =>
                                                                        t.type == typename).FirstOrDefault();

                        //Если книга не существует, то выдается сообщение об ошибке
                        if (type == null)
                        {
                            type = new TypeClass {
                                type = Convert.ToString(typename)
                            };
                        }

                        //проверка на наличие авторов в базе
                        List <AuthorClass> authors = new List <AuthorClass>();
                        //разделение авторов сначала на двух разных, а затем каждого на инициалы
                        string   FIO_Authors  = Convert.ToString(row["Автор"]);
                        string[] split_Author = FIO_Authors.Split(',');
                        //перебираем инициаллы
                        foreach (string strF_IO in split_Author)
                        {
                            string[]    F_I_O = strF_IO.Split(' ', '.');
                            AuthorClass author = null;
                            string      fam = F_I_O[0], name = F_I_O[1], otch = F_I_O[2];
                            //сравниваем инициалы на наличие соотношениий в базе. Инициалы И.О. сверяются с первыми бууквами значений.
                            author = DbModel.init().Authors.Where(a => a.family_name.StartsWith(fam) && a.first_name.StartsWith(name) && a.middle_name.StartsWith(otch)).FirstOrDefault();
                            //если такой автор в базе найден, то.....

                            if (author != null)
                            {
                                //в класс (таблицу) автора добавляется новой значение
                                authors.Add(author);
                            }
                            else
                            {
                                //если данные не найдены, то открывается форма "AddAvtor" для того, чтобы пользователь расшифровал значение.
                                //От формы данные добавляются в базу
                                AddAvtorForm addAvtor = new AddAvtorForm(fam, name, otch);
                                if (addAvtor.ShowDialog() != DialogResult.OK)
                                {
                                    builder.AppendLine(String.Format("Fio author {0} not found!", strF_IO));
                                }
                                else
                                {
                                    author = addAvtor.GetAuthor();
                                    authors.Add(author);
                                }
                            }
                        }



                        //Проверка на наличие издательства с такими данными. !!!!!!!!!Действия схожи с данными об авторах!!!!!!!
                        List <PublisherClass> publishers = new List <PublisherClass>();
                        string         publicher_str = Convert.ToString(row["Издательство"]);
                        string[]       split_publisher = publicher_str.Split(':');
                        PublisherClass publisher = null;
                        string         publisher_name = split_publisher[1], publisher_city = split_publisher[0];
                        publisher = DbModel.init().Publishers.Where(p =>
                                                                    p.city.StartsWith(publisher_city) && p.name.StartsWith(publisher_name)).FirstOrDefault();
                        if (publisher != null)
                        {
                            publishers.Add(publisher);
                        }
                        else
                        {
                            AddPublisherForm addPublisher = new AddPublisherForm(publisher_city, publisher_name);
                            if (addPublisher.ShowDialog() != DialogResult.OK)
                            {
                                builder.AppendLine(String.Format("Издательство не найдено!", publicher_str));
                            }
                            else
                            {
                                publisher = addPublisher.GetPublisher();
                                publishers.Add(publisher);
                            }
                        }


                        //Проверка на наличие данной литературы
                        BookClass book     = null;
                        string    bookname = row["Название"].ToString();
                        int?      bookclassnum = null;
                        try
                        {
                            bookclassnum = Convert.ToInt32(row["Класс"]);
                        }
                        catch { }
                        book = DbModel.init().Books.Include(b => b.publisher).Include(b => b.type).Include(b => b.Authors)
                               .Where(b =>
                                      b.classnum == bookclassnum &&
                                      b.name_book == bookname &&
                                      b.publisher.idPublisher == publisher.idPublisher &&
                                      b.type.idType == type.idType
                                      ).FirstOrDefault();

                        if (book == null)
                        {
                            AddBookForm addBook = new AddBookForm(bookclassnum, bookname, publisher, type, authors);
                            if (addBook.ShowDialog() != DialogResult.OK)
                            {
                                builder.AppendLine(String.Format("Литература не найдена!", bookname));
                            }
                            book = addBook.GetBook();
                        }

                        int Litheraturecount = Convert.ToInt32(row["Количество"]);
                        purchaseList.purchaseAccountings.Add(
                            new PurchaseAccountingClass
                        {
                            count = Litheraturecount,
                            price = Convert.ToDecimal(row["Цена"]),
                            literatureTurnover = LiteratureTurnoverClass.addNewLitherature(book, Litheraturecount)
                        }
                            );
                    }
                    AddPurchaseForm addPurchase = new AddPurchaseForm(purchaseList);
                    addPurchase.ShowDialog();
                    MessageBox.Show("Boooozhe! ONO RABOTAET!");
                }
            }
        }
Esempio n. 10
0
 public SubscriberClass(PublisherClass p)
 {
     p.Event += d_Event;
 }
Esempio n. 11
0
 public SubscriberClass(PublisherClass p)
 {
     p.EventAccessor += d_Event;
 }
Esempio n. 12
0
        //Ping Hosts asynchronously
        public static async Task PingAsyncHosts(ASynchroneHost addresses, string updateRate, int update)
        {
            while (true)
            {
                //Date before Ping Hosts
                DateTime       DateD    = DateTime.Now;
                PublisherClass itemList = new PublisherClass();
                //
                var pingTasks = addresses.Ip_Address.Select(address =>
                {
                    return(new Ping().SendPingAsync(address.ToString()));
                });

                await Task.WhenAll(pingTasks);


                StringBuilder pingResultBuilder = new StringBuilder();

                foreach (var pingReply in pingTasks)
                {
                    pingResultBuilder.Append(pingReply.Result.Address);
                    Temp_Test_Connection_Async_Host[pingReply.Result.Address.ToString()] = true;
                }

                foreach (var item in addresses.TagList)
                {
                    Item element = new Item();
                    element.Address = item.Ip_Address;
                    element.TagName = item.TagKey;
                    DateTime localDate = DateTime.Now;
                    element.TimeStamp = localDate;


                    if (Temp_Test_Connection_Async_Host[item.Ip_Address] == true)
                    {
                        WorkerLogger.TraceLog(MessageType.Debug, " Host with address: " + item + " is connected");
                        element.is_open     = true;
                        item.is_open        = true;
                        element.Description = "Host with ip: " + item.Ip_Address + "is open";
                    }
                    else
                    {
                        WorkerLogger.TraceLog(MessageType.Debug, " Host with address: " + item + " is not connected");
                        element.is_open     = false;
                        item.is_open        = false;
                        element.Description = "Host with ip: " + item.Ip_Address + "is down or cannot be reachable";
                    }
                    itemList.Payload.Add(element);
                }
                Publisherqueue.Add(itemList);



                Clear_Test_Connection();
                //Date after test connection
                DateTime DateF = DateTime.Now;
                //We have to subtract the time of traitement from the updateRate
                //If the traitement time was higher than the updateRate we had to excute the next ping without waiting
                if (update - (DateD.Second - DateF.Second) > 0)
                {
                    await Task.Delay(TimeSpan.FromSeconds(update - (DateD.Second - DateF.Second)));
                }
                //we have to set the test_connection values to false
                Clear_Test_Connection();
            }
        }