示例#1
0
        /// <summary>
        /// Deserializes poll packet from XML string into PollPacket object 
        /// </summary>
        /// <param name="xmlString">XML string, which holds serialized PollPacket object</param>
        /// <returns>Deserialized PollPacket object</returns>
        public static PollPacket DeserializePacket(string xmlString)
        {
            PollPacket pollPacket = new PollPacket();
            Survey.isSerialized = true;
            try
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(PollPacket));
                MemoryStream memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(xmlString));
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.ASCII);

                pollPacket = (PollPacket)xmlSerializer.Deserialize(memoryStream);

                if (pollPacket.survey != null)
                {
                    foreach (Poll poll in pollPacket.survey.Polls)
                    {
                        foreach (Choice choice in poll.Choices)
                        {
                            choice.parent = poll;
                        }
                    }
                }
            }
            catch (Exception)
            {
                Survey.isSerialized = false;
                return null;
            }

            Survey.isSerialized = false;
            return pollPacket;
        }
示例#2
0
文件: Program.cs 项目: itproto/ilsrep
        public static void AuthorizeUser()
        {
            Console.WriteLine("Welcome to polls editor program.");
            while (true)
            {
                // Read user name
                while (true)
                {
                    Console.Write("Please enter your name:");
                    userName = Console.ReadLine();
                    if (userName != String.Empty)
                    {
                        break;
                    }
                    else
                    {
                        //Console.Clear();
                        Console.WriteLine("! You didn't enter your name.");
                    }
                }

                PollPacket pollPacket = new PollPacket();
                pollPacket.user = new User();
                pollPacket.user.username = userName;
                pollPacket.user.action = User.LOGIN;
                pollPacket = ReceivePollPacket(pollPacket);

                if (pollPacket.user.action == User.NEW_USER)
                {
                    Console.WriteLine("{0}, please, set your password:"******"{0}, please, enter your password:"******"Invalid password!");
            }
        }
示例#3
0
        /// <summary>
        /// Method is executed when data is received
        /// </summary>
        /// <param name="iAsyncResult"></param>
        public void ProcessClient( IAsyncResult iAsyncResult )
        {
            int clientID = (int)iAsyncResult.AsyncState;
            StateObject client = workers[clientID];
            int countReceived = 0;

            try
            {
                countReceived = client.workSocket.EndReceive( iAsyncResult );
                if ( countReceived == 0 )
                {
                    EventLog.WriteEntry( String.Format( "Client {0} disconnected", client.ipAddress ), EventLogEntryType.Information );
                    client.workSocket.Close();
                    workers.RemoveAt( clientID );

                    return;
                }
            }
            catch ( SocketException e )
            {
                if ( e.ErrorCode == 10054 )
                {
                    EventLog.WriteEntry( String.Format( "Client {0} disconnected", client.ipAddress ), EventLogEntryType.Information );
                    workers.RemoveAt( clientID );
                }
                else
                {
                    EventLog.WriteEntry( String.Format( "Socket Exception on client {0}: {1}", client.ipAddress, e.Message ), EventLogEntryType.Error );
                }

                return;
            }

            string receivedData = Encoding.ASCII.GetString( client.buffer, 0, countReceived );
            PollPacket receivedPacket = PollSerializator.DeserializePacket( receivedData );
            if ( receivedPacket == null )
            {
                EventLog.WriteEntry( "Invalid data received", EventLogEntryType.Error );
                client.workSocket.BeginReceive( client.buffer, 0, StateObject.BUFFERSIZE, SocketFlags.None, new AsyncCallback( ProcessClient ), clientID );

                return;
            }

            // Packet to be sent back
            PollPacket sendPacket = new PollPacket();

            if (!client.isAuthorized)
            {
                switch (receivedPacket.user.action)
                {
                    case User.LOGIN:
                        sendPacket.user = PollDAL.AuthorizeUser(receivedPacket.user);
                        if (sendPacket.user.action == User.ACCEPTED)
                        {
                            client.isAuthorized = true;
                            EventLog.WriteEntry("User accepted: " + sendPacket.user.username, EventLogEntryType.Information);
                        }
                        break;
                    case User.NEW_USER:
                        sendPacket.user = PollDAL.RegisterUser(receivedPacket.user);
                        if (sendPacket.user.action == User.ACCEPTED)
                        {
                            EventLog.WriteEntry("New user created: " + sendPacket.user.username, EventLogEntryType.Information);
                        }
                        break;
                }
            }
            else
            {
                // Select option
                switch ( receivedPacket.request.type )
                {
                    case Request.GET_LIST:
                        sendPacket.surveyList = new SurveyList();
                        sendPacket.surveyList.items = PollDAL.GetSurveys();
                        EventLog.WriteEntry( String.Format( "Survey List sent to {0}", client.ipAddress ), EventLogEntryType.Information );
                        break;
                    case Request.GET_SURVEY:
                        sendPacket.survey = PollDAL.GetSurvey( Convert.ToInt32( receivedPacket.request.id ) );
                        EventLog.WriteEntry( String.Format( "Survey {0} sent to {1}", sendPacket.survey.Id, client.ipAddress ), EventLogEntryType.Information );
                        break;
                    case Request.EDIT_SURVEY:
                        PollDAL.EditSurvey(receivedPacket.survey);
                        EventLog.WriteEntry( String.Format( "Survey {0} changed by {1}", receivedPacket.survey.Id, client.ipAddress ), EventLogEntryType.Information );
                        break;
                    case Request.CREATE_SURVEY:
                        receivedPacket.survey.Id = PollDAL.CreateSurvey( receivedPacket.survey );
                        EventLog.WriteEntry( String.Format( "Survey {0} created by {1}", receivedPacket.survey.Id, client.ipAddress ), EventLogEntryType.Information );
                        break;
                    case Request.REMOVE_SURVEY:
                        PollDAL.RemoveSurvey( Convert.ToInt32( receivedPacket.request.id ) );
                        EventLog.WriteEntry( String.Format( "Survey {0} removed by {1}", receivedPacket.request.id, client.ipAddress ), EventLogEntryType.Information );
                        break;
                    case Request.SAVE_RESULT:
                        PollDAL.SaveSurveyResult( receivedPacket.resultsList );
                        EventLog.WriteEntry( String.Format( "Survey {0} results of user {1} sent by {2}", receivedPacket.resultsList.surveyId, receivedPacket.resultsList.userName, client.ipAddress ), EventLogEntryType.Information );
                        break;
                    case Request.GET_RESULTS:
                        sendPacket.resultsList = PollDAL.GetSurveyResults(Convert.ToInt32(receivedPacket.request.id));
                        EventLog.WriteEntry( String.Format( "Survey {0} results sent to {1}", receivedPacket.request.id, client.ipAddress ), EventLogEntryType.Information );
                        break;
                    default:
                        EventLog.WriteEntry( String.Format( "Invalid option sent by {0}", client.ipAddress ), EventLogEntryType.Error );
                        break;
                }
            }

            string sendString = PollSerializator.SerializePacket( sendPacket );
            byte[] sendData = Encoding.ASCII.GetBytes( sendString );
            try
            {
                client.workSocket.BeginSend( sendData, 0, sendData.Length, SocketFlags.None, new AsyncCallback( SendCallback ), clientID );
            }
            catch ( SocketException e )
            {
                if ( e.ErrorCode == 10054 )
                {
                    EventLog.WriteEntry( String.Format( "Client {0} disconnected", client.ipAddress ), EventLogEntryType.Information );
                    workers.RemoveAt( clientID );
                }
                else
                {
                    EventLog.WriteEntry( String.Format( "Socket Exception on client {0}: {1}", client.ipAddress, e.Message ), EventLogEntryType.Error );
                }

                return;
            }
        }
示例#4
0
文件: Program.cs 项目: itproto/ilsrep
        /// <summary>
        /// Send results of survey to server
        /// </summary>
        public static void SaveSurveyResults()
        {
            PollPacket sendPacket = new PollPacket();
            sendPacket.request = new Request();
            sendPacket.request.type = Request.SAVE_RESULT;
            sendPacket.resultsList = new SurveyResults();
            sendPacket.resultsList.userName = userName;
            sendPacket.resultsList.surveyId = survey.Id;

            foreach (Choice userChoice in userChoices)
            {
                PollResult curSurveyResult = new PollResult();
                curSurveyResult.questionId = userChoice.parent.Id;
                if (userChoice.Id == 0)
                {
                    curSurveyResult.answerId = 0;
                    curSurveyResult.customChoice = userChoice.choice;
                }
                else
                {
                    curSurveyResult.answerId = userChoice.Id;
                }
                sendPacket.resultsList.results.Add(curSurveyResult);
            }
            string sendString = PollSerializator.SerializePacket(sendPacket);
            client.Send(sendString);
            Console.WriteLine("-> Result of survey successfully sent to server");
        }
示例#5
0
文件: Program.cs 项目: itproto/ilsrep
        /// <summary>
        /// Function sends request, receive PollPacket and check if receivedPacket == null. If true, user can retry to receive Packet, else function returns receivedPacket
        /// </summary>
        /// <param name="sendPacket">PollPacket with request to send</param>
        /// <returns>PollPacket receivedPacket</returns>
        public static PollPacket ReceivePollPacket(PollPacket sendPacket)
        {
            while (true)
            {
                try
                {
                    string sendString = PollSerializator.SerializePacket(sendPacket);
                    client.Send(sendString);
                }
                catch (Exception exception)
                {
                    Console.WriteLine("! " + exception.Message);
                }

                string receivedString = client.Receive();
                PollPacket receivedPacket = new PollPacket();
                receivedPacket = PollSerializator.DeserializePacket(receivedString);

                // Check if received data is correct
                if (receivedPacket == null)
                {
                    Console.WriteLine("! Wrong data received");
                    Console.WriteLine("Would you like to retry?[y/n]:");
                    while (true)
                    {
                        string userInput;
                        userInput = Console.ReadLine();
                        if (userInput == "y")
                        {
                            DisconnectFromServer();
                            ConnectToServer();
                            break;
                        }
                        else if (userInput == "n")
                        {
                            Environment.Exit(-1);
                        }
                        else
                        {
                            Console.WriteLine("! Invalid choice");
                        }
                    }
                }
                else
                {
                    return receivedPacket;
                }
            }
        }
示例#6
0
文件: Program.cs 项目: itproto/ilsrep
        /// <summary>
        /// Server sends list of available surveys. User picks one and client gets that survey from server.
        /// </summary>
        public static void GetSurvey()
        {
            PollPacket sendPacket = new PollPacket();
            sendPacket.request = new Request();
            sendPacket.request.type = Request.GET_LIST;

            PollPacket receivedPacket = new PollPacket();
            receivedPacket = ReceivePollPacket(sendPacket);

            // Check if list is not empty
            if (receivedPacket.surveyList.items.Count == 0)
            {
                Console.WriteLine("Sorry, but data base is empty, no surveys...");
                client.Disconnect();
                Console.WriteLine("- Disconnected from server");
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey(true);
                Environment.Exit(-1);
            }

            // Output list of surveys
            Console.WriteLine("List of surveys:");
            int index = 0;
            foreach (Item curItem in receivedPacket.surveyList.items)
            {
                index++;
                Console.WriteLine(index + ". " + curItem.name);
            }

            while (true)
            {
                Console.WriteLine("Please select survey[1-{0}]:", receivedPacket.surveyList.items.Count);
                // Let user input survey id
                string userAnswer = Console.ReadLine();

                try
                {
                    index = Convert.ToInt32(userAnswer);

                    if (index > 0 && index <= receivedPacket.surveyList.items.Count)
                    {
                        string surveyID = receivedPacket.surveyList.items[index - 1].id.ToString();
                        sendPacket.request.type = Request.GET_SURVEY;
                        sendPacket.request.id = surveyID;
                        break;
                    }
                    else
                    {
                        throw new Exception("Invalid survey id! Please, input correct id");
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine("! " + exception.Message);
                }
            }

            // Receive poll
            receivedPacket = ReceivePollPacket(sendPacket);
            survey = receivedPacket.survey;
            Console.WriteLine("<- Survey received");
        }
示例#7
0
文件: Program.cs 项目: itproto/ilsrep
        public static void AuthorizeUser()
        {
            Console.WriteLine("Welcome to polls client program.");
            while (true)
            {
                // Read user name
                while (true)
                {
                    Console.Write("Please enter your name:");
                    userName = Console.ReadLine();
                    if (userName != String.Empty)
                    {
                        break;
                    }
                    else
                    {
                        //Console.Clear();
                        Console.WriteLine("! You didn't enter your name.");
                    }
                }

                PollPacket pollPacket = new PollPacket();
                pollPacket.user = new User();
                pollPacket.user.username = userName;
                pollPacket.user.action = User.LOGIN;
                pollPacket = ReceivePollPacket(pollPacket);

                if (pollPacket.user.action == User.NEW_USER)
                {
                    Console.WriteLine("{0}, please, set your password:"******"{0}, please, enter your password:"******"Invalid password!");
            }

            Console.Clear();
            Console.WriteLine("Glad to meet you, " + userName);
            Console.WriteLine(userName + ", let's start the survey?[y/n]");

            // Ask user if he want to start the survey
            while (true)
            {
                string userInput = Console.ReadLine();
                if (userInput == CONSOLE_YES) break;
                if (userInput == CONSOLE_NO) Environment.Exit(0);
                Console.WriteLine("! Wrong choice, please, choose [y/n]:");
            }
        }
示例#8
0
        /// <summary>
        /// Serializes poll packet from PollPacket object into XML string
        /// </summary>
        /// <param name="pollPacket">PollPacket object</param>
        /// <returns>XML string, which holds serialized PollPacket object</returns>
        public static String SerializePacket(PollPacket pollPacket)
        {
            String XmlizedString = null;
            try
            {
                MemoryStream memoryStream = new MemoryStream();
                XmlSerializer xs = new XmlSerializer(typeof(PollPacket));
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.ASCII);

                xs.Serialize(xmlTextWriter, pollPacket);
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                XmlizedString = Encoding.ASCII.GetString(memoryStream.ToArray());
            }
            catch (Exception)
            {
                return null;
            }
            return XmlizedString;
        }
示例#9
0
文件: Program.cs 项目: itproto/ilsrep
        /// <summary>
        /// Run conversation with user
        /// </summary>
        public static void RunUserDialog()
        {
            // Get list of surveys from server and write they in console
            PollPacket sendPacket = new PollPacket();
            sendPacket.request = new Request();
            sendPacket.request.type = Request.GET_LIST;

            PollPacket receivedPacket = new PollPacket();
            receivedPacket = ReceivePollPacket(sendPacket);

            // Check if list is not empty
            if (receivedPacket.surveyList.items.Count == 0)
            {
                Console.WriteLine("Sorry, but data base is empty, no surveys...");
                if (InputHelper.AskQuestion(String.Format("Would you create new survey[{0}/{1}]?", STRING_YES, STRING_NO), new string[] { STRING_YES, STRING_NO }) == STRING_YES)
                {
                    EditSurvey(0);
                }
                else
                {
                    Console.WriteLine("Press any key to exit...");
                    Console.ReadKey(true);
                    Environment.Exit(0);
                }
                return;
            }

            Console.WriteLine( "1. Create new survey" );
            Console.WriteLine( "2. Edit survey" );
            Console.WriteLine( "3. Remove survey" );
            int action = InputHelper.AskQuestion( "Choose action [1-3]:", 1, 3 );

            int surveyIndex;
            switch (action)
            {
                case 1:
                    EditSurvey( 0 );
                    break;
                case 2:
                    surveyIndex = receivedPacket.surveyList.GetSurveyId();
                    EditSurvey( Convert.ToInt32( receivedPacket.surveyList[surveyIndex-1].id ) );
                    break;
                case 3:
                    surveyIndex = receivedPacket.surveyList.GetSurveyId();
                    RemoveSurvey( receivedPacket.surveyList[surveyIndex-1] );
                    break;
                default:
                    Console.WriteLine("Invalid action!");
                    break;
            }
        }
示例#10
0
文件: Program.cs 项目: itproto/ilsrep
        /// <summary>
        /// Remove survey
        /// </summary>
        public static void RemoveSurvey( Item item )
        {
            // Ask if user is sure
            if ( InputHelper.AskQuestion( "Do you really want to remove survey \"" + item.name + "\" [y/n]?", new string[] { STRING_YES, STRING_NO } ) == "n" )
            {
                return;
            }

            PollPacket sendPacket = new PollPacket();
            sendPacket.request = new Request();
            sendPacket.request.type = Request.REMOVE_SURVEY;
            sendPacket.request.id = item.id.ToString();
            string sendString = PollSerializator.SerializePacket(sendPacket);
            client.Send(sendString);
        }
示例#11
0
文件: Program.cs 项目: itproto/ilsrep
        /// <summary>
        /// Main method
        /// </summary>
        public static void Main()
        {
            cultureInfo.NumberFormat.NumberDecimalSeparator = ".";

            ConnectToServer();
            AuthorizeUser();
            while (true)
            {
                RunUserDialog();
                DisconnectFromServer();
                if ( InputHelper.AskQuestion( "Do you want to execute another action[y/n]?", new string[] { STRING_YES, STRING_NO } ) == STRING_NO )
                    break;
                ConnectToServer();
                PollPacket pollPacket = new PollPacket();
                pollPacket.user = new User();
                pollPacket.user.username = userName;
                pollPacket.user.password = userPassword;
                pollPacket.user.action = User.LOGIN;
                pollPacket = ReceivePollPacket(pollPacket);
                if (pollPacket.user.action == User.DENIED)
                {
                    Console.WriteLine("Sorry, access denied");
                    break;
                }
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey(true);
        }
示例#12
0
文件: Program.cs 项目: itproto/ilsrep
        /// <summary>
        /// Adds or edits survey and saves it to server
        /// </summary>
        /// <param name="surveyID">id of session to edit</param>
        public static void EditSurvey( int surveyID )
        {
            Survey survey;

            if ( surveyID == 0 )
            {
                survey = new Survey();
            }
            else
            {
                PollPacket pollPacket = new PollPacket();
                pollPacket.request = new Request();
                pollPacket.request.type = Request.GET_SURVEY;
                pollPacket.request.id = surveyID.ToString();
                pollPacket = ReceivePollPacket( pollPacket );
                survey = pollPacket.survey;
            }

            survey.Name = InputHelper.AskQuestion("Enter survey name:", survey.Name, null);
            survey.TestMode = InputHelper.ToBoolean(InputHelper.AskQuestion("Test mode[y/n]?", InputHelper.ToString(survey.TestMode), new string[] { STRING_YES, STRING_NO }));

            if (survey.TestMode == true)
            {
                while (true)
                {
                    try
                    {
                        survey.MinScore = Convert.ToDouble(InputHelper.AskQuestion("Min score to pass test:", Convert.ToString(survey.MinScore, cultureInfo), null), cultureInfo);
                        if (survey.MinScore > 1 || survey.MinScore < 0)
                            throw new Exception("min score must be between 0 and 1");
                        break;
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine("Error: {0}", exception.Message);
                        //Console.WriteLine("Please, input correct min score (example: 0.5)");
                    }
                }
            }

            while(true)
            {
                Console.WriteLine("Survey contains {0} polls.", survey.Polls.Count);

                if (survey.Polls.Count > 0)
                {
                    Console.WriteLine( "Actions:" );
                    Console.WriteLine( "1. Add new poll" );
                    Console.WriteLine( "2. Edit poll" );
                    Console.WriteLine( "3. Remove poll" );
                    Console.WriteLine( "4. End" );
                    int userChoice = InputHelper.AskQuestion("Select action [1-4]:", 1, 4);

                    if ( userChoice == 4 )
                        break;

                    int index;
                    switch (userChoice)
                    {
                        case 1:
                            EditPoll( ref survey, -1 );
                        break;
                        case 2:
                            index = 0;
                            Console.WriteLine("List of polls:");
                            foreach (Poll poll in survey.Polls)
                            {
                                index++;
                                Console.WriteLine("{0}. {1}", index, poll.Name);
                            }

                            userChoice = InputHelper.AskQuestion(String.Format("Choose which one to edit [1-{0}]:", index), 1, index);

                            EditPoll( ref survey, userChoice-1 );
                        break;
                        case 3:
                            index = 0;
                            Console.WriteLine("List of polls:");
                            foreach (Poll poll in survey.Polls)
                            {
                                index++;
                                Console.WriteLine("{0}. {1}", index, poll.Name);
                            }

                            survey.Polls.RemoveAt(InputHelper.AskQuestion(String.Format("Choose which one to delete [1-{0}]:", index), 1, index)-1);
                        break;
                    }
                }
                else
                {
                    EditPoll( ref survey, -1 );
                }
            }

            // Save survey to server
            if (InputHelper.AskQuestion("Do you want to save this survey to server [y/n]?", new string[] { STRING_YES, STRING_NO }) == STRING_YES)
            {
                PollPacket sendPacket = new PollPacket();
                sendPacket.request = new Request();
                if (surveyID == 0)
                {
                    sendPacket.request.type = Request.CREATE_SURVEY;
                }
                else
                {
                    sendPacket.request.type = Request.EDIT_SURVEY;
                }
                sendPacket.request.id = surveyID.ToString();
                sendPacket.survey = survey;
                string sendString = PollSerializator.SerializePacket(sendPacket);
                client.Send(sendString);
            }
        }
示例#13
0
文件: Program.cs 项目: itproto/ilsrep
        /// <summary>
        /// Function sends request, receive PollPacket and check if receivedPacket == null. If true, user can retry to receive Packet, else function returns receivedPacket
        /// </summary>
        /// <param name="sendPacket">PollPacket with request to send</param>
        /// <returns>PollPacket receivedPacket</returns>
        public static PollPacket ReceivePollPacket( PollPacket sendPacket )
        {
            try
            {
                string sendString = PollSerializator.SerializePacket( sendPacket );
                PollClientGUI.client.Send( sendString );
            }
            catch ( Exception )
            {
                return null;
            }

            string receivedString = PollClientGUI.client.Receive();
            PollPacket receivedPacket = new PollPacket();
            receivedPacket = PollSerializator.DeserializePacket( receivedString );

            // Check if received data is correct
            if ( receivedPacket == null )
            {
                return null;
            }
            return receivedPacket;
        }