Ejemplo n.º 1
0
        public static void getMessage()
        {
            //Initialize instance to perform CRUD operation on the Active Directory DB
            CRUD = new CRUD();
            CRUD.Binding();

            //Initialize new connection to the RabbitMQ server
            var factory = new ConnectionFactory()
            {
                HostName = "10.3.56.6"
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    //Declare Exchhange
                    channel.ExchangeDeclare(exchange: "direct_logs",
                                            type: "direct");
                    var queueName = channel.QueueDeclare().QueueName;

                    //Bind to queue where to consume data from
                    channel.QueueBind(queue: queueName,
                                      exchange: "direct_logs",
                                      routingKey: Severity.AD.ToString());
                    Console.WriteLine(" [*] Waiting for messages.");

                    //Declare consumer delegate to execute custom code on each event/message recieved
                    var consumer = new EventingBasicConsumer(channel);
                    consumer.Received += (model, ea) =>
                    {
                        //Convert message from bytes into a XML string
                        var body       = ea.Body.ToArray();
                        var message    = Encoding.UTF8.GetString(body);
                        var routingKey = ea.RoutingKey;

                        Console.WriteLine(" [x] Recieved '{0}':'{1}'", routingKey, message);

                        XmlSchemaSet schema = new XmlSchemaSet();
                        schema.Add("", "Userxsd.xsd");
                        XDocument xml = XDocument.Parse(message, LoadOptions.SetLineInfo);


                        bool xmlValidation = true;
                        //If XML from the GUI, skip XML Validation as some XML formats are not valid and will throw errors
                        if (XMLParser.ReadXMLTag(message, "origin") != "GUI")
                        {
                            xml.Validate(schema, (sender, e) =>
                            {
                                xmlValidation = false;
                            });
                        }

                        //Check if validation is true
                        if (xmlValidation)
                        {
                            Console.WriteLine("Consumer: valid");

                            //Check if the XML comes from the GUI or the UUID
                            if (XMLParser.ReadXMLTag(message, "origin") == "GUI")
                            {
                                var oper = XMLParser.ReadXMLTag(message, "method");
                                //Method that only comes from the GUI, it asks for more info on the user with only the Container name
                                if (oper.Equals("READ"))
                                {
                                    //Only 2 options, UPDATE or DELETE
                                    if (XMLParser.ReadXMLTag(message, "goal").Equals("UPDATE"))
                                    {
                                        //Return User data to GUI to able to display and change the data
                                        if (!ProducerGUI.send(XMLParser.ObjectToXML(CRUD.FindADUser(XMLParser.ReadXMLTag(message, "cn")).ADObjectToIntraUserObject()), Severity.GUI.ToString()))
                                        {
                                            Console.WriteLine("##################################################");
                                            Console.WriteLine($"#    Producing Message on Queue has FAILED       #");
                                            Console.WriteLine("##################################################");
                                        }
                                    }
                                    else
                                    {
                                        "DELETE".OperationToCRUD(CRUD.FindADUser(XMLParser.ReadXMLTag(message, "cn")).ADObjectToIntraUserObject(), CRUD);
                                    }
                                }
                                else
                                {
                                    oper.OperationToCRUD(XMLParser.XMLToObject <IntraUser>(message), CRUD);
                                }
                            }
                            else if (XMLParser.ReadXMLTag(message, "origin") == "UUID")
                            {
                                /**
                                 *  Both DELETE and UPDATE/CREATE have different formats XML that gets returned from the UUID
                                 *  This poses a problem when converting to different user objects.
                                 *  To be safe and alsow the problem with empty tags dissapearing,
                                 *  the outgoing XML is HARDCODED with dynamic user data
                                 */
                                if (XMLParser.ReadXMLTag(message, "method") != "DELETE")
                                {
                                    var user = XMLParser.XMLToObject <ExtraUser>(message);

                                    //Replace attributes to send a new message on the Queue
                                    user.MetaData.Origin    = "AD";
                                    user.MetaData.TimeStamp = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss%K");

                                    //<?xml version="1.0" encoding="utf-8"?>
                                    string xmlmessage = "<user><header>" +
                                                        "<UUID>" + user.MetaData.UUIDMaster + "</UUID>" +
                                                        "<method>" + user.MetaData.Methode + "</method>" +
                                                        "<origin>" + user.MetaData.Origin + "</origin>" +
                                                        "<version>" + user.MetaData.Version + "</version>" +
                                                        "<sourceEntityId></sourceEntityId>" +
                                                        "<timestamp>" + user.MetaData.TimeStamp + "</timestamp>" +
                                                        "</header>" +
                                                        "<body>" +
                                                        "<firstname>" + user.UserData.FirstName + "</firstname>" +
                                                        "<lastname>" + user.UserData.LastName + "</lastname>" +
                                                        "<email>" + user.UserData.Email + "</email>" +
                                                        "<birthday>" + user.UserData.BirthDay + "</birthday>" +
                                                        "<role>" + user.UserData.Role + "</role>" +
                                                        "<study>" + user.UserData.Study + "</study>" +
                                                        "</body></user>";

                                    //Produce a message on the User queue
                                    if (!ProducerV2.Send(xmlmessage, Severity.user.ToString()))
                                    {
                                        Console.WriteLine("##################################################");
                                        Console.WriteLine($"# Producing Message on the User Queue has FAILED #");
                                        Console.WriteLine("##################################################");
                                    }
                                }
                                else
                                {
                                    var user = XMLParser.XMLToObject <UUIDUser>(message);

                                    //Replace attributes to send a new message on the Queue
                                    user.MetaData.Origin    = "AD";
                                    user.MetaData.TimeStamp = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss%K");

                                    //<?xml version="1.0" encoding="utf-8"?>
                                    string xmlmessage = "<user><header>" +
                                                        "<UUID>" + user.MetaData.UUIDMaster + "</UUID>" +
                                                        "<method>" + user.MetaData.Methode + "</method>" +
                                                        "<origin>" + user.MetaData.Origin + "</origin>" +
                                                        "<version></version>" +
                                                        "<sourceEntityId></sourceEntityId>" +
                                                        "<timestamp>" + user.MetaData.TimeStamp + "</timestamp>" +
                                                        "</header>" +
                                                        "<body>" +
                                                        "<firstname>" + user.UserData.FirstName + "</firstname>" +
                                                        "<lastname>" + user.UserData.LastName + "</lastname>" +
                                                        "<email>" + user.UserData.Email + "</email>" +
                                                        "<birthday>" + user.UserData.BirthDay + "</birthday>" +
                                                        "<role>" + user.UserData.Role + "</role>" +
                                                        "<study>" + user.UserData.Study + "</study>" +
                                                        "</body></user>";

                                    //Produce a message on the User queue
                                    if (!ProducerV2.Send(xmlmessage, Severity.user.ToString()))
                                    {
                                        Console.WriteLine("##################################################");
                                        Console.WriteLine($"# Producing Message on the User Queue has FAILED #");
                                        Console.WriteLine("##################################################");
                                    }
                                }
                            }
                            else
                            {
                                //If the origin of the XML string is not known or not handled, than an alert will be fired
                                Console.WriteLine("##################################################");
                                Console.WriteLine($"#  ALERT: an XML String comes from the outside   #");
                                Console.WriteLine($"#         and has NOT been handled!              #");
                                Console.WriteLine("##################################################");
                            }
                        }
                        else
                        {
                            //When the XML string is not valid, another check will be taken place
                            Console.WriteLine("Consumer: not valid");
                            //xsd validation error
                            schema = new XmlSchemaSet();
                            schema.Add("", "Errorxsd.xsd");
                            xml           = XDocument.Parse(message, LoadOptions.SetLineInfo);
                            xmlValidation = true;

                            //Validating XML with new XSD Scheme
                            xml.Validate(schema, (sender, e) =>
                            {
                                xmlValidation = false;
                            });

                            //If valid, a log will be send on the Queue
                            if (xmlValidation)
                            {
                                string error = "<error>" +
                                               "<header>" +
                                               "<code>2000</code>" +
                                               "<origin>AD</origin>" +
                                               "<timestamp>" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss%K") + "</timestamp>" +
                                               "</header>" +
                                               "<body>" +
                                               "<objectUUID></objectUUID>" +
                                               "<objectSourceId></objectSourceId>" +
                                               "<objectOrigin>AD</objectOrigin>" +
                                               "<description>Something went wrong when adding to the UUID master, DB error:</description>" +
                                               "</body>" +
                                               "</error>";
                                ProducerGUI.send(error, Severity.logging.ToString());
                            }
                            //If not, an error will be displayed (Same principal as the error catch from the ReadXMLTag Method inside the XMLParser.class)
                            XDocument xmlUser                = XDocument.Parse(message);
                            string    errorDescription       = "";
                            IEnumerable <XElement> xElements = xmlUser.Descendants("description");
                            foreach (var element in xElements)
                            {
                                errorDescription = element.Value;
                            }
                            Console.WriteLine(errorDescription);
                        }
                    };
                    //Declare consumer delegate to the channel so some code gets executed when a new message is recieved
                    channel.BasicConsume(queue: queueName,
                                         autoAck: true,
                                         consumer: consumer);

                    Console.WriteLine(" Press [enter] to exit.");
                    //Readline to suspend program to receieve messages, if any key is entered, the Consumer will Exit(0)
                    Console.ReadLine();
                }
        }
Ejemplo n.º 2
0
        /**
         *  Main Methode: Reads the operation and assigns the right CRUD operation on the incoming user
         *      @param1 => The method/operation of the CRUD to be executed
         *      @param2 => The incoming user object that is used for the CRUD
         *      @param3 => The CRUD instance with all the CRUD functionality inside
         */
        public static void OperationToCRUD(this string operation, IntraUser user, CRUD crudInstance)
        {
            //Makes an AD/C# user object for ease of use
            var adUser = user.IntraUserObjectToADObject();

            //Check for operation with switch case
            switch (operation.ToUpperInvariant())
            {
            //Creates a new user in the Active Directory DB
            case "CREATE":
                if (crudInstance.CreateUser(user.IntraUserObjectToADObject()))
                {
                    //Check if new user made it into the DB
                    if (crudInstance.IsUserInAD(adUser.CN))
                    {
                        //Get the newly generated GUID from the Attributes
                        user.MetaData.GUID = crudInstance.FindADUser(adUser.CN).ObjectGUID;
                        //Update the UUID with the newly created user
                        Uuid.Update(user);
                    }
                    else
                    {
                        //If user is not found, display an error
                        Console.WriteLine("##################################################");
                        Console.WriteLine($"#      Newly created user cannot be found        #");
                        Console.WriteLine("##################################################");
                    }
                }
                else
                {
                    //Show error if Create got interrupted
                    Console.WriteLine("##################################################");
                    Console.WriteLine($"# CREATING user from Active Directory has FAILED #");
                    Console.WriteLine("##################################################");

                    //Make a XML Error string to log error
                    string error = "<error>" +
                                   "<header>" +
                                   "<code>3003</code>" +
                                   "<origin>AD</origin>" +
                                   "<timestamp>" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss%K") + "</timestamp>" +
                                   "</header>" +
                                   "<body>" +
                                   "<objectUUID></objectUUID>" +
                                   "<objectSourceId></objectSourceId>" +
                                   "<objectOrigin>AD</objectOrigin>" +
                                   "<description>The user could not be added to the AD</description>" +
                                   "</body>" +
                                   "</error>";
                    //Send the error on the Logging Queue
                    ProducerGUI.send(error, Severity.logging.ToString());
                }
                break;

            //Deletes an existing user from the Active Directory DB
            case "DELETE":
                if (crudInstance.DeleteUser(adUser.CN))
                {
                    /**
                     *  Because the GUI only has the Container name of all the users
                     *  the DELETE method only comes wrapped around a READ method,
                     *  to first find the user and with that reference => delete the user
                     */
                    user.MetaData.Methode = CRUDMethode.DELETE;
                    //Update the UUID with the deleted user
                    Uuid.Update(user);
                }
                else
                {
                    //Show error if Delete got interrupted
                    Console.WriteLine("##################################################");
                    Console.WriteLine($"# DELETING user from Active Directory has FAILED #");
                    Console.WriteLine("##################################################");
                }
                break;

            //Updates an existing user from the Active Directory DB
            case "UPDATE":
                //Find the old user object based on the same GUID from both users
                var oldUser = crudInstance.FindADUser("objectGUID=" + ConvertGuidToOctetString(user.MetaData.GUID));
                if (crudInstance.UpdateUser(oldUser, user.IntraUserObjectToADObject()))
                {
                    //Update the UUID with the newly updated user
                    Uuid.Update(user);
                }
                else
                {
                    //Show error if Update got interrupted
                    Console.WriteLine("##################################################");
                    Console.WriteLine($"# UPDATING user from Active Directory has FAILED #");
                    Console.WriteLine("##################################################");
                }
                break;

            //Reads all users in Active Directory and wrap it into a List<ADUser>
            case "READ_ALL":
                //Get all users
                ListUsers.List = crudInstance.GetADUsers();
                //Converts List into a XML Array and send it on the Queue of the GUI
                ProducerGUI.send(ObjectToXML(ListUsers.List), Severity.GUI.ToString());     //Make new Producer
                break;

            default:
                Console.WriteLine("##################################################");
                Console.WriteLine($"#       INVALID Operation: {operation} ");
                Console.WriteLine("##################################################");
                break;
            }
        }