Пример #1
0
        public ActionResult Create(Library.Message message)
        {
            if (!ModelState.IsValid)
            {
                return(View("Create"));
            }

            messageWeb.AddMessage(message);
            return(RedirectToAction("Index"));
        }
Пример #2
0
        private void btn_MSend_Click(object sender, EventArgs e)
        {
            byte[]          bytes   = new byte[1024 * 4];
            Library.Message message = new Library.Message();
            message.type = (int)CM_All.메시지;
            message.MMS  = myNick + " : " + this.txt_Chat.Text;
            bytes        = CM_Library.Serialize(message);
            Stream stream = new NetworkStream(client.Client);

            stream.Write(bytes, 0, bytes.Length);
            this.txt_Chat.Text = "";
            stream.Flush();
            Set_byte(bytes);
        }//메시지를 보내는거 구현
Пример #3
0
        private void btnEnviar_Click(object sender, EventArgs e)
        {
            try
            {

                var checkedButton = mainPanel.Controls.OfType<RadioButton>()
                                      .FirstOrDefault(r => r.Checked);
                if (txtMensaje.Text == "")
                {
                    MessageBox.Show("No se puede enviar un mensaje vacío", "Message sending application", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    Library.Message newM = new Library.Message();
                    newM.Content = txtMensaje.Text;
                    newM.Importance = (Level)Enum.Parse(typeof(Level), checkedButton.Text);
                    netCM.SendMessage(newM);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #4
0
 /// <summary>
 /// Agrega datos a la BD a través de un procedimiento almacenado
 /// </summary>
 /// <param name="msg"></param>
 /// <returns>True si la inserción fue exitosa</returns>
 public bool AddNewMessage(Message msg)
 {
     try
     {
         DBConnection.Open();
         SQLcmdSP = new SqlCommand("sp_StoreMessage", DBConnection);
         SQLcmdSP.CommandType = CommandType.StoredProcedure;
         SQLcmdSP.Parameters.Add(new SqlParameter("@content", SqlDbType.NVarChar, 200));
         SQLcmdSP.Parameters.Add(new SqlParameter("@type", SqlDbType.NVarChar, 50));
         SQLcmdSP.Parameters[0].Value = msg.Content;
         SQLcmdSP.Parameters[1].Value = msg.Importance.ToString();
         int i = SQLcmdSP.ExecuteNonQuery();
         return true;
     }
     catch
     {
         return false;
     }
     finally
     {
         SQLcmdSP.Dispose();
         DBConnection.Close();
     }
 }
Пример #5
0
 public MessageEventArgs(Message pe, DateTime dt)
 {
     this._m = pe;
     this._dt = dt;
 }
Пример #6
0
        //-------------스트림(타입에 따른)을 받아오는 쓰레드 핸들러 Request 구현 해야한다네 (메시지, 좌표, 턴, 정답 등)------------------------------//
        private void Request()
        {
            SendMyTurn();
            while (true)
            {
                byte[]     bytes  = new byte[1024 * 4];
                Stream     stream = new NetworkStream(client.Client);
                int        len    = stream.Read(bytes, 0, bytes.Length);
                CM_Library Two    = (CM_Library)CM_Library.Deserialize(bytes);
                stream.Flush();
                switch (Two.type)
                {
                case (int)CM_All.메시지:
                {
                    Library.Message message = (Library.Message)CM_Library.Deserialize(bytes);
                    //메시지 출력 구현해야함
                    this.txt_Mul.Invoke(new MethodInvoker(delegate() {
                            txt_Mul.Text += message.MMS + "\r\n";
                        }));
                    Set_byte(bytes);
                    break;
                }

                case (int)CM_All.좌표:
                {
                    GPoint gPoint = (GPoint)CM_Library.Deserialize(bytes);
                    //좌표찍는거 구현해야함
                    gh = pictureBox1.CreateGraphics();
                    //sel_Color(pen, gPoint.gColor);
                    //pen.Width = gPoint.gWidth;
                    gh.DrawLine(pen, point.X, point.Y, gPoint.X, gPoint.Y);
                    point.X = gPoint.X; point.Y = gPoint.Y;
                    Set_byte(bytes);
                    break;
                }

                case (int)CM_All.문제:
                {
                    Problem problem = (Problem)CM_Library.Deserialize(bytes);
                    //문제받기
                    this.Invoke(new MethodInvoker(delegate()
                        {
                            txt_problem.Text = problem.problem;
                        }));
                    if (this.CM_My.InvokeRequired)
                    {
                        this.CM_My.Invoke(new MethodInvoker(delegate()
                            {
                                CM_My.Text      = "MY TURN";
                                CM_My.BackColor = Color.Lime;
                            }));
                    }
                    else
                    {
                        CM_My.Text      = "MY TURN";
                        CM_My.BackColor = Color.Lime;
                    }
                    Set_byte(bytes);
                    break;
                }

                case (int)CM_All.점수:
                {
                    Upoint upoint = (Upoint)CM_Library.Deserialize(bytes);
                    User_Point[upoint.Nic] = upoint.point;
                    Set_byte(bytes);
                    if (j == 4)
                    {
                        Ranking();
                    }
                    break;
                }

                case (int)CM_All.처음좌표:
                {
                    GPoint gPoint = (GPoint)CM_Library.Deserialize(bytes);
                    //좌표찍는거 구현해야함
                    gh = pictureBox1.CreateGraphics();
                    sel_Color(pen, gPoint.gColor);
                    pen.Width = gPoint.gWidth;
                    point.X   = gPoint.X; point.Y = gPoint.Y;
                    Set_byte(bytes);
                    break;
                }

                case (int)CM_All.그림초기화:
                {
                    pictureBox1.Image = null;
                    Set_byte(bytes);
                    break;
                }
                }
            }
        }
Пример #7
0
        public void Request(int Type, byte[] bytes, TcpClient client) //Type에 따라 달라지는 직렬화
        {
            switch (Type)
            {
            case (int)CM_All.메시지:
            {
                Library.Message message = new Library.Message();
                message = (Library.Message)CM_Library.Deserialize(bytes);
                DisplayText(message.MMS);
                //Set_byte(bytes);
                //bytes = CM_Library.Serialize(message);
                //모든 클라이언트에 보내주는 메소드 만들어야함
                for (int i = 0; i < count; i++)
                {
                    Stream stream4 = new NetworkStream(tcpClients[i].Client);
                    stream4.Write(bytes, 0, bytes.Length);
                    stream4.Flush();
                }
                break;
            }

            case (int)CM_All.레디:
            {
                Ready_Off ready_Off = new Ready_Off();
                ready_Off = (Ready_Off)CM_Library.Deserialize(bytes);
                on.On[Number_D[client]] = true;
                on.type = (int)CM_All.자기번호;
                Set_byte(bytes);
                bytes = CM_Library.Serialize(on);
                for (int i = 0; i < count; i++)
                {
                    Stream stream3 = new NetworkStream(tcpClients[i].Client);
                    stream3.Write(bytes, 0, bytes.Length);
                    stream3.Flush();
                }
                break;
            }

            case (int)CM_All.닉네임:
            {
                Login login = new Login();
                login = (Login)CM_Library.Deserialize(bytes);

                //login_D.Add(dictionary, login);
                User_point.Add(login.id, 0);
                Nick.Add(login.id);
                Set_byte(bytes);

                Ready ready = new Ready();
                ready.type = (int)CM_All.클라이언트라벨;
                for (int i = 0; i < count; i++)
                {
                    ready.nickNameList[i] = Nick[i].ToString();
                }
                bytes = CM_Library.Serialize(ready);
                for (int i = 0; i < count; i++)
                {
                    Stream stream2 = new NetworkStream(tcpClients[i].Client);
                    stream2.Write(bytes, 0, bytes.Length);
                    stream2.Flush();
                }
                break;
            }

            case (int)CM_All.좌표:
            {
                //GPoint gPoint = new GPoint();
                //gPoint = (GPoint)CM_Library.Deserialize(bytes);
                for (int i = 0; i < count; i++)
                {
                    if (i != ti_time)
                    {
                        Stream stream1 = new NetworkStream(tcpClients[i].Client);
                        stream1.Write(bytes, 0, bytes.Length);
                        stream1.Flush();
                    }
                }
                break;
            }

            case (int)CM_All.턴:
            {
                ++ti_time;
                if (ti_time == 0)
                {
                    Library.Message mms = new Library.Message();
                    mms.type = (int)CM_All.메시지;
                    mms.MMS  = "게임시작";
                    byte[] buffer = new byte[1024 * 4];
                    buffer = CM_Library.Serialize(mms);
                    foreach (var cl in tcpClients)
                    {
                        Stream stream_2 = new NetworkStream(cl.Client);
                        stream_2.Write(buffer, 0, buffer.Length);
                        stream_2.Flush();
                    }
                }
                Set_byte(bytes);
                Problem problem = new Problem();
                problem.type    = (int)CM_All.문제;
                problem.problem = Allproblem[ti_time].ToString();
                bytes           = CM_Library.Serialize(problem);
                Stream stream0 = new NetworkStream(tcpClients[ti_time].Client);
                stream0.Write(bytes, 0, bytes.Length);
                stream0.Flush();
                break;
            }

            case (int)CM_All.정답:
            {
                /*클라이언트의 답과 제시한 문제의 답과 같을 경우 점수를 주고 마지막 폼4번에서 점수를 출력해준다. <- 만들어야한다*/
                Answer answer = new Answer();
                answer = (Answer)CM_Library.Deserialize(bytes);
                if (Allproblem[ti_time] == answer.txtAnswer)
                {
                    User_point[answer.Nicname] += 10;
                    DisplayText(answer.Nicname + " : " + User_point[answer.Nicname].ToString());
                }
                //모두에게 각자의 점수를 보내준다
                Upoint upoint = new Upoint();
                upoint.Nic   = answer.Nicname;
                upoint.point = User_point[answer.Nicname];
                upoint.type  = (int)CM_All.점수;
                Set_byte(bytes);
                bytes = CM_Library.Serialize(upoint);
                for (int i = 0; i < count; i++)
                {
                    Stream stream_1 = new NetworkStream(tcpClients[i].Client);
                    stream_1.Write(bytes, 0, bytes.Length);
                    stream_1.Flush();
                }
                break;
            }

            case (int)CM_All.처음좌표:
            {
                for (int i = 0; i < count; i++)
                {
                    if (i != ti_time)
                    {
                        Stream stream1 = new NetworkStream(tcpClients[i].Client);
                        stream1.Write(bytes, 0, bytes.Length);
                        stream1.Flush();
                    }
                }
                break;
            }

            case (int)CM_All.그림초기화:
            {
                for (int i = 0; i < count; i++)
                {
                    if (i != ti_time)
                    {
                        Stream stream_2 = new NetworkStream(tcpClients[i].Client);
                        stream_2.Write(bytes, 0, bytes.Length);
                        stream_2.Flush();
                    }
                }
                break;
            }
            }
        }
        private void _okButton_Click(object sender, RoutedEventArgs e)
        {
            var digitalSignature = _signatureComboBox.SelectedItem as DigitalSignature;

            int limit = 0;
            if (!Inspect.ContainTrustSignature(digitalSignature.ToString())) limit = -1;

            var comment = _commentTextBox.Text.Substring(0, Math.Min(_commentTextBox.Text.Length, Message.MaxCommentLength));
            var message = new Message(comment);

            _amoebaManager.MulticastUpload(_tag, message, limit, Settings.Instance.Global_MiningTime, digitalSignature);

            this.Close();
        }
Пример #9
0
        /// <summary>
        /// Envía un mensaje al servidor para que se almacene en la BD
        /// </summary>
        /// <param name="clientMsg">Mensaje a enviar al servidor</param>
        public void SendMessage(Message clientMsg)
        {
            try
            {
                if (_isConnected)
                {
                    netDataWriter.Write((Byte)(ControlMessage.CM_Message));
                    netDataWriter.Write(ObjSerializer.ObjectToByteArray(clientMsg).Length);
                    netDataWriter.Write(ObjSerializer.ObjectToByteArray(clientMsg));
                    netDataWriter.Flush();

                    ControlMessage srvAns = (ControlMessage)Enum.Parse(typeof(ControlMessage), netDataReader.ReadByte().ToString());

                    if (srvAns == ControlMessage.CM_OK)
                    {
                        MessageEventArgs mEa = new MessageEventArgs(clientMsg, DateTime.Now);
                        OnMessageSent(mEa); //Lanzamos el evento de envío exitoso
                    }
                    if (srvAns == ControlMessage.CM_Error)
                    {
                        OnServerError(); //Lanzamos el evento de error en el servidor
                    }
                }
            }
            catch
            {
                Console.WriteLine("Error en envío de mensajes");
            }
        }
Пример #10
0
        // Receive all incoming packets.
        private void InteractWithClient(ref TcpClient commChannel, ref BinaryReader netDataReader, ref BinaryWriter netDataWriter)
        {
            try
            {
                while (commChannel.Client.Connected)  // While we are connected.
                {
                    ControlMessage ctrlMsg = (ControlMessage)Enum.Parse(typeof(ControlMessage), netDataReader.ReadByte().ToString());
                    /*La instrucción anterior parsea el contenido de un mensaje de control que el cliente envía
                     * previo a colocar cualquier mensaje en el medio de red.
                     * La interacción es básicamente siempre así:
                     *      1. El cliente envía un mensaje de control.
                     *      2. Si el mensaje de control es de tipo CM_Message, el cliente envía:
                     *          2.1 El tamaño del mensaje.
                     *          2.2 Los datos del mensaje serializados.
                     *      3. El servidor parsea el mensaje de control y el mensaje.
                     *      4. El servidor envía una confirmación al cliente indicando que se recibió el mensaje correctamente.
                     *      5. El servidor genera un evento que contiene el mensaje y que puede ser utilizado por la GUI para presentarlo al usuario.
                     */

                    switch (ctrlMsg)
                    {
                        case ControlMessage.CM_Message:
                            /*
                             * El cliente va a enviar un mensaje. Debemos deserializar el contenido para luego pasarlo a la GUI.
                             */
                            Message newMsg = new Message();
                            // Leemos el tamaño del mensaje
                            int sizeOfMsg = netDataReader.ReadInt32();
                            newMsg = (Message)ObjSerializer.ByteArrayToObject(netDataReader.ReadBytes(sizeOfMsg));
                            lock (db)
                            {
                                if (db.AddNewMessage(newMsg))
                                {
                                    netDataWriter.Write((Byte)ControlMessage.CM_OK);
                                    netDataWriter.Flush(); //Mensaje almacenado en la BD con éxito
                                    MessageEventArgs infoMsg = new MessageEventArgs(newMsg, DateTime.Now);
                                    OnMessageReceived(infoMsg); //Se dispara el evento y agregamos la información del mensaje recibido
                                    // Esto para que la GUI pueda tener acceso al mensaje.
                                }
                                else
                                {
                                    netDataWriter.Write((Byte)ControlMessage.CM_Error);
                                    netDataWriter.Flush(); //Problemas almacenando mensaje
                                }
                            }
                            break;
                        case ControlMessage.CM_GetMessages:
                            Level msgLevel = (Level)Enum.Parse(typeof(Level), netDataReader.ReadByte().ToString());
                            Dictionary<int, Message> msgType = db.GetAllMessagesByType(msgLevel);

                            if (msgType.ContainsKey(-1))
                            {
                                netDataWriter.Write((Byte)ControlMessage.CM_NoMessages);
                                netDataWriter.Flush(); //No hay mensajes
                                evtW.writeInfo("No hay mensajes en la BD");
                            }
                            else
                            {
                                if (msgType.Count > 0)
                                {
                                    netDataWriter.Write((Byte)ControlMessage.CM_OK);
                                    netDataWriter.Flush(); //Hay mensajes
                                    netDataWriter.Write(ObjSerializer.ObjectToByteArray(msgType).Length);
                                    netDataWriter.Write(ObjSerializer.ObjectToByteArray(msgType));
                                    netDataWriter.Flush();
                                    evtW.writeInfo("Hay mensajes en la BD y se enviaron al cliente");
                                }
                                else
                                {
                                    netDataWriter.Write((Byte)ControlMessage.CM_Error);
                                    netDataWriter.Flush(); //Mensaje de error al cliente
                                    evtW.writeError("Hay errores en la BD");
                                }
                            }
                            /*
                             * Si existiesen más interacciones entre el cliente y el servidor, se deberían agregar más
                             * cases a este switch según mensajes de control existan y que se envíen desde el cliente.
                             */
                            break;
                        default:
                            break;
                    }
                }
            }
            catch
            {
                netDataWriter.Write((Byte)ControlMessage.CM_Error);
                netDataWriter.Flush();
            }
        }
Пример #11
0
        /// <summary>
        /// Obtains the list of registered providers of the system
        /// </summary>
        /// <returns>A dictionary with identifiers and characteristics of each provider</returns>
        public Dictionary<int, Message> GetAllMessagesByType(Level L)
        {
            SqlDataReader messageReader;
            try
            {
                SQLcmdSP = new SqlCommand();
                SQLcmdSP.CommandText = "sp_ExtractMessages";
                SQLcmdSP.CommandType = CommandType.StoredProcedure;
                SQLcmdSP.Parameters.Add(new SqlParameter("@type", SqlDbType.NVarChar, 50));
                SQLcmdSP.Parameters[0].Value = L.ToString();
                SQLcmdSP.Connection = DBConnection;
                DBConnection.Open();

                messageReader = SQLcmdSP.ExecuteReader();
                Dictionary<int, Message> ResultMessages = new Dictionary<int,Message>();
                if (messageReader.HasRows)
                {
                    while (messageReader.Read())
                    {
                        Message msgToRead = new Message();
                        msgToRead.Content = messageReader.GetString(1);
                        msgToRead.Importance = (Level)Enum.Parse(typeof(Level), messageReader.GetString(2));
                        ResultMessages.Add(messageReader.GetInt32(0), msgToRead);
                    }
                }
                else
                {
                    ResultMessages = new Dictionary<int,Message>();//No hay mensajes
                    ResultMessages.Add(-1, new Message());
                    return ResultMessages;
                }
                messageReader.Close();
                return ResultMessages; //Diccionario con usuarios registrados
            }
            catch
            {
                //evtLWDB.writeError("Error when getting Provider list" + Environment.NewLine + exc.Message);
                return new Dictionary<int,Message>();
            }
            finally
            {
                SQLcmdSP.Dispose();
                DBConnection.Close();
            }
        }