Пример #1
0
        /// <summary>
        /// Assign a worker to the shift.
        /// </summary>
        /// <param name="worker"></param>
        public void Assign(TestWorker worker)
        {
            log.Debug("{0} shift assigned worker {1}", _name, worker.Name);

            Workers.Add(worker);

            worker.Busy += (s, ea) => Interlocked.Increment(ref _busyCount);
            worker.Idle += (s, ea) =>
            {
                // Quick check first using Interlocked.Decrement
                if (Interlocked.Decrement(ref _busyCount) == 0)
                {
                    lock (_syncRoot)
                    {
                        // Check busy count again under the lock
                        if (_busyCount == 0 && !HasWork)
                        {
                            this.EndShift();
                        }
                    }
                }
            };

            worker.Start();
        }
Пример #2
0
        private void btnDelete_Click(object sender, EventArgs e)
        {
            int id = 0;

            int.TryParse(tbId.Text, out id);
            if (id != 0)
            {
                Workers currentWorkers = BLWorkers.GetWorkersById(APCContext, id);
                if (currentWorkers != null)
                {
                    APCContext.DeleteObject(currentWorkers);
                    APCContext.SaveChanges();
                    MessageBox.Show("Delete Successfully");
                    ClearContent();
                }
                else
                {
                    MessageBox.Show("Workers Id not found");
                }
            }
            else
            {
                MessageBox.Show("Workers Id not found");
            }
        }
        public ActionResult LoginUpdate(Workers account, string newPassword, String newPasswordConfirm)
        {
            var query  = db.Workers.Where(x => x.WorkerAccountName == account.WorkerAccountName && x.Password == account.Password).FirstOrDefault();
            var queryT = db.Workers.Where(x => x.WorkerAccountName == account.WorkerAccountName && x.Password == account.Password).ToList();
            var count  = queryT.Count();

            if (count > 0)
            {
                if (newPassword != "" && newPasswordConfirm != "")
                {
                    if (newPassword == newPasswordConfirm)
                    {
                        query.WorkerAccountName = account.WorkerAccountName;
                        query.Password          = newPassword;
                        db.SaveChanges();
                        FormsAuthentication.SignOut();
                        return(RedirectToAction("Login", "Login"));
                    }
                    else
                    {
                        ViewBag.MessageUpdate = "Passwords Are Not The Same!";
                    }
                }
                else
                {
                    ViewBag.MessageUpdate = "Wrong New Password!";
                }
            }
            else
            {
                ViewBag.MessageUpdate = "Wrong Password!";
            }
            return(View());
        }
Пример #4
0
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            decimal salary = 0;
            int     id     = 0;

            int.TryParse(tbId.Text, out id);
            decimal.TryParse(tbSalary.Text, out salary);
            if (id != 0)
            {
                Workers currentWorkers = BLWorkers.GetWorkersById(APCContext, id);
                if (currentWorkers != null)
                {
                    currentWorkers.Name   = tbName.Text;
                    currentWorkers.Salary = salary;
                    APCContext.SaveChanges();
                    MessageBox.Show("Workers Details Successfully Updated");
                    ClearContent();
                }
                else
                {
                    MessageBox.Show("Workers Id not found");
                }
            }
            else
            {
                MessageBox.Show("Workers Id not found");
            }
        }
Пример #5
0
        public void Unload()
        {
            SelectedWorkers.Clear();
            Workers.Clear();

            isLoaded = false;
        }
Пример #6
0
        private async Task InitilizeTasks()
        {
            int max = Config.MaxDownloaders;

            for (int i = 0; i < Config.MaxDownloaders; i++)
            {
                TaskState state = new TaskState();
                Task      task  = new Task <Task>(DoDownloadWork, state);
                //Task task = DoDownloadWork(state);
                state.Id = task.Id;

                Downloaders.TryAdd(i, task);
                Tasks.TryAdd(task.Id, task);
            }

            for (int i = 0; i < Config.MaxProcessors; i++)
            {
                TaskState state = new TaskState();
                Task      task  = new Task <Task>(DoWork, state, TaskCreationOptions.LongRunning);
                state.Id = task.Id;

                Workers.TryAdd(i, task);
                Tasks.TryAdd(task.Id, task);
            }
        }
Пример #7
0
        private void BtnAddservice_Click(object sender, RoutedEventArgs e)
        {
            Workers currentWorker = (Workers)CBoxWorkers.SelectedItem;

            _ccurrnetServices.IdWorker = currentWorker.Id;

            if (_ccurrnetServices.Id == 0)
            {
                db_a752cb_hellobeauty6Entities.GetContex().Services.Add(_ccurrnetServices);
            }

            try
            {
                db_a752cb_hellobeauty6Entities.GetContex().SaveChanges();
                MessageBox.Show("Услуга успешно сохранена");
                NavManager.AccountFrame.Navigate(new PageServices(NavManager.BtnServices.Content + ""));
            }
            catch (DbEntityValidationException ex)
            {
                if (ApplicationConfig.IsDev)
                {
                    foreach (var errors in ex.EntityValidationErrors)
                    {
                        foreach (var validationError in errors.ValidationErrors)
                        {
                            MessageBox.Show(validationError.ErrorMessage);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Произошла ошибка", "Внимание", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }
Пример #8
0
        public async Task SaveAsync(Workers entity)
        {
            try
            {
                if (entity == null)
                {
                    return;
                }

                using (var timeLineContext = _contextFactory.GetTimeLineContext())
                {
                    var entityModel = await timeLineContext
                                      .Workers
                                      .FirstOrDefaultAsync(item => item.Id.Equals(entity.Id));

                    if (entityModel == null)
                    {
                        entityModel = new DA.Workers();
                        MapForUpdateentity(entity, entityModel);
                        await timeLineContext.Workers.AddAsync(entityModel);
                    }
                    else
                    {
                        MapForUpdateentity(entity, entityModel);
                    }


                    timeLineContext.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #9
0
 public override bool IsDoneWorking()
 {
     return
         (IsAtEndOfWorkload() ||
          Workers.All(w => w.State == PipelineWorker.WorkerState.Stopped)
         );
 }
Пример #10
0
 public WorkGroup(int amountOfWorkers)
 {
     for (var i = 0; i < amountOfWorkers; i++)
     {
         Workers.Add(new Worker());
     }
 }
Пример #11
0
        public virtual async Task <bool> SendItemAsync(object itemToProcess)
        {
            try
            {
                if (!Workers.Any())
                {
                    throw new Exception("No workers available!");
                }
                if (itemToProcess == null)
                {
                    throw new ArgumentNullException(nameof(itemToProcess));
                }
                var worker = SelectWorker();
                while (!worker.CanReceiveItems())
                {
                    Thread.Sleep(2000);
                }
                await worker.ReceiveAsync(itemToProcess);

                return(true);
            }
            catch (Exception e)
            {
                ErrorHandler.HandleException(e);
                return(false);
            }
        }
Пример #12
0
        public ActionResult ReturnToPersonMain()
        {
            string[] data = System.IO.File.ReadAllLines(@"F:\vs2017python\asp DBProject\WebApplication4\Info.txt");
            string   ac   = data[0];
            string   pwd  = data[1];

            User objAdmin = new User()
            {
                Account = ac,
                Pwd     = pwd
            };

            objAdmin = new LoginService().AdminLogin(objAdmin);

            Workers       worker = new Workers(objAdmin.ID);
            List <string> needs  = new List <string>(); //查询的数据需求,此处时座位号

            needs.Add("Name");
            needs.Add("Phone");
            needs.Add("Kind");
            List <string> res = new List <string>();     //查询结果,GroundWorkerHome 用到的查询结果

            res = DataBaseAccess.GetSingleInfo(worker, needs);
            res.Add(objAdmin.ID.ToString());
            return(View("GroundWorkerHome", res));
        }
        public override void DoRequest(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData)
        {
            DataPacket newPacket = (DataPacket)packet.Clone();
            UInt32 gwioid = CidGenerator.Next();
            Record record = InfoService.IOID.Create(gwioid);
            record.Destination = packet.Sender;
            record.IOID = packet.Parameter2;

            record = InfoService.ChannelCid[packet.Parameter1];

            // Lost the CID
            if (record == null)
            {
                if (Log.WillDisplay(TraceEventType.Error))
                    Log.TraceEvent(System.Diagnostics.TraceEventType.Error, chain.ChainId, "Readnotify not linked to a correct channel");
                packet.Chain.Dispose();
                return;
            }

            if (record.SID == null)
            {
                if (Log.WillDisplay(TraceEventType.Error))
                    Log.TraceEvent(System.Diagnostics.TraceEventType.Error, chain.ChainId, "Readnotify without SID");
                chain.Dispose();
                return;
            }

            newPacket.Destination = record.Destination;
            newPacket.Parameter1 = record.SID.Value;
            newPacket.Parameter2 = gwioid;

            sendData(newPacket);
        }
Пример #14
0
 private void CreateWorkers()
 {
     Workers.Add(new Worker("Шванов Сергій Володимирович", Posts.FirstOrDefault(el => el.Name == "Програміст"), ".Net Розробник", 5)
     {
         Id = 1, Bio = "Новий працівник"
     });
     Workers.Add(new Worker("Лозова Аліна Анатоліївна", Posts.FirstOrDefault(el => el.Name == "Дизайнер"), "3D-Дизайнер", 4)
     {
         Id = 2
     });
     Workers.Add(new Worker("Кріпак Олександр Макарович", Posts.FirstOrDefault(el => el.Name == "Програміст"), "Веб-розробник", null)
     {
         Id = 3
     });
     Workers.Add(new Worker("Возілевський Леонід Андрійович", Posts.FirstOrDefault(el => el.Name == "Тестувальник"), "Тестувальник ПО", 3)
     {
         Id = 4
     });
     Workers.Add(new Worker("Ломаченко Олександр Іванович", Posts.FirstOrDefault(el => el.Name == "Тестувальник"), null, 7)
     {
         Id = 5
     });
     Workers.Add(new Worker("Федоренко Оксана Василівна", Posts.FirstOrDefault(el => el.Name == "Дизайнер"), null, null)
     {
         Id = 6
     });
     Workers.Add(new Worker("Баланов Руслан Ігорович", Posts.FirstOrDefault(el => el.Name == "Програміст"), null, 8)
     {
         Id = 7
     });
     Workers.Add(new Worker("Харченко Іван Іванович", Posts.FirstOrDefault(el => el.Name == "Менеджер"), "Менеджер по рекламі", 4)
     {
         Id = 8
     });
 }
        public ActionResult Login(Workers worker, int Remember = 0)
        {
            var query       = db.Workers.Where(x => x.WorkerAccountName == worker.WorkerAccountName && x.Password == worker.Password).FirstOrDefault();
            var queryToList = db.Workers.Where(x => x.WorkerAccountName == worker.WorkerAccountName && x.Password == worker.Password).ToList();
            int count       = queryToList.Count();

            if (count > 0)
            {
                if (Remember == 1)
                {
                    //giriş bilgilerinizi kullanarak bir uygulama üzerinde oturum açmanıza olanak sağlar
                    //remember tıklandıysa hatırlayacak yoksa hatırkamayacak
                    FormsAuthentication.RedirectFromLoginPage(worker.WorkerAccountName, true);
                }
                else
                {
                    FormsAuthentication.RedirectFromLoginPage(worker.WorkerAccountName, false);
                }
                return(RedirectToAction("Index", "Category"));
            }
            else
            {
                ViewBag.Mesaj = "Wrong Login!";
                return(View());
            }
        }
Пример #16
0
    protected void SubmitBid_Click(object sender, EventArgs e)
    {
        jobId = (int)Session["theJob"];

        currentWorker = (Workers)Session["user"];
        int giveBid = Convert.ToInt32(Bidtxtbox.Text);
        int lowestBid = DataFactory.GetLowestBid(jobId);
        if (giveBid <= lowestBid || giveBid <= 0 || lowestBid == 0)
        {
            Bids bid = new Bids()
            {
                Bid = Convert.ToInt32(Bidtxtbox.Text),
                Id_Job = theJob.Id_Job,
                Id_Worker = currentWorker.Id_Worker
            };
            DataFactory.AddBid(bid);
            DataFactory.UpdateCurrentbid(jobId, giveBid);
            Response.Redirect("ViewJob.aspx");
        }

        if (giveBid >= lowestBid)
        {
            ErrorInBidLbl.Text = "Ditt bud är för högt, det ligger redan ett lägre bud på detta jobb!";
        }
    }
Пример #17
0
        private void btnAddW_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(txtFwname.Text) &&
                !string.IsNullOrWhiteSpace(txtLwname.Text) &&
                !string.IsNullOrWhiteSpace(dtpwBirthDate.Text) &&
                !string.IsNullOrWhiteSpace(txtwCardId.Text) &&
                !string.IsNullOrWhiteSpace(txtwPhoneNumber.Text))
            {
                Workers wr = new Workers();


                wr.FirstName   = txtFwname.Text;
                wr.LastName    = txtLwname.Text;
                wr.BirthDate   = dtpwBirthDate.Value;
                wr.CardId      = txtwCardId.Text;
                wr.PhoneNumber = txtwPhoneNumber.Text;
                wr.Email       = txtEmail.Text;
                wr.AddedDate   = DateTime.Now;

                db.Workers.Add(wr);
                db.SaveChanges();
                Reset();

                MessageBox.Show("Client added succesfully!");
                FillDgv(db.Workers.ToList());
            }
        }
Пример #18
0
        private void btnUpdateW_Click(object sender, EventArgs e)
        {
            Workers wr = db.Workers.Find(this.selectedId);

            wr.FirstName   = txtFwname.Text;
            wr.LastName    = txtLwname.Text;
            wr.BirthDate   = dtpwBirthDate.Value;
            wr.CardId      = txtwCardId.Text;
            wr.PhoneNumber = txtwPhoneNumber.Text;
            wr.Email       = txtEmail.Text;
            wr.AddedDate   = DateTime.Now;


            db.SaveChanges();
            Reset();


            btnDeleteW.Visible = false;
            btnUpdateW.Visible = false;
            btnAddW.Visible    = true;


            MessageBox.Show("Worker info updated succesfully!");
            FillDgv(db.Workers.ToList());
        }
Пример #19
0
        static void Main(string[] args)
        {
            Console.Write("Enter department name: ");
            string departmentName = Console.ReadLine();

            Console.WriteLine();

            Console.WriteLine("Enter worker data:");
            Console.WriteLine();

            Console.Write("Name: ");
            string workerName = Console.ReadLine();

            Console.Write("Level (Junior/MidLevel/Senior): ");
            string      level = Console.ReadLine();
            WorkerLevel levels;

            Enum.TryParse <WorkerLevel>(level, true, out levels);
            Console.Write("Base Salary: ");
            double baseSalary = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);

            Console.WriteLine();

            Console.Write("How many contracts to this worker? ");
            int contracts = int.Parse(Console.ReadLine());

            Console.WriteLine();

            Department d      = new Department(departmentName);
            Workers    worker = new Workers(workerName, levels, baseSalary, d);

            for (int i = 1; i <= contracts; i++)
            {
                Console.WriteLine($"Enter the #{i} contract data");
                Console.WriteLine();
                Console.Write("Date (DD/MM/YYYY): ");
                DateTime date = DateTime.Parse(Console.ReadLine());
                Console.Write("Value per hour: ");
                double valuePerHour = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
                Console.Write("Duration (hours): ");
                int hours = int.Parse(Console.ReadLine());
                Console.WriteLine();

                HourContract c = new HourContract(date, valuePerHour, hours);
                worker.AddContract(c);
            }
            Console.WriteLine();

            Console.Write("Enter month and year to calculate income (MM/YYYY): ");
            string dateIncome = Console.ReadLine();
            int    month      = int.Parse(dateIncome.Substring(0, 2));
            int    year       = int.Parse(dateIncome.Substring(3));

            Console.WriteLine("Name: " + worker.Name);
            Console.WriteLine("Department: " + worker.Department.Name);
            Console.WriteLine("Income for: " + dateIncome + ": " + worker.Income(year, month).ToString("F2", CultureInfo.InvariantCulture));

            Console.ReadLine();
        }
Пример #20
0
 public void AddWorker(Colonist colonist)
 {
     if (WorkerCapacity == Workers.Count)
     {
         throw new GameException($"{Name} is full");
     }
     Workers.Add(colonist);
 }
Пример #21
0
 public void AddWorker(CozyWorker worker)
 {
     worker.MessageCallback = MsgCallback;
     lock (Locker)
     {
         Workers.Add(worker);
     }
 }
Пример #22
0
 //הוספה מחיקה עדכון ושליפה אנשי צוות
 public static void AddWorker(Workers worker)
 {
     using (var db = new SulamEntities())
     {
         db.Workers.Add(worker);
         db.SaveChanges();
     }
 }
Пример #23
0
 public ParameterlessFiberArray(int noW)
     : base(noW)
 {
     for (int i = 0; i < NumberOfWorkers; i++)
     {
         Workers.Add(new TWorker());
     }
 }
Пример #24
0
        // GET: Workers/Edit/5
        public ActionResult Edit(int id)
        {
            var     identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
            var     email    = HttpContext.User.Identity.Name;
            Workers workers  = db.Workers.Where(l => l.Name == email).First();

            return(View(workers));
        }
Пример #25
0
        // GET: Workers/Create

        public ActionResult Create(String UserId)
        {
            Workers workers = new Workers();

            workers.UserId = UserId;

            return(View(workers));
        }
 private void PackersComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     if (PackersComboBox.SelectedItem != null)
     {
         Workers selectedPacker = PackersComboBox.SelectedItem as Workers;
         packerId = selectedPacker.w_id;
     }
 }
Пример #27
0
        public void CountEmployees()
        {
            Console.Clear();
            Console.WriteLine("Count workers:" + " " + Workers.Count() + "\nCount managers: " + " " + Managers.Count() + "\nCount taskmasters:" + " " + Taskmasters.Count());
            var sum = Workers.Count() + Managers.Count() + Taskmasters.Count();

            Console.WriteLine("\nAll employees" + " " + sum);
        }
Пример #28
0
        public ActionResult CreateWorker()
        {
            Workers worker = new Workers();

            worker.UserId = TempData["UserId"].ToString();

            return(View(worker));
        }
Пример #29
0
        public void Add()
        {
            Worker w = new Worker();

            w.SetIndex(count);
            count++;
            Workers.Add(w);
        }
 public override void DoResponse(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData)
 {
     Record record = InfoService.ChannelCid[packet.Parameter1];
     if (Log.WillDisplay(TraceEventType.Critical))
     {
         if (record != null)
             Log.TraceEvent(TraceEventType.Critical, chain.ChainId, "Proto Error (" + packet.Parameter2 + ") on CID: " + packet.Parameter1 + " (" + record.Channel + "), SID = " + record.SID);
         else
             Log.TraceEvent(TraceEventType.Critical, chain.ChainId, "Proto Error (" + packet.Parameter2 + ") on CID: " + packet.Parameter1);
     }
 }
        public override void DoResponse(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData)
        {
            DataPacket newPacket = (DataPacket)packet.Clone();
            Record record = InfoService.IOID[packet.Parameter2];
            if (record == null || record.IOID == null)
                return;

            InfoService.IOID.Remove(packet.Parameter2);
            CidGenerator.ReleaseCid(packet.Parameter2);

            newPacket.Destination = record.Destination;
            newPacket.Parameter2 = record.IOID.Value;
            sendData(newPacket);
        }
Пример #32
0
 public static bool insertWorkers(APCEntities APCContext, string name, decimal salary)
 {
     if (name.Trim() != "")
     {
         Workers workers = new Workers();
         workers.Name = name;
         workers.Salary = salary;
         APCContext.AddToWorkers(workers);
         APCContext.SaveChanges();
         return true;
     }
     else
         return false;
 }
 public override void DoRequest(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData)
 {
     try
     {
         EventAdd.Unsubscribe(chain.Subscriptions[packet.Parameter2]);
         uint res;
         chain.Subscriptions.TryRemove(packet.Parameter2, out res);
     }
     catch
     {
         if (Log.WillDisplay(System.Diagnostics.TraceEventType.Critical))
             Log.TraceEvent(System.Diagnostics.TraceEventType.Critical, chain.ChainId, "Error while cancelling a monitor.");
         chain.Dispose();
     }
 }
Пример #34
0
        public override void DoRequest(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData)
        {
            Record channelInfo = InfoService.ChannelCid[packet.Parameter1];
            // Lost the CID
            if (channelInfo == null)
            {
                if (Log.WillDisplay(System.Diagnostics.TraceEventType.Error))
                    Log.TraceEvent(System.Diagnostics.TraceEventType.Error, chain.ChainId, "Write not linked to a correct channel");
                packet.Chain.Dispose();
                return;
            }
            SecurityAccess access;
            switch (chain.Side)
            {
                case Workers.ChainSide.SIDE_A:
                    access = chain.Gateway.Configuration.Security.EvaluateSideA(channelInfo.Channel, chain.Username, chain.Hostname, packet.Sender.Address.ToString());
                    break;
                default:
                    access = chain.Gateway.Configuration.Security.EvaluateSideB(channelInfo.Channel, chain.Username, chain.Hostname, packet.Sender.Address.ToString());
                    break;
            }
            // We don't have write access quit!
            if (!access.Has(SecurityAccess.WRITE))
            {
                return;
            }

            DataPacket newPacket = (DataPacket)packet.Clone();
            UInt32 gwioid = CidGenerator.Next();

            newPacket.Destination = channelInfo.Destination;
            // No SID? Can't write
            if (channelInfo.SID == null)
            {
                if (Log.WillDisplay(TraceEventType.Critical))
                    Log.TraceEvent(TraceEventType.Critical, chain.ChainId, "Write without SID");
                WorkerChain ioc = TcpManager.GetIocChain(null, channelInfo.Destination);
                if (ioc != null)
                    ioc.Dispose();
                chain.Dispose();
                return;
            }

            newPacket.Parameter1 = channelInfo.SID.Value;
            newPacket.Parameter2 = gwioid;

            sendData(newPacket);
        }
        public override void DoResponse(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData)
        {
            DataPacket newPacket = (DataPacket)packet.Clone();
            Record record = InfoService.IOID[packet.Parameter2];

            if (record == null)
                return;

            // Removes it to avoid the cleaup
            InfoService.IOID.Remove(packet.Parameter2);
            CidGenerator.ReleaseCid(packet.Parameter2);

            lock (EventAdd.lockObject)
            {
                // It's the initial answer as get of "cached" monitor.
                if (record.IOID.HasValue && record.IOID.Value == 0)
                {
                    if (!record.SID.HasValue)
                        return;

                    if (record.CID.HasValue && InfoService.ChannelSubscription.Knows(record.CID.Value))
                    {
                        if (InfoService.ChannelSubscription[record.CID.Value].PacketCount == 0 && InfoService.ChannelSubscription[record.CID.Value].FirstValue == true)
                        {
                            if (Log.WillDisplay(TraceEventType.Verbose))
                                Log.TraceEvent(TraceEventType.Verbose, chain.ChainId, "Sending readnotify data on " + record.SID.Value);

                            newPacket.Command = 1;
                            newPacket.Parameter1 = 1;
                            newPacket.Parameter2 = record.SID.Value;
                            newPacket.Destination = record.Destination;
                            newPacket.DataCount = record.DataCount.Value;
                            newPacket.DataType = record.DBRType.Value;

                            sendData(newPacket);
                            InfoService.ChannelSubscription[record.CID.Value].FirstValue = false;
                            InfoService.ChannelSubscription[record.CID.Value].PacketCount = 1;
                        }
                    }
                    return;
                }
            }

            newPacket.Destination = record.Destination;
            newPacket.Parameter1 = 1;
            newPacket.Parameter2 = record.IOID.Value;
            sendData(newPacket);
        }
Пример #36
0
        public override void DoRequest(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData)
        {
            IPAddress senderAddress=packet.Sender.Address;
            if (senderAddress.Equals(chain.Gateway.Configuration.LocalSideA.Address) || senderAddress.Equals(chain.Gateway.Configuration.LocalSideB.Address))
                return;

            // Use only the 5th beacon as restart
            if (packet.Parameter1 != 5)
                return;

            // Reset the beacon sender
            if (chain.Side == Workers.ChainSide.SIDE_A && chain.Gateway.beaconB != null)
                chain.Gateway.beaconB.ResetBeacon();
            else if (chain.Side == Workers.ChainSide.SIDE_B && chain.Gateway.beaconA != null)
                chain.Gateway.beaconA.ResetBeacon();
        }
Пример #37
0
 /// <summary>
 /// Both request / answer should be handled in the same way.
 /// If we didn't sent the first packet then we should answer,
 /// otherwise it's the answer to our own echo, therefore drop it.
 /// </summary>
 /// <param name="packet"></param>
 /// <param name="chain"></param>
 void HandleEcho(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate SendData)
 {
     // Answer to our own?
     if (InfoService.EchoSent[packet.Sender] != null)
     {
         // Yes then drop the packet and remove the info from our list
         InfoService.EchoSent.Remove(packet.Sender);
     }
     else
     {
         // No then let's answer with the same content just changing the destination as the sender
         DataPacket newPacket = (DataPacket)packet.Clone();
         newPacket.Destination = packet.Sender;
         //newPacket.NeedToFlush = true;
         SendData(newPacket);
     }
 }
Пример #38
0
    protected void RegLuffare(object sender, EventArgs e)
    {
        if (RegPasswordUser.Value == RegPasswordRptUser.Value)
        {
            WrongPwLblUser.Visible = false;

            Workers worker = new Workers(){
                UserName = RegEmailUser.Value,
                Password = RegPasswordUser.Value
            };

            LuffarJobbDBEntities db = new LuffarJobbDBEntities();
            db.Workers.Add(worker);
            db.SaveChanges();

            ConfirmationLblUser.Visible = true;

            Session["user"] = RegEmailUser.Value;
            Response.Redirect("Wrk_ViewJobs.aspx");
        }
        else if (RegPasswordUser.Value != RegPasswordRptUser.Value) WrongPwLblUser.Visible = true;
    }
 public override void DoRequest(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData)
 {
     chain.Username = packet.GetDataAsString();
 }
 /// <summary>
 /// Doesn't have a response for this message
 /// </summary>
 /// <param name="packet"></param>
 /// <param name="chain"></param>
 /// <param name="sendData"> </param>
 public override void DoResponse(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData)
 {
 }
Пример #41
0
 /// <summary>
 /// Create a new Workers object.
 /// </summary>
 /// <param name="id">Initial value of Id.</param>
 public static Workers CreateWorkers(int id)
 {
     Workers workers = new Workers();
     workers.Id = id;
     return workers;
 }
Пример #42
0
 public override void DoResponse(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData)
 {
     HandleEcho(packet, chain, sendData);
 }
Пример #43
0
        /// <summary>
        /// ParanoidPirate.Queue [-v]
        ///
        /// Does load-balancing with heartbeating on worker tasks to detect
        /// crashed, blocked or slow running worker tasks    .
        /// </summary>
        private static void Main(string[] args)
        {
            Console.Title = "NetMQ ParanoidPirate Queue";

            // serves as flag for exiting the program
            var exit = false;
            // catch CTRL+C as exit command
            Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                exit = true;
            };

            var verbose = args.Length > 0 && args[0] == "-v";

            using (var frontend = new RouterSocket())
            using (var backend = new RouterSocket())
            using (var poller = new NetMQPoller())
            {
                frontend.Bind(Commons.QueueFrontend);
                backend.Bind(Commons.QueueBackend);

                var workers = new Workers();

                // client sends to this socket
                frontend.ReceiveReady += (s, e) =>
                {
                    // only process incoming client requests
                    // if we have workers available handle client requests as long as we have workers
                    // storage capability of the socket otherwise and pick up later
                    if (workers.Available)
                    {
                        // get all message frames!
                        var request = frontend.ReceiveMultipartMessage();

                        if (verbose)
                            Console.WriteLine("[QUEUE] received {0}", request);

                        // get next available worker
                        var worker = workers.Next();
                        // wrap message with worker's address
                        var msg = Wrap(worker, request);

                        if (verbose)
                            Console.WriteLine("[QUEUE -> WORKER] sending {0}", msg);

                        backend.SendMultipartMessage(msg);
                    }
                };

                // worker sends to this socket
                backend.ReceiveReady += (s, e) =>
                {
                    var msg = e.Socket.ReceiveMultipartMessage();

                    if (verbose)
                        Console.WriteLine("[QUEUE <- WORKER] received {0}", msg);

                    // use workers identity for load-balancing
                    var workerIdentity = Unwrap(msg);
                    var worker = new Worker(workerIdentity);
                    workers.Ready(worker);
                    // just convenience
                    var readableWorkerId = workerIdentity.ConvertToString();

                    if (msg.FrameCount == 1)
                    {
                        var data = msg[0].ConvertToString();
                        // the message is either READY or HEARTBEAT or corrupted
                        switch (data)
                        {
                            case Commons.PPPHeartbeat:
                                Console.WriteLine("[QUEUE <- WORKER] Received a Heartbeat from {0}",
                                    readableWorkerId);
                                break;
                            case Commons.PPPReady:
                                Console.WriteLine("[QUEUE <- WORKER] Received a READY form {0}",
                                    readableWorkerId);
                                break;
                            default:
                                Console.WriteLine("[QUEUE <- WORKER] ERROR received an invalid message!");
                                break;
                        }
                    }
                    else
                    {
                        if (verbose)
                            Console.WriteLine("[QUEUE -> CLIENT] sending {0}", msg);

                        frontend.SendMultipartMessage(msg);
                    }
                };

                var timer = new NetMQTimer(Commons.HeartbeatInterval);
                // every specified ms QUEUE shall send a heartbeat to all connected workers
                timer.Elapsed += (s, e) =>
                {
                    // send heartbeat to every worker
                    foreach (var worker in workers)
                    {
                        var heartbeat = new NetMQMessage();

                        heartbeat.Push(new NetMQFrame(Commons.PPPHeartbeat));
                        heartbeat.Push(worker.Identity);

                        Console.WriteLine("[QUEUE -> WORKER] sending heartbeat!");

                        backend.SendMultipartMessage(heartbeat);
                    }
                    // restart timer
                    e.Timer.Enable = true;
                    // remove all dead or expired workers
                    workers.Purge();
                };

                if (verbose)
                    Console.WriteLine("[QUEUE] Start listening!");

                poller.Add(frontend);
                poller.Add(backend);

                poller.RunAsync();

                // hit CRTL+C to stop the while loop
                while (!exit)
                    Thread.Sleep(100);
            }
        }
        public override void DoResponse(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData)
        {
            if (!InfoService.ChannelCid.Knows(packet.Parameter1))  // Response too late, we drop it.
            {
                if (Log.WillDisplay(TraceEventType.Verbose))
                    Log.TraceEvent(System.Diagnostics.TraceEventType.Verbose, (packet.Chain == null ? 0 : packet.Chain.ChainId), "Drop late reponse.");
                return;
            }

            Record record = InfoService.ChannelCid[packet.Parameter1];
            if (record.Channel == null) // Response too late, we drop it.
            {
                if (Log.WillDisplay(TraceEventType.Verbose))
                    Log.TraceEvent(System.Diagnostics.TraceEventType.Verbose, (packet.Chain == null ? 0 : packet.Chain.ChainId), "Drop late reponse.");
                return;
            }
            if (Log.WillDisplay(TraceEventType.Verbose))
                Log.TraceEvent(System.Diagnostics.TraceEventType.Verbose, (packet.Chain == null ? 0 : packet.Chain.ChainId), "Got response for " + record.Channel + ".");

            record.SID = packet.Parameter2;
            if(!chain.Channels.Any(row=>row == record.Channel))
                chain.Channels.Add(record.Channel);

            object lockOper = locks.GetOrAdd(record.Channel, new object());

            // Stores in the channel end point the retreiven info
            Record channelInfo;
            lock (lockOper)
            //if(true)
            {
                channelInfo = InfoService.ChannelEndPoint[record.Channel];
                if (channelInfo == null)
                {
                    if (Log.WillDisplay(TraceEventType.Error))
                        Log.TraceEvent(System.Diagnostics.TraceEventType.Error, (packet.Chain == null ? 0 : packet.Chain.ChainId), "Got create channel response, but lost the request.");
                    return;
                }
                channelInfo.SID = packet.Parameter2;
                channelInfo.DBRType = packet.DataType;
                channelInfo.DataCount = packet.DataCount;
                channelInfo.GWCID = packet.Parameter1;
            }
            channelInfo.Notify(chain, packet);

            // Was a prepared creation, let's stop
            if (record.Client != null && record.Channel != null)
            {
                WorkerChain destChain = TcpManager.GetClientChain(record.Client);
                if (destChain != null)
                {
                    Log.TraceEvent(TraceEventType.Verbose, chain.ChainId, "Direct responce create channel cid " + destChain.ChannelCid[record.Channel]);

                    // Give back access rights before the create channel
                    DataPacket accessPacket = DataPacket.Create(0, packet.Chain);
                    accessPacket.Command = 22;
                    accessPacket.DataType = 0;
                    accessPacket.DataCount = 0;
                    accessPacket.Parameter1 = destChain.ChannelCid[record.Channel];
                    accessPacket.Parameter2 = (uint)record.AccessRight;
                    accessPacket.Sender = packet.Sender;
                    accessPacket.Destination = record.Client;
                    sendData(accessPacket);

                    DataPacket newPacket = (DataPacket)packet.Clone();
                    newPacket.Parameter1 = destChain.ChannelCid[record.Channel];
                    newPacket.Parameter2 = packet.Parameter1;
                    newPacket.Destination = record.Client;
                    sendData(newPacket);
                }

            }
        }
Пример #45
0
 /// <summary>
 /// There are no comments for Workers in the schema.
 /// </summary>
 public void AddToWorkers(Workers workers)
 {
     base.AddObject("Workers", workers);
 }
 /// <summary>
 /// Closing channel is currently simply answering as if we do it... but in fact does nothing.
 /// </summary>
 /// <param name="packet"></param>
 /// <param name="chain"></param>
 /// <param name="sendData"> </param>
 public override void DoRequest(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData)
 {
     DataPacket newPacket = (DataPacket)packet.Clone();
     newPacket.Destination = packet.Sender;
     sendData(newPacket);
 }
Пример #47
0
    protected void SubmitCommentBtn_OnClick(object sender, EventArgs e)
    {
        if (CommentTextArea.Value != null)
        {
            currentWorker = (Workers)Session["user"];
            string comment = CommentTextArea.Value;
            string author = currentWorker.UserName;
            jobId = (int)Session["theJob"];

            JobComments jc = new JobComments()
            {
                Comment = comment,
                Author = author,
                Id_Job = jobId
            };
            LuffarJobbDBEntities db = new LuffarJobbDBEntities();
            db.JobComments.Add(jc);
            db.SaveChanges();

            CommentTextArea.Value = "";
            Response.Redirect(Request.RawUrl);
        }
        else
        {
            ErrorInBidLbl.Text = "Kan inte göra en tom kommentar";
        }
    }
Пример #48
0
        // We get back the answer from the IOC
        public override void DoResponse(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData)
        {
            Record record = InfoService.SearchChannel[packet.Parameter2];
            if (record == null)
                return;

            // Let's create the channel in parallel. That should speedup the communication.
            string channelName = record.Channel;

            if (Gateway.AutoCreateChannel)
            {
                if (!InfoService.ChannelEndPoint.Knows(channelName))
                {
                    Record channelInfo = InfoService.ChannelEndPoint[channelName];
                    if (Log.WillDisplay(TraceEventType.Information))
                        Log.TraceEvent(TraceEventType.Information, chain.ChainId, "Pre-create the channel " + channelName);

                    UInt32 gwcid = CidGenerator.Next();

                    channelInfo = InfoService.ChannelEndPoint.Create(record.Channel);
                    channelInfo.Destination = new IPEndPoint(packet.Sender.Address, packet.DataType);
                    channelInfo.GWCID = gwcid;

                    record = InfoService.ChannelCid.Create(gwcid);
                    record.Channel = channelName;
                    record.GWCID = gwcid;
                    record.Destination = new IPEndPoint(packet.Sender.Address, packet.DataType);

                    DataPacket channelPacket = DataPacket.Create(16 + channelName.Length + DataPacket.Padding(channelName.Length));
                    channelPacket.PayloadSize = (ushort)(channelName.Length + DataPacket.Padding(channelName.Length));
                    channelPacket.DataType = 0;
                    channelPacket.DataCount = 0;
                    channelPacket.Command = 18;
                    channelPacket.Parameter1 = gwcid;
                    // Version
                    channelPacket.Parameter2 = Gateway.CA_PROTO_VERSION;
                    IPEndPoint dest = new IPEndPoint(packet.Sender.Address, packet.DataType);
                    channelPacket.Destination = dest;
                    //channelPacket.NeedToFlush = true;
                    channelPacket.SetDataAsString(channelName);

                    Gateway gw = packet.Chain.Gateway;

                    System.Threading.ThreadPool.QueueUserWorkItem(state =>
                    {
                        try
                        {
                            TcpManager.SendIocPacket(gw, channelPacket);
                            //TcpManager.FlushBuffer(dest);
                        }
                        catch
                        {
                        }
                    });

                    record = InfoService.SearchChannel[packet.Parameter2];
                }
            }

            if (chain.Side == ChainSide.SIDE_B || chain.Side == ChainSide.UDP_RESP_SIDE_A)
                InfoService.SearchChannelEndPointA.Remove(channelName);
            else
                InfoService.SearchChannelEndPointB.Remove(channelName);

            IPEndPoint destination = new IPEndPoint(packet.Sender.Address, packet.DataType);
            WorkerChain ioc = TcpManager.GetIocChain(chain.Gateway, destination);
            // We can't connect to the IOC...
            if (ioc == null)
                return;
            if (!ioc.Channels.Any(row => row == channelName))
                ioc.Channels.Add(channelName);
            Record channel = InfoService.ChannelEndPoint[channelName];
            if (channel == null)
                channel = InfoService.ChannelEndPoint.Create(channelName);
            channel.Server = destination;

            if (chain.Side == ChainSide.SIDE_B || chain.Side == ChainSide.UDP_RESP_SIDE_A)
                channel.knownFromSideA = true;
            else
                channel.knownFromSideA = false;

            if (record == null || record.CID == null)
                return;
            // Auto-creation of the channels after a restart
            if (record.CID == 0)
            {
                if (Log.WillDisplay(TraceEventType.Information))
                    Log.TraceEvent(TraceEventType.Information, chain.ChainId, "Recovered channel " + channelName);
                return;
            }

            DataPacket newPacket = (DataPacket)packet.Clone();

            if (packet.Chain.Gateway.Configuration.ConfigurationType == ConfigurationType.BIDIRECTIONAL)
            {
                if (chain.Side == Workers.ChainSide.SIDE_A)
                    newPacket.DataType = (UInt16)chain.Gateway.Configuration.LocalSideB.Port;
                else
                    newPacket.DataType = (UInt16)chain.Gateway.Configuration.LocalSideA.Port;
            }
            else if (chain.Side == Workers.ChainSide.UDP_RESP_SIDE_A)
                newPacket.DataType = (UInt16)chain.Gateway.Configuration.LocalSideA.Port;
            else
                newPacket.DataType = (UInt16)chain.Gateway.Configuration.LocalSideB.Port;
            newPacket.Parameter1 = 0xffffffff;
            newPacket.Parameter2 = record.CID.Value;
            newPacket.Destination = record.Client;
            newPacket.SetUInt16(16, Gateway.CA_PROTO_VERSION);

            sendData(newPacket);
        }
 public abstract void DoResponse(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData);
        public override void DoResponse(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData)
        {
            lock (lockObject)
            {
                if (packet.PayloadSize == 0)
                {
                    // Closing channel.
                    return;
                }

                Record mainSubscription = InfoService.ChannelSubscription[packet.Parameter2];
                if (mainSubscription == null)
                {
                    /*if (Log.WillDisplay(TraceEventType.Error))
                        Log.TraceEvent(TraceEventType.Error, chain.ChainId, "Main monitor not found.");*/
                    //chain.Dispose();
                    return;
                }
                string recId = mainSubscription.Channel;
                Record subscriptions = InfoService.SubscribedChannel[recId];

                if (subscriptions == null)
                {
                    if (Log.WillDisplay(TraceEventType.Error))
                        Log.TraceEvent(TraceEventType.Error, chain.ChainId, "Subscription list not found not found.");
                    chain.Dispose();
                    return;
                }

                // Keep a copy of the first packet.
                /*if (subscriptions.FirstPacket == null)
                    subscriptions.FirstPacket = (DataPacket)packet.Clone();*/

                subscriptions.FirstValue = false;

                foreach (UInt32 i in subscriptions.SubscriptionList)
                {
                    DataPacket newPacket = (DataPacket)packet.Clone();
                    Record subscription = InfoService.ChannelSubscription[i];

                    // Received a response after killing it maybe
                    if (subscription == null || subscription.SubscriptionId == null)
                        continue;

                    if (subscription.PacketCount == 0 && subscription.FirstValue == true)
                    {
                        //subscription.PacketCount++;
                        continue;
                    }

                    subscription.PacketCount++;

                    newPacket.Destination = subscription.Client;
                    newPacket.Parameter2 = subscription.SubscriptionId.Value;

                    // Event cancel send a command 1 as response (as event add)
                    // To see the difference check the payload as the event cancel always have a payload of 0
                    if (packet.PayloadSize == 0)
                    {
                        InfoService.ChannelSubscription.Remove(packet.Parameter2);
                        CidGenerator.ReleaseCid(packet.Parameter2);
                        WorkerChain clientChain = TcpManager.GetClientChain(newPacket.Destination);
                        if (clientChain != null)
                        {
                            uint val;
                            clientChain.Subscriptions.TryRemove(newPacket.Parameter2, out val);
                        }
                        continue;
                    }

                    sendData(newPacket);
                }
            }
        }
Пример #51
0
 public static bool insertProject_Workers(APCEntities APCContext, Project project, Workers worker, DateTime startDate, DateTime endDate, decimal totalHours, decimal salary)
 {
     Project_Workers project_workers = new Project_Workers();
     project_workers.Project = project;
     project_workers.Workers = worker;
     project_workers.StartDate = startDate;
     project_workers.EndDate = endDate;
     project_workers.TotalHours = totalHours;
     project_workers.Salary = salary;
     project_workers.TotalSalary = salary * totalHours;
     project_workers.Invoiced = false;
     APCContext.AddToProject_Workers(project_workers);
     APCContext.SaveChanges();
     return true;
 }
        public override void DoRequest(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData)
        {
            if (packet.DataCount == 0)
            {
                if (Log.WillDisplay(TraceEventType.Error))
                    Log.TraceEvent(TraceEventType.Error, chain.ChainId, "Event add with datacount == 0!");
                packet.DataCount = 1;
            }
            lock (lockObject)
            {
                Record record = InfoService.ChannelCid[packet.Parameter1];
                // Lost the CID...
                if (record == null)
                {
                    if (Log.WillDisplay(TraceEventType.Error))
                        Log.TraceEvent(System.Diagnostics.TraceEventType.Error, chain.ChainId, "EventAdd not linked to a correct channel");
                    packet.Chain.Dispose();
                    return;
                }

                if (record.SID == null)
                {
                    if (Log.WillDisplay(TraceEventType.Error))
                        Log.TraceEvent(System.Diagnostics.TraceEventType.Error, chain.ChainId, "EventAdd SID null");
                    packet.Chain.Dispose();
                    return;
                }

                if (Log.WillDisplay(TraceEventType.Information))
                    Log.TraceEvent(System.Diagnostics.TraceEventType.Information, chain.ChainId, "Add event for " + record.Channel);

                // Not enough info
                if (packet.MessageSize < 12 + 2 + packet.HeaderSize)
                {

                }

                string recId = record.Channel + "/" + packet.DataType + "/" + packet.DataCount + "/" + packet.GetUInt16(12 + (int)packet.HeaderSize);
                //Console.WriteLine(recId);

                //recId = ""+CidGenerator.Next();

                UInt32 gwcid = CidGenerator.Next();
                Record currentMonitor = InfoService.ChannelSubscription.Create(gwcid);
                currentMonitor.Destination = record.Destination;
                currentMonitor.DBRType = packet.DataType;
                currentMonitor.DataCount = packet.DataCount;
                currentMonitor.Client = packet.Sender;
                currentMonitor.SubscriptionId = packet.Parameter2;
                currentMonitor.SID = record.SID.Value;
                currentMonitor.Channel = recId;
                currentMonitor.FirstValue = false;

                chain.Subscriptions[packet.Parameter2] = gwcid;

                // A new monitor
                // Create a new subscription for the main channel
                // And create a list of subscriptions
                if (!InfoService.SubscribedChannel.Knows(recId))
                {
                    if (Log.WillDisplay(TraceEventType.Information))
                        Log.TraceEvent(System.Diagnostics.TraceEventType.Information, chain.ChainId, "Creating new monitor monitor");

                    // Create the subscriptions record.
                    Record subscriptions = new Record();
                    subscriptions.SubscriptionList = new ConcurrentBag<UInt32>();
                    subscriptions.SubscriptionList.Add(gwcid);
                    subscriptions.FirstValue = true;
                    InfoService.SubscribedChannel[recId] = subscriptions;

                    // We don't need to skip till the first packet.
                    currentMonitor.PacketCount = 1;

                    gwcid = CidGenerator.Next();
                    subscriptions.GWCID = gwcid;

                    WorkerChain ioc = TcpManager.GetIocChain((packet.Chain == null ? null : packet.Chain.Gateway), record.Destination);
                    if (ioc == null)
                    {
                        if (Log.WillDisplay(TraceEventType.Error))
                            Log.TraceEvent(System.Diagnostics.TraceEventType.Error, chain.ChainId, "Lost IOC");
                        chain.Dispose();
                        return;
                    }
                    ioc.ChannelSubscriptions[recId] = gwcid;

                    currentMonitor = InfoService.ChannelSubscription.Create(gwcid);
                    currentMonitor.Channel = recId;
                    currentMonitor.Destination = record.Destination;
                    currentMonitor.SID = record.SID;
                    currentMonitor.DBRType = packet.DataType;
                    currentMonitor.DataCount = packet.DataCount;

                    DataPacket newPacket = (DataPacket)packet.Clone();
                    newPacket.Parameter1 = record.SID.Value;
                    newPacket.Parameter2 = gwcid;
                    newPacket.Destination = record.Destination;
                    sendData(newPacket);
                }
                else
                {
                    Record subscriptions = null;

                    if (Log.WillDisplay(TraceEventType.Information))
                        Log.TraceEvent(System.Diagnostics.TraceEventType.Information, chain.ChainId, "Linking to existing monitor");

                    // Add ourself to the subscriptions
                    subscriptions = InfoService.SubscribedChannel[recId];
                    if (subscriptions == null)
                    {
                        if (Log.WillDisplay(TraceEventType.Error))
                            Log.TraceEvent(System.Diagnostics.TraceEventType.Error, chain.ChainId, "Lost main monitor");
                        chain.Dispose();
                        return;
                    }
                    subscriptions.SubscriptionList.Add(gwcid);

                    // Channel never got the first answer
                    // So let's wait like the others
                    if (subscriptions.FirstValue)
                    {
                        currentMonitor.FirstValue = true;
                        currentMonitor.PacketCount = 1;
                    }
                    // Channel already got the first answer
                    // Send a ReadNotify to get the first value
                    else
                    {
                        /*DataPacket newPacket = (DataPacket)subscriptions.FirstPacket.Clone();
                        newPacket.Destination = packet.Sender;
                        newPacket.Parameter2 = packet.Parameter2;
                        newPacket.Sender = packet.Sender;
                        sendData(newPacket);*/

                        currentMonitor.FirstValue = true;
                        currentMonitor.PacketCount = 0;

                        UInt32 gwioid = CidGenerator.Next();
                        // Send an intial read-notify
                        DataPacket newPacket = DataPacket.Create(0, packet.Chain);
                        newPacket.Command = 15;
                        newPacket.DataCount = packet.DataCount;
                        newPacket.DataType = packet.DataType;
                        newPacket.Parameter1 = record.SID.Value;
                        newPacket.Parameter2 = gwioid;
                        newPacket.Destination = record.Destination;

                        record = InfoService.IOID.Create(gwioid);
                        record.Destination = packet.Sender;
                        record.IOID = 0;
                        record.SID = packet.Parameter2;
                        record.DBRType = packet.DataType;
                        record.DataCount = packet.DataCount;
                        record.CID = gwcid;

                        sendData(newPacket);
                    }
                }
            }
        }
        public override void DoRequest(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData)
        {
            /*Stopwatch sw = new Stopwatch();
            sw.Start();*/
            string channelName = packet.GetDataAsString();
            Record channelInfo = null;

            // Get a lock object for this particula channel name
            object lockOper = locks.GetOrAdd(channelName, new object());

            //if (InfoService.ChannelEndPoint.Knows(channelName))
            channelInfo = InfoService.ChannelEndPoint[channelName];

            // Never got this channel!
            if (channelInfo == null)
            {
                StorageService<string> searchService;
                if (chain.Side == ChainSide.SIDE_A)
                    searchService = InfoService.SearchChannelEndPointA;
                else
                    searchService = InfoService.SearchChannelEndPointB;

                if (!searchService.Knows(channelName))
                {
                    if (Log.WillDisplay(TraceEventType.Error))
                        Log.TraceEvent(TraceEventType.Error, chain.ChainId, "Created channel (" + channelName + ") without knowing where it should point at...");
                    chain.Dispose();
                    return;
                }
                channelInfo = searchService[channelName];
                channelInfo.ChainSide = chain.Side;
                InfoService.ChannelEndPoint[channelName] = channelInfo;

                channelInfo.GWCID = null;
            }
            //Console.WriteLine("Create 1: " + sw.Elapsed);

            if (Log.WillDisplay(TraceEventType.Verbose))
                Log.TraceEvent(TraceEventType.Verbose, chain.ChainId, "Request " + channelName + " with cid " + packet.Parameter1);

            SecurityAccess access;
            switch (chain.Side)
            {
                case Workers.ChainSide.SIDE_A:
                    access = chain.Gateway.Configuration.Security.EvaluateSideA(channelName, chain.Username, chain.Hostname, packet.Sender.Address.ToString());
                    break;
                default:
                    access = chain.Gateway.Configuration.Security.EvaluateSideB(channelName, chain.Username, chain.Hostname, packet.Sender.Address.ToString());
                    break;
            }

            // Don't have the right, return a fail create channel
            if (!access.Has(SecurityAccess.READ))
            {
                if (Log.WillDisplay(TraceEventType.Warning))
                    Log.TraceEvent(System.Diagnostics.TraceEventType.Warning, packet.Chain.ChainId, "Create channel " + channelName + " from " + packet.Sender + " while not having rights to read");
                DataPacket newPacket = DataPacket.Create(0, chain);
                newPacket.Command = 26;
                newPacket.Parameter1 = packet.Parameter1;
                newPacket.Sender = packet.Sender;
                newPacket.Destination = packet.Sender;
                sendData(newPacket);
                return;
            }

            var knownGWCID = false;
            var knownSID = false;
            lock (lockOper)
            {
                knownGWCID = channelInfo.GWCID.HasValue;
                knownSID = channelInfo.SID.HasValue;
            }

            // We never got back any answer, let's trash the GWCID to re-create it
            if (knownGWCID
                && !knownSID
                && (Gateway.Now - channelInfo.CreatedOn).TotalSeconds > 10)
            {
                channelInfo.GWCID = null;
                knownGWCID = false;
            }

            // Checks if we have already a channel open with the IOC or not
            // If we have it we can answer directly
            if (knownGWCID)
            {
                //Console.WriteLine("Create 2: " + sw.Elapsed);
                if (Log.WillDisplay(TraceEventType.Verbose))
                    Log.TraceEvent(System.Diagnostics.TraceEventType.Verbose, (packet.Chain == null ? 0 : packet.Chain.ChainId), "Request of a known channel (" + channelName + ")");
                // We need to check if this is something currently in creation

                // Seems we know all
                if (knownSID)
                {

                    Log.TraceEvent(TraceEventType.Verbose, chain.ChainId, "Cached responce create channel cid " + packet.Parameter1);

                    // Give back access rights before the create channel
                    DataPacket newPacket = DataPacket.Create(0, packet.Chain);
                    newPacket.Command = 22;
                    newPacket.DataType = 0;
                    newPacket.DataCount = 0;
                    newPacket.Parameter1 = packet.Parameter1;
                    newPacket.Parameter2 = (uint)access;
                    newPacket.Sender = packet.Sender;
                    newPacket.Destination = packet.Sender;
                    sendData(newPacket);

                    // Gives the create channel answer
                    newPacket = DataPacket.Create(0, packet.Chain);
                    newPacket.Command = 18;
                    // ReSharper disable PossibleInvalidOperationException
                    newPacket.DataType = channelInfo.DBRType.Value;
                    // ReSharper restore PossibleInvalidOperationException
                    // ReSharper disable PossibleInvalidOperationException
                    newPacket.DataCount = channelInfo.DataCount.Value;
                    // ReSharper restore PossibleInvalidOperationException
                    newPacket.Parameter1 = packet.Parameter1;
                    newPacket.Parameter2 = channelInfo.GWCID.Value;
                    newPacket.Sender = packet.Sender;
                    newPacket.Destination = packet.Sender;
                    sendData(newPacket);

                    chain.ChannelCid[channelName] = packet.Parameter1;

                    // We have all the info we can continue.
                    chain.Gateway.DoClientConnectedChannels(chain.ClientEndPoint.ToString(), channelName);

                    //Console.WriteLine("Create 2.1: " + sw.Elapsed);
                    return;
                }

                // Still in creation then let's wait till the channel actually is created
                lock (lockOper)
                {
                    uint clientCid = packet.Parameter1;
                    IPEndPoint clientIp = packet.Sender;
                    Log.TraceEvent(TraceEventType.Verbose, chain.ChainId, "Add event for " + clientCid);

                    channelInfo.GetNotification += delegate(object sender, DataPacket receivedPacket)
                    {
                        //Console.WriteLine("Create 5: " + sw.Elapsed);
                        Record record = InfoService.ChannelCid[receivedPacket.Parameter1];
                        if (record == null || record.Channel == null) // Response too late, we drop it.
                            return;

                        Record resChannelInfo = InfoService.ChannelEndPoint[record.Channel];
                        if (resChannelInfo == null)
                            return;

                        Log.TraceEvent(TraceEventType.Verbose, chain.ChainId, "Event responce create channel cid " + clientCid);

                        // Give back access rights before the create channel
                        DataPacket resPacket = DataPacket.Create(0, packet.Chain);
                        resPacket.Command = 22;
                        resPacket.DataType = 0;
                        resPacket.DataCount = 0;
                        //resPacket.Parameter1 = packet.Parameter1;
                        resPacket.Parameter1 = clientCid;
                        resPacket.Parameter2 = (uint)access;
                        resPacket.Sender = clientIp;
                        resPacket.Destination = clientIp;
                        TcpManager.SendClientPacket(resPacket);

                        resPacket = (DataPacket)receivedPacket.Clone();
                        resPacket.Command = 18;
                        resPacket.Destination = clientIp;
                        resPacket.Parameter1 = clientCid;
                        resPacket.Parameter2 = channelInfo.GWCID.Value;
                        resPacket.Sender = clientIp;
                        TcpManager.SendClientPacket(resPacket);

                        chain.ChannelCid[channelName] = clientCid;
                        chain.Gateway.DoClientConnectedChannels(chain.ClientEndPoint.ToString(), channelName);
                    };
                }
            }
            // We don't have, we need therefore to connect to the IOC to create one
            else
            {
                //Console.WriteLine("Create 3: " + sw.Elapsed);
                /*if (chain.ChannelCid.ContainsKey(channelName))
                {
                    if (Log.WillDisplay(TraceEventType.Warning))
                        Log.TraceEvent(System.Diagnostics.TraceEventType.Warning, (packet.Chain == null ? 0 : packet.Chain.ChainId), "Duplicated request (" + channelName + ")");
                }*/

                if (Log.WillDisplay(TraceEventType.Verbose))
                    Log.TraceEvent(System.Diagnostics.TraceEventType.Verbose, (packet.Chain == null ? 0 : packet.Chain.ChainId), "Request of a new channel (" + channelName + ")");
                channelInfo.GWCID = packet.Parameter1;

                UInt32 gwcid = CidGenerator.Next();
                Record record = InfoService.ChannelCid.Create(gwcid);
                record.Channel = channelName;
                record.GWCID = gwcid;
                record.Client = packet.Sender;
                record.AccessRight = access;
                record.Destination = channelInfo.Server;
                record.ChainSide = chain.Side;
                chain.ChannelCid[channelName] = packet.Parameter1;

                // Send create channel
                DataPacket newPacket = (DataPacket)packet.Clone();
                newPacket.Parameter1 = gwcid;
                // Version
                newPacket.Parameter2 = Gateway.CA_PROTO_VERSION;
                newPacket.Destination = channelInfo.Server;
                sendData(newPacket);

                chain.Gateway.DoClientConnectedChannels(chain.ClientEndPoint.ToString(), channelName);
            }
            //Console.WriteLine("Create 6: " + sw.Elapsed);
        }
 /// <summary>
 /// Doesn't have a response for this message
 /// </summary>
 /// <param name="packet"></param>
 /// <param name="chain"></param>
 public override void DoResponse(DataPacket packet, Workers.WorkerChain chain, DataPacketDelegate sendData)
 {
     throw new NotImplementedException();
 }