public ActionResult <string> Get(string channelId, string resourceId, string instance)
        {
            try
            {
                // Just because .NET is some weird kind of monster and doesn't like to play well with URLs... Thanks Microsoft
                // Note WebUtility outputs stuff in a CORRECT fashion while HttpUtility is NOT suitable for case sensitive systems
                channelId  = WebUtility.UrlDecode(channelId);
                resourceId = WebUtility.UrlDecode(resourceId);
                instance   = WebUtility.UrlDecode(instance);

                // Check if the request was created by the current instance
                if (KeySync.instance.Equals(instance))
                {
                    // Sync all the calendars
                    KeySync.runCal();
                }
                // Clean up the current channel, it's not valid
                else
                {
                    GService.service.Channels.Stop(KeySync.deleteChannel(channelId, resourceId)).Execute();
                }
            }
            catch (Exception e)
            {
                ControlRoom.SendErrorMessage("Google Sync error", e.Message);
            }

            return(instance);
        }
Beispiel #2
0
        // Update an employee using PlanningLibrary (layered code on google contacts)
        public void updateEmployee(XmlDocument doc)
        {
            // Parsing data from XmlDocument
            XmlNodeList UUID       = doc.GetElementsByTagName("UUID");
            XmlNodeList firstname  = doc.SelectNodes("//name/firstname");
            XmlNodeList lastname   = doc.SelectNodes("//name/lastname");
            XmlNodeList email      = doc.GetElementsByTagName("email");
            XmlNodeList xmlVersion = doc.GetElementsByTagName("version");

            // Logging parsed data
            Console.WriteLine(UUID[0].InnerText);
            Console.WriteLine(firstname[0].InnerText);
            Console.WriteLine(lastname[0].InnerText);
            Console.WriteLine(email[0].InnerText);
            Console.WriteLine(xmlVersion[0].InnerText);

            // Making Person(employee) with given data - makeperson converts the given data to <attendee> format
            var employee = PlanningLibrary.Program.makePerson(firstname[0].InnerText, lastname[0].InnerText, email[0].InnerText);

            // Adding/updating the Person(employee) to google people/contacts using method from PlanningLibrary
            // Expects an <attendee> (converted var employee), UUID, version
            Attendee.IupdateAttendee(employee, UUID[0].InnerText, xmlVersion[0].InnerText);

            Console.WriteLine("employee successfully updated");
            ControlRoom.SendConfirmationMessage("Planning: Employee successfully updated");
        }
Beispiel #3
0
        // Send a message to the RMQ queue
        public static void sendMessage(string doc)
        {
            Debug.WriteLine(doc);

            if (String.IsNullOrEmpty(doc))
            {
                return;
            }

            if (!ControlRoom.CheckMessage(doc))
            {
                throw new Exception();
            }

            var factory = new ConnectionFactory()
            {
                HostName = ConfigurationManager.AppSettings["server"].ToString(), UserName = ConfigurationManager.AppSettings["username"].ToString(), Password = ConfigurationManager.AppSettings["password"].ToString(), Port = Convert.ToInt32(ConfigurationManager.AppSettings["port"].ToString())
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare(exchange: ConfigurationManager.AppSettings["exchange"].ToString(), type: ConfigurationManager.AppSettings["type"].ToString());
                    var body = Encoding.UTF8.GetBytes(doc);
                    channel.BasicPublish(exchange: ConfigurationManager.AppSettings["exchange"].ToString(), routingKey: ConfigurationManager.AppSettings["routingKey"].ToString(), basicProperties: null, body: body);
                }
        }
        public FreeControlForm(ControlRoom new_controlRoom, int new_rtId)
        {
            InitializeComponent();
            // Set ControlRoom
            controlRoom = new_controlRoom;
            // Set RT id
            rtId = new_rtId;
            // Make coordCalc
            CoordCalc = controlRoom.RadioTelescopeControllers[rtId - 1].CoordinateController;
            // Set increment
            Increment = 1;
            UpdateIncrementButtons();
            // Add free control appt
            CurrentAppointment                    = new Appointment();
            CurrentAppointment.StartTime          = DateTime.UtcNow.AddSeconds(5);
            CurrentAppointment.EndTime            = DateTime.UtcNow.AddMinutes(15);
            CurrentAppointment.Status             = AppointmentStatusEnum.REQUESTED;
            CurrentAppointment.Type               = AppointmentTypeEnum.FREE_CONTROL;
            CurrentAppointment.SpectraCyberConfig = new SpectraCyberConfig(SpectraCyberModeTypeEnum.CONTINUUM);
            CurrentAppointment.TelescopeId        = rtId;
            CurrentAppointment.UserId             = 1;
            DatabaseOperations.AddAppointment(CurrentAppointment);
            //Calibrate Move
            CalibrateMove();

            logger.Info("FreeControl Form Initalized");
        }
Beispiel #5
0
        public void BuildUp()
        {
            SensorNetworkServer SN = new SensorNetworkServer(SnServerIp, SnServerPort, SnClientIp, SnClientPort, SnTelescopeId, true);

            rtManagementThreads = new List <RadioTelescopeControllerManagementThread>()
            {
                new RadioTelescopeControllerManagementThread(new RadioTelescopeController(
                                                                 new RadioTelescope(new SpectraCyberSimulatorController(new SpectraCyberSimulator()), new  SimulationPLCDriver(PlcIp, McuIp, McuPort, PlcPort, true, false), new Location(), new Orientation(), 1, SN))),
                new RadioTelescopeControllerManagementThread(new RadioTelescopeController(
                                                                 new RadioTelescope(new SpectraCyberSimulatorController(new SpectraCyberSimulator()), new  SimulationPLCDriver(PlcIp, McuIp, McuPort + 1, PlcPort + 1, true, false), new Location(), new Orientation(), 2, SN))),
                new RadioTelescopeControllerManagementThread(new RadioTelescopeController(
                                                                 new RadioTelescope(new SpectraCyberSimulatorController(new SpectraCyberSimulator()), new  SimulationPLCDriver(PlcIp, McuIp, McuPort + 2, PlcPort + 2, true, false), new Location(), new Orientation(), 3, SN))),
            };

            controlRoom = new ControlRoom(weatherStation, 87);

            // End the CR's listener's server. We have to do this until we stop hard-coding that dang value.
            // TODO: Remove this logic when the value is no longer hard-coded (issue #350)
            //PrivateObject listener = new PrivateObject(controlRoom.mobileControlServer);
            //((TcpListener)listener.GetFieldOrProperty("server")).Stop();

            controlRoom.RTControllerManagementThreads.Add(rtManagementThreads[0]);
            controlRoom.RTControllerManagementThreads.Add(rtManagementThreads[1]);
            controlRoom.RTControllerManagementThreads.Add(rtManagementThreads[2]);
        }
Beispiel #6
0
        /// <summary>
        /// Initializes the diagnostic form based off of the specified configuration.
        /// </summary>
        ///
        public DiagnosticsForm(ControlRoom controlRoom, int rtId)
        {
            InitializeComponent();
            az = 0.0;
            el = 0.0;



            this.controlRoom = controlRoom;


            this.rtId = rtId;

            dataGridView1.ColumnCount           = 2;
            dataGridView1.Columns[0].HeaderText = "Hardware";
            dataGridView1.Columns[1].HeaderText = "Status";

            GetHardwareStatuses();
            string[] spectraCyberRow   = { "SpectraCyber", statuses[0] };
            string[] weatherStationRow = { "Weather Station", statuses[1] };
            string[] mcuRow            = { "MCU", statuses[2] };
            string[] tempSensorRow     = { "Temp Sensor", statuses[3] };

            dataGridView1.Rows.Add(spectraCyberRow);
            dataGridView1.Rows.Add(weatherStationRow);
            dataGridView1.Rows.Add(mcuRow);
            dataGridView1.Update();

            SetCurrentAzimuthAndElevation();
            logger.Info("DiagnosticsForm Initalized");
        }
Beispiel #7
0
        public void BuildUp()
        {
            string IP = PLCConstants.LOCAL_HOST_IP;

            rtManagementThreads = new List <RadioTelescopeControllerManagementThread>()
            {
                new RadioTelescopeControllerManagementThread(new RadioTelescopeController(
                                                                 new RadioTelescope(new SpectraCyberController(new SpectraCyber()), new  SimulationPLCDriver(IP, IP, 8103, 8103, true, false), new Location(), new Orientation()))),
                new RadioTelescopeControllerManagementThread(new RadioTelescopeController(
                                                                 new RadioTelescope(new SpectraCyberController(new SpectraCyber()), new  SimulationPLCDriver(IP, IP, 8106, 8106, true, false), new Location(), new Orientation()))),
                new RadioTelescopeControllerManagementThread(new RadioTelescopeController(
                                                                 new RadioTelescope(new SpectraCyberController(new SpectraCyber()), new  SimulationPLCDriver(IP, IP, 8109, 8109, true, false), new Location(), new Orientation()))),
            };

            controlRoom = new ControlRoom(weatherStation);

            // End the CR's listener's server. We have to do this until we stop hard-coding that dang value.
            // TODO: Remove this logic when the value is no longer hard-coded (issue #350)
            PrivateObject listener = new PrivateObject(controlRoom.mobileControlServer);

            ((TcpListener)listener.GetFieldOrProperty("server")).Stop();

            controlRoom.RTControllerManagementThreads.Add(rtManagementThreads[0]);
            controlRoom.RTControllerManagementThreads.Add(rtManagementThreads[1]);
            controlRoom.RTControllerManagementThreads.Add(rtManagementThreads[2]);
        }
Beispiel #8
0
        // Weather Station override
        //public bool weatherStationOverride = false;

        public ControlRoomController(ControlRoom controlRoom)
        {
            ControlRoom             = controlRoom;
            WeatherMonitoringThread = new Thread(new ThreadStart(WeatherMonitoringRoutine))
            {
                Name = "Weather Monitoring Routine"
            };
            KeepWeatherMonitoringThreadAlive = false;
        }
 public ActionResult <UUID.Output.UuidOutput> Put(string uuid, int module, string id, int version, string type)
 {
     try
     {
         return(ModuleService.insert(uuid, module, id, version, type));
     }
     catch (Exception e)
     {
         ControlRoom.SendErrorMessage("UUID API failed", String.Format("Message: {0}, UUID: {1}, Module: {2}, Id: {3}, Version: {4}, Type: {5}", e.Message, uuid, module, id, version, type));
         return(StatusCode(500, e.Message));
     }
 }
 public ActionResult <UUID.Output.UuidOutput> Get(int module, string id, int version)
 {
     try
     {
         return(ModuleService.getUUID(module, id, version, ""));
     }
     catch (Exception e)
     {
         ControlRoom.SendErrorMessage("UUID API failed", String.Format("Message: {0}, Module: {1}, Id: {2}, Version: {3}", e.Message, module, id, version));
         return(StatusCode(500, e.Message));
     }
 }
Beispiel #11
0
 public ActionResult <IList <UUID.Output.IdOutput> > GetList(string uuid, int module, int version)
 {
     try
     {
         return(UUIDService.getByUUID(uuid, version).FindAll(e => e.module.Equals(module)));
     }
     catch (Exception e)
     {
         ControlRoom.SendErrorMessage("UUID API failed", String.Format("Message: {0}, UUID: {1}, Module: {2}, Version: {3}", e.Message, uuid, module, version));
         return(StatusCode(500, e.Message));
     }
 }
        public static void BringUp(TestContext context)
        {
            ControlRoom = new ControlRoom(new SimulationWeatherStation(100), 81);

            // End the CR's listener's server. We have to do this until we stop hard-coding that dang value.
            // TODO: Remove this logic when the value is no longer hard-coded (issue #350)
            // PrivateObject listener = new PrivateObject(ControlRoom.mobileControlServer);
            //((TcpListener)listener.GetFieldOrProperty("server")).Stop();

            CRController           = new ControlRoomController(ControlRoom);
            CalibrationOrientation = new Orientation(0, 90);
        }
 public ActionResult <IList <UUID.Output.UuidOutput> > Get(string id, string type)
 {
     try
     {
         return(ModuleService.getUUID(id, type));
     }
     catch (Exception e)
     {
         ControlRoom.SendErrorMessage("UUID API failed", String.Format("Message: {0}, ID: {1}, Type: {2}", e.Message, id, type));
         return(StatusCode(500, e.Message));
     }
 }
Beispiel #14
0
        protected override void ProcessDemo()
        {
            var mediator             = new Mediator();
            var controlRoom          = new ControlRoom(mediator);
            var defenseFortification = new DefenseFortification(mediator);

            mediator.Attach(controlRoom);
            mediator.Attach(defenseFortification);

            controlRoom.Send("Full defense mode!");
            defenseFortification.Send("Defense mode activated!");
        }
Beispiel #15
0
 public ActionResult <IList <UUID.Output.IdOutput> > Get(string uuid)
 {
     try
     {
         return(UUIDService.getByUUID(uuid, ""));
     }
     catch (Exception e)
     {
         ControlRoom.SendErrorMessage("UUID API failed", String.Format("Message: {0}, UUID: {1}", e.Message, uuid));
         return(StatusCode(500, e.Message));
     }
 }
 public ActionResult <Boolean> GetBool(string id, string type)
 {
     try
     {
         ModuleService.getUUID(id, type);
         return(true);
     }
     catch (Exception e)
     {
         ControlRoom.SendErrorMessage("UUID API failed", String.Format("Message: {0}, ID: {1}, Type: {2}", e.Message, id, type));
         return(StatusCode(500, false));
     }
 }
Beispiel #17
0
        // Delete a calendar using PlanningLibrary (layered code on google calendar)
        public void deleteCalendar(XmlDocument doc)
        {
            // Parsing data from XmlDocument
            XmlNodeList id = doc.GetElementsByTagName("UUID");

            // Logging parsed data
            Console.WriteLine(id[0].InnerText);

            // Delete a calendar, filled with parsed data from XmlDocument and finally sent with PlanningLibrary method.
            // Expects a UUID
            Calendarss.IdeleteCalendarById(id[0].InnerText);

            Console.WriteLine("Event successfully deleted");
            ControlRoom.SendConfirmationMessage("Planning: Event successfully deleted");
        }
Beispiel #18
0
        // Delete an employee using PlanningLibrary (layered code on google contacts)
        public void deleteEmployee(XmlDocument doc)
        {
            //Parsing data from XmlDocument
            XmlNodeList UUID = doc.GetElementsByTagName("UUID");

            // Logging parsed data
            Console.WriteLine(UUID[0].InnerText);

            // Deleting the Person(employee) to google people/contacts using method from PlanningLibrary
            // Expects a UUID
            Attendee.IdeleteAttendee(UUID[0].InnerText);

            Console.WriteLine("employee successfully deleted");
            ControlRoom.SendConfirmationMessage("Planning: Employee successfully deleted");
        }
Beispiel #19
0
        public RemoteListener(int port, ControlRoom control)
        {
            logger.Debug(Utilities.GetTimeStamp() + ": Setting up remote listener");
            server = new TcpListener(port);

            controlRoom = control;

            // Start listening for client requests.
            server.Start();

            KeepTCPMonitoringThreadAlive = true;
            // start the listening thread
            TCPMonitoringThread = new Thread(new ThreadStart(TCPMonitoringRoutine));

            TCPMonitoringThread.Start();
        }
Beispiel #20
0
        // Delete an event on an existing calendar using PlanningLibrary (layered code on google calendar)
        public void deleteEvent(XmlDocument doc)
        {
            // Parsing data from XmlDocument
            XmlNodeList EventID    = doc.GetElementsByTagName("UUID");       // gets the event id (not calendar)
            XmlNodeList CalendarID = doc.GetElementsByTagName("event_UUID"); // event_UUID is the field to retrieve a CALENDAR id and NOT event

            // Logging parsed data
            Console.WriteLine(CalendarID[0].InnerText);
            Console.WriteLine(EventID[0].InnerText);

            // Delete a calendar, filled with parsed data from XmlDocument and finally sent with PlanningLibrary method.
            // Expects an event UUID and calendar UUID
            Eventss.IDeleteEventById(EventID[0].InnerText, CalendarID[0].InnerText);

            Console.WriteLine("Session successfully deleted");
            ControlRoom.SendConfirmationMessage("Planning: Session successfully deleted");
        }
Beispiel #21
0
        public ManualControlForm(ControlRoom new_controlRoom, int rtId)
        {
            InitializeComponent();

            // Set ControlRoom
            controlRoom = new_controlRoom;

            // Make rt_controller
            rt_controller = controlRoom.RadioTelescopeControllers[rtId - 1];

            // Update Text
            UpdateText("Manual Control for Radio Telescope " + rt_controller.RadioTelescope.Id.ToString());

            // Set speed
            comboBox1.Text = "0.1 RPM";
            speed          = 16667;

            logger.Info("ManualControlForm Initalized");
        }
Beispiel #22
0
        public void BuildUp()
        {
            string IP = PLCConstants.LOCAL_HOST_IP;

            rtManagementThreads = new List <RadioTelescopeControllerManagementThread>()
            {
                new RadioTelescopeControllerManagementThread(new RadioTelescopeController(
                                                                 new RadioTelescope(new SpectraCyberController(new SpectraCyber()), new  SimulationPLCDriver(IP, IP, 8103, 8103), new Location(), new Orientation()))),
                new RadioTelescopeControllerManagementThread(new RadioTelescopeController(
                                                                 new RadioTelescope(new SpectraCyberController(new SpectraCyber()), new  SimulationPLCDriver(IP, IP, 8106, 8106), new Location(), new Orientation()))),
                new RadioTelescopeControllerManagementThread(new RadioTelescopeController(
                                                                 new RadioTelescope(new SpectraCyberController(new SpectraCyber()), new  SimulationPLCDriver(IP, IP, 8109, 8109), new Location(), new Orientation()))),
            };

            controlRoom = new ControlRoom(weatherStation);
            controlRoom.RTControllerManagementThreads.Add(rtManagementThreads[0]);
            controlRoom.RTControllerManagementThreads.Add(rtManagementThreads[1]);
            controlRoom.RTControllerManagementThreads.Add(rtManagementThreads[2]);
        }
Beispiel #23
0
        public EditScriptsForm(ControlRoom new_controlRoom, int rtId)
        {
            InitializeComponent();

            // Set ControlRoom
            controlRoom = new_controlRoom;

            // Make rt_controller
            rt_controller = controlRoom.RadioTelescopeControllers[rtId - 1];

            // Update Text
            UpdateText("Edit Scripts in Control Form for Radio Telescope " + rt_controller.RadioTelescope.Id.ToString());

            // Set speed
            // comboBox1.Text = "0.1 RPM";
            speed = 0.1;

            logger.Info(Utilities.GetTimeStamp() + ": Edit Script Form Initalized");
        }
Beispiel #24
0
        // Update a calendar using PlanningLibrary (layered code on google calendar)
        public void updateCalendar(XmlDocument doc)
        {
            // Parsing data from XmlDocument
            XmlNodeList titel      = doc.GetElementsByTagName("eventName");
            XmlNodeList id         = doc.GetElementsByTagName("UUID");
            XmlNodeList xmlVersion = doc.GetElementsByTagName("version");

            // Logging parsed data
            Console.WriteLine(titel[0].InnerText);
            Console.WriteLine(id[0].InnerText);
            Console.WriteLine(xmlVersion[0].InnerText);

            // Creating a new <google.api> calendar to update an existing one, filled with parsed data from XmlDocument and finally sent with PlanningLibrary method.
            // Expects a <google.api> calendar, UUID, version
            Google.Apis.Calendar.v3.Data.Calendar calendar = new Google.Apis.Calendar.v3.Data.Calendar();
            calendar.Summary = titel[0].InnerText;
            Calendarss.IupdateCalendarById(calendar, id[0].InnerText, xmlVersion[0].InnerText);

            Console.WriteLine("Event successfully updated");
            ControlRoom.SendConfirmationMessage("Planning: Event successfully updated");
        }
Beispiel #25
0
        public void Initialize()
        {
            RadioTelescope = new RadioTelescope();

            AbstractPLCDriver PLC = new SimulationPLCDriver(PlcIp, McuIp, McuPort, PlcPort, true, false);

            RadioTelescope.PLCDriver = PLC;

            SensorNetworkServer SN = new SensorNetworkServer(SnServerIp, SnServerPort, SnClientIp, SnClientPort, SnTelescopeId, true);

            RadioTelescope.SensorNetworkServer = SN;

            RtController = new RadioTelescopeController(RadioTelescope);

            AbstractWeatherStation WS = new SimulationWeatherStation(1000);

            ControlRoom = new ControlRoom(WS, 80);

            ControlRoom.mobileControlServer.rtController = RtController;

            PrivListener = new PrivateObject(ControlRoom.mobileControlServer);
        }
Beispiel #26
0
 public static void BringUp(TestContext context)
 {
     ControlRoom            = new ControlRoom(new SimulationWeatherStation(100));
     CRController           = new ControlRoomController(ControlRoom);
     CalibrationOrientation = new Orientation(0, 90);
 }
Beispiel #27
0
        public static void Main(string[] args)
        {
            new GService();

            // Create RMQ connection
            var factory = new ConnectionFactory()
            {
                HostName = ConfigurationManager.AppSettings["server"].ToString(), UserName = ConfigurationManager.AppSettings["username"].ToString(), Password = ConfigurationManager.AppSettings["password"].ToString(), Port = Convert.ToInt16(ConfigurationManager.AppSettings["port"].ToString())
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    // Configurating channel
                    channel.ExchangeDeclare(exchange: ConfigurationManager.AppSettings["exchange"].ToString(), type: ConfigurationManager.AppSettings["type"].ToString());
                    channel.QueueBind(queue: ConfigurationManager.AppSettings["queue"].ToString(), exchange: ConfigurationManager.AppSettings["exchange"].ToString(), routingKey: ConfigurationManager.AppSettings["routingKey"].ToString());

                    Console.WriteLine("[*] Waiting for messages.");

                    // Create a RMQ listener
                    var consumer = new EventingBasicConsumer(channel);

                    consumer.Received += (model, ea) =>
                    {
                        try
                        {
                            // Load in the the message
                            var message = Encoding.UTF8.GetString(ea.Body);
                            //check validity of message with controlroom nuget package / library
                            var valid = ControlRoom.CheckMessage(message);
                            Console.WriteLine("Message is valid: " + valid);
                            Console.WriteLine(" [x] {0}", message);

                            if (!valid)
                            {
                                throw new CleanException();
                            }

                            // Create a new xml doc to catch message
                            XmlDocument doc = new XmlDocument();
                            doc.LoadXml(message);

                            // Find out who the sender is and if it is set or not
                            // Discard any messages that we send ourselves so we do not create a loop
                            XmlNodeList xmlSender = doc.GetElementsByTagName("sender");
                            if (xmlSender.Count == 0 || xmlSender[0].InnerText.ToLower().Equals("planning"))
                            {
                                throw new CleanException();
                            }

                            // Get a the messageType, stop if we cannot find it
                            // Create a local messagetype variable (lower version)
                            XmlNodeList xmlMessageType = doc.GetElementsByTagName("messageType");
                            if (xmlMessageType.Count == 0)
                            {
                                throw new CleanException();
                            }

                            string messageType = xmlMessageType[0].InnerText.ToLower();

                            // Check if the message is supported or not
                            if (!messageTypes.Contains(messageType))
                            {
                                Console.WriteLine("Unsupported messageType found {0}", messageType);
                                throw new CleanException();
                            }

                            // Version checks & parsing, get the latest version from the UUID master
                            XmlNodeList xmlVersion = doc.GetElementsByTagName("version");
                            int         version    = 0;

                            XmlNodeList xmlUUID = doc.GetElementsByTagName("session_UUID");

                            if (xmlUUID.Count == 0)
                            {
                                xmlUUID = doc.GetElementsByTagName("UUID");
                            }

                            int latestVersion = Calendarss.getversion(xmlUUID[0].InnerText);

                            if (xmlVersion.Count > 0)
                            {
                                if (xmlVersion[0].InnerText != string.Empty)
                                {
                                    version = Convert.ToInt32(xmlVersion[0].InnerText);
                                }
                            }

                            // Check if we should discard the message or not
                            if (latestVersion >= version)
                            {
                                Console.WriteLine("Receiving old data, discarding; Received: {0} Latest: {1}", version, latestVersion);
                                throw new CleanException();
                            }

                            // IsActive checks & parsing
                            bool        isActive    = true;
                            XmlNodeList xmlIsActive = doc.GetElementsByTagName("isActive");
                            if (xmlIsActive.Count > 0)
                            {
                                if (xmlIsActive[0].InnerText != string.Empty)
                                {
                                    isActive = Convert.ToBoolean(Convert.ToInt16(xmlIsActive[0].InnerText));
                                }
                            }

                            Console.WriteLine("Trying to process a messageType {0}, with version {1} and active state of {2}", messageType, version, isActive);

                            // Picking up messageType (event/session/employee) with CRUD operation based off isActive/version
                            switch (messageType)
                            {
                            case "createevent":
                                if (isActive == false)
                                {
                                    new ReceiveMessage().deleteCalendar(doc);
                                    break;
                                }
                                else if (version == 1)
                                {
                                    new ReceiveMessage().createCalendar(doc);
                                    break;
                                }
                                else if (version > 1)
                                {
                                    new ReceiveMessage().updateCalendar(doc);
                                    break;
                                }

                                break;

                            case "createsession":
                                if (isActive == false)
                                {
                                    new ReceiveMessage().deleteEvent(doc);
                                    break;
                                }
                                else if (version == 1)
                                {
                                    new ReceiveMessage().createEvent(doc);
                                    break;
                                }
                                else if (version > 1)
                                {
                                    new ReceiveMessage().updateEvent(doc);
                                    break;
                                }
                                break;

                            case "createemployee":
                                if (isActive == false)
                                {
                                    new ReceiveMessage().deleteEmployee(doc);
                                    break;
                                }
                                else if (version == 1)
                                {
                                    new ReceiveMessage().createEmployee(doc);
                                    break;
                                }
                                else if (version > 1)
                                {
                                    new ReceiveMessage().updateEmployee(doc);
                                    break;
                                }

                                break;

                            default:
                                break;
                            }

                            // Nothing went wrong?! Good! Send an ack to RMQ
                            channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                        }

                        catch (CleanException e)
                        {
                            // Nothing went wrong, we're just invalidating this message
                            channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                        }
                        // Attendee overlay exception
                        catch (AttendeeOverlayException e)
                        {
                            // Something went wrong, we're just invalidating this message & notifying the CR
                            channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                            ControlRoom.SendErrorMessage("Planning Attendee overlay error", e.Message);
                        }
                        // Date is invalid
                        catch (DateExpception e)
                        {
                            // Something went wrong, we're just invalidating this message & notifying the CR
                            channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                            ControlRoom.SendErrorMessage("Planning Invalid date error", e.Message);
                        }

                        catch (DeletedException e)
                        {
                            // Something went wrong, we're just invalidating this message & notifying the CR
                            channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                            ControlRoom.SendErrorMessage("Planning Delete error", e.Message);
                        }
                        // Duplication error
                        catch (DuplicationException e)
                        {
                            // Something went wrong, we're just invalidating this message & notifying the CR
                            channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                            ControlRoom.SendErrorMessage("Planning Duplication error", e.Message);
                        }
                        // Format error (could possibly appear with dates)
                        catch (FormatException e)
                        {
                            // Something went wrong, we're just invalidating this message & notifying the CR
                            channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                            ControlRoom.SendErrorMessage("Planning Formatting error", e.Message);
                        }
                        // Location overlaying with another
                        catch (LocationOverlayException e)
                        {
                            // Something went wrong, we're just invalidating this message & notifying the CR
                            channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                            ControlRoom.SendErrorMessage("Planning Location overlay error", e.Message);
                        }
                        // Unexpectedly could not delete
                        catch (NotDeletedException e)
                        {
                            // Something went wrong, we're just invalidating this message & notifying the CR
                            channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                            ControlRoom.SendErrorMessage("Planning Not deleted error", e.Message);
                        }
                        // Not found exception
                        catch (NotFoundException e)
                        {
                            // Something went wrong, we're just invalidating this message & notifying the CR
                            channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                            ControlRoom.SendErrorMessage("Planning Not found error", e.Message);
                        }
                        // Requirements do not match
                        catch (RequirementsNotMetcs e)
                        {
                            // Something went wrong, we're just invalidating this message & notifying the CR
                            channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                            ControlRoom.SendErrorMessage("Planning Requirements not met error", e.Message);
                        }
                        // Server error
                        catch (ServerFault e)
                        {
                            // Something went wrong, we're just invalidating this message & notifying the CR
                            channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                            ControlRoom.SendErrorMessage("Planning Server error", e.Message);
                        }
                        // Wrong version of message (got vers < curr vers)
                        catch (WrongVersionException e)
                        {
                            // Something went wrong, we're just invalidating this message & notifying the CR
                            channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                            ControlRoom.SendErrorMessage("Planning Wrong version error", e.Message);
                        }

                        //all exceptions catcher
                        catch (Exception e)
                        {
                            Console.WriteLine(e.StackTrace);

                            // In case something goes wrong...
                            //channel.BasicNack(deliveryTag: ea.DeliveryTag, multiple: false, requeue: false);
                            ControlRoom.SendErrorMessage("Planning Receiver error", e.Message);
                        }
                    };

                    channel.BasicConsume(queue: ConfigurationManager.AppSettings["queue"].ToString(), autoAck: Convert.ToBoolean(ConfigurationManager.AppSettings["autoAck"].ToString()), consumer: consumer);
                    Console.WriteLine("Press any key to exit planning RabbitMQ receiver");
                    Console.ReadKey(true);
                }
        }
Beispiel #28
0
        // Update an event on an existing calendar using PlanningLibrary (layered code on google calendar)
        public void updateEvent(XmlDocument doc)
        {
            // Parsing data from XmlDocument
            XmlNodeList titel      = doc.GetElementsByTagName("titel");
            XmlNodeList desc       = doc.GetElementsByTagName("desc");
            XmlNodeList lokaal     = doc.GetElementsByTagName("lokaal");
            XmlNodeList start      = doc.GetElementsByTagName("start");
            XmlNodeList end        = doc.GetElementsByTagName("end");
            XmlNodeList EventID    = doc.GetElementsByTagName("session_UUID"); // Gets the event id (not calendar)
            XmlNodeList CalendarID = doc.GetElementsByTagName("event_UUID");   // event_UUID is the field to retrieve a CALENDAR id and NOT event
            XmlNodeList xmlVersion = doc.GetElementsByTagName("version");

            // Logging parsed data
            Console.WriteLine(titel[0].InnerText);
            Console.WriteLine(desc[0].InnerText);
            Console.WriteLine(lokaal[0].InnerText);
            Console.WriteLine(start[0].InnerText);
            Console.WriteLine(end[0].InnerText);
            Console.WriteLine(EventID[0].InnerText);
            Console.WriteLine(CalendarID[0].InnerText);
            Console.WriteLine(xmlVersion[0].InnerText);

            // Reformatting time to google api time
            // Null iformatprovider argument as string is time represenation
            DateTime event_begin = DateTime.ParseExact(start[0].InnerText, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);
            DateTime event_end   = DateTime.ParseExact(end[0].InnerText, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);

            // Logging parsed data which has been reformatted
            Console.WriteLine(event_begin);
            Console.WriteLine(event_end);

            // Create a new <google.api> event to update an existing one, fields filled in with parsed data from XmlDocument
            Event e = new Event();

            e.Summary     = titel[0].InnerText;
            e.Location    = lokaal[0].InnerText;
            e.Description = desc[0].InnerText;
            e.Start       = new EventDateTime {
                DateTime = event_begin
            };                                                      //conversie System Datetime to Google Apis Calendar V3 Data EventDateTime
            e.End = new EventDateTime {
                DateTime = event_end
            };                                                  //conversie System Datetime to Google Apis Calendar V3 Data EventDateTime

            // List which will contain every user (attendee or employee) that was in the XmlDocument
            List <string> people = new List <string>();

            // Iterate every user into the list
            foreach (XmlNode speaker in doc.SelectNodes("//users/UUID"))
            {
                var person = speaker.InnerText;

                Console.WriteLine(person);

                people.Add(person);
            }

            // Using PlanningLibrary method which awaits a List of users and convert it to Attendees (attendees are added to an event and must be existing in google contacts)
            e.Attendees = PlanningLibrary.Program.convertPersonToAttendee(people);

            // Creates a new event to update an existing event in a specified calendar(no value, default primary calendar), filled with parsed data from XmlDocument and finally sent with PlanningLibrary method.
            // Expects a <google.api> event, calendar UUID, event UUID, version
            Eventss.IupdateEventById(e, CalendarID[0].InnerText, EventID[0].InnerText, xmlVersion[0].InnerText);

            Console.WriteLine("Session successfully updated");
            ControlRoom.SendConfirmationMessage("Planning: Session successfully updated");
        }
Beispiel #29
0
        // Create a calendar XML message
        public static string calMessage(CalendarListEntry cal)
        {
            string version = "";
            string uuid    = "";

            try
            {
                // Fetch data from the UUID master
                UUID uuidMaster = new UUID();

                // Check if the calendar exists or not; create or update the UUID
                try
                {
                    uuid = uuidMaster.GetUuidBy(7, cal.Id);

                    // uuid exists, so it is an update request -> check time name difference with
                    IdOutput output = JsonConvert.DeserializeObject <IdOutput>(uuidMaster.GetIdBy(uuid, 7));

                    // Delete detected
                    if (cal.Deleted == true)
                    {
                        // Event was made trough the interface, not us
                        version = (output.version + 1).ToString();
                    }
                    else
                    {
                        IdOutput name = JsonConvert.DeserializeObject <IdOutput>(uuidMaster.GetIdBy(String.Format("name-property-{0}", cal.Id), 7));

                        // Name change detected
                        if (!cal.Summary.Trim().Equals(name.id))
                        {
                            // update the name in the uuid master
                            uuidMaster.PutUpdateUUID(String.Format("name-property-{0}", cal.Id), cal.Summary.Trim(), Calendarss.getversion(String.Format("name-property-{0}", cal.Id)) + 1);

                            // Event was made trough the interface, not us
                            version = (output.version + 1).ToString();
                        }
                    }

                    if (version.Equals(output.version))
                    {
                        return("");
                    }

                    uuidMaster.PutUpdateUUID(uuid, cal.Id, Convert.ToInt32(version));
                }
                // UUID did not exist for the calendar, create it and make an entry for the calendar name
                catch (Exception e)
                {
                    // Create listener :)
                    GService.service.Events.Watch(KeySync.newChannel(String.Format("&calId={0}", cal.Id)), cal.Id).Execute();

                    uuid = uuidMaster.PutCreateUUID(cal.Id);
                    uuidMaster.PutUpdateUUID(String.Format("name-property-{0}", cal.Id), cal.Summary.Trim(), 1);

                    version = "1";
                }
            }
            catch (Exception e)
            {
                // Notify CR when something happens
                ControlRoom.SendErrorMessage("Google Calendar Sync Error", e.Message);
                return("");
            }

            // Construct the XML msg
            return("<message>" +
                   "<header><messageType>CreateEvent</messageType><description>CRUD of an event</description><sender>planning</sender></header>" +
                   "<datastructure>" +
                   "<UUID>" + uuid + "</UUID>" +
                   "<eventName>" + cal.Summary + "</eventName>" +
                   "<timestamp>" + new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds() + "</timestamp>" +
                   "<isActive>" + (cal.Deleted == true ? "0" : "1") + "</isActive>" +
                   "<version>" + version + "</version>" +
                   "<extraField></extraField>" +
                   "</datastructure>" +
                   "</message>");
        }
Beispiel #30
0
        // Construct a message based on an Event obj
        public static string eventMessage(Google.Apis.Calendar.v3.Data.Event eventObj, string calId)
        {
            string version    = "";
            string uuid       = "";
            string event_uuid = "";
            string users      = "";

            // Setup up the Google People service in order to convert attendees to UUIDs
            PeopleResource.ConnectionsResource.ListRequest peopleRequest = GService.peopleService.People.Connections.List("people/me");
            peopleRequest.PersonFields = "names,emailAddresses,userDefined";
            Google.Apis.PeopleService.v1.Data.ListConnectionsResponse connectionsResponse = peopleRequest.Execute();
            IList <Person> connections = connectionsResponse.Connections;

            try
            {
                // Fetch data from the UUID master
                UUID uuidMaster = new UUID();

                // Check if the calendar exists in our system
                try
                {
                    event_uuid = uuidMaster.GetUuidBy(7, calId);
                }
                catch (Exception e)
                {
                    return("");
                }

                // Check if the event exists or not; create or update the UUID
                try
                {
                    uuid = uuidMaster.GetUuidBy(7, eventObj.Id);

                    // uuid exists, so it is an update request -> check time difference with uuid master
                    IdOutput output = JsonConvert.DeserializeObject <IdOutput>(uuidMaster.GetIdBy(uuid, 7));

                    // Add some fake delay
                    output.timestamp.AddSeconds(10);

                    if (eventObj.Updated < output.timestamp)
                    {
                        return("");
                    }

                    // Event was made trough the interface, not us
                    version = (output.version + 1).ToString();

                    uuidMaster.PutUpdateUUID(uuid, eventObj.Id, Convert.ToInt32(version));
                }
                catch (Exception e)
                {
                    uuid    = uuidMaster.PutCreateUUID(eventObj.Id);
                    version = "1";
                }

                if (eventObj.Attendees != null)
                {
                    // Convert all the attendees to UUIDs (employees & speakers)
                    foreach (var user in eventObj.Attendees.ToList())
                    {
                        foreach (var person in connections)
                        {
                            if (person.EmailAddresses.Where(email => email.Value.ToLower().Equals(user.Email.ToLower())).Count() > 0)
                            {
                                users += "<UUID>" + (person.UserDefined.First(ud => ud.Key.ToLower().Equals("uuid")).Value) + "</UUID>";
                            }
                        }
                    }
                }

                if (String.IsNullOrEmpty(users))
                {
                    users = "<UUID/>";
                }
            }
            catch (Exception e)
            {
                // Notify CR when something happens
                ControlRoom.SendErrorMessage("Google Calendar Sync Error", e.Message);
                return(e.StackTrace);
            }

            try
            {
                // Test for overlaying data, notify control room just in case
                ExceptionHandler <Google.Apis.Calendar.v3.Data.Event> .DateOverlay(eventObj.Start.DateTime, eventObj.End.DateTime);

                ExceptionHandler <Google.Apis.Calendar.v3.Data.Event> .LocationOverlay(eventObj.Start.DateTime, eventObj.End.DateTime, eventObj.Location, eventObj.Id);

                ExceptionHandler <Google.Apis.Calendar.v3.Data.Event> .AttendeeOverlay(eventObj.Start.DateTime, eventObj.End.DateTime, eventObj.Attendees, eventObj.Id);
            }
            catch (Exception e)
            {
                ControlRoom.SendErrorMessage("Google Calendar Overlay Error", e.Message);
            }


            // Construct the XML msg
            return("<message>" +
                   "<header><messageType>CreateSession</messageType><description>CRUD of a session</description><sender>planning</sender></header>" +
                   "<datastructure>" +
                   "<event_UUID>" + event_uuid + "</event_UUID>" +
                   "<session_UUID>" + uuid + "</session_UUID>" +
                   "<titel>" + eventObj.Summary + "</titel>" +
                   "<desc>" + eventObj.Description + "</desc>" +
                   "<users>" + users + "</users>" +
                   "<lokaal>" + eventObj.Location + "</lokaal>" +
                   "<start>" + eventObj.Start.DateTime.Value.ToString("yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture) + "</start>" +
                   "<end>" + eventObj.End.DateTime.Value.ToString("yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture) + "</end>" +
                   "<version>" + version + "</version>" +
                   "<timestamp>" + new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds() + "</timestamp>" +
                   "<isActive>" + (eventObj.Status == "cancelled" ? "0" : "1") + "</isActive>" +
                   "<extraField></extraField>" +
                   "</datastructure>" +
                   "</message>");
        }