Ejemplo n.º 1
0
        /// <summary>
        /// Envia un mensaje al servidor para autenticar el inicio de seción.
        /// </summary>
        /// <param name="mobile">Identificador del móvil.</param>
        /// <param name="message">Mensaje a transmitir.</param>
        /// <param name="clientPassword">Clave del cliente móvil.</param>
        private void SendData(MessagePurpose message, byte[] clientPassword, string mobile)
        {
            byte[] messageBytes = new byte[1 + clientPassword.Length + Encoding.ASCII.GetByteCount(mobile)];

            messageBytes[0] = (byte)message;
            Array.Copy(clientPassword, 0, messageBytes, 1, clientPassword.Length);
            Array.Copy(Encoding.ASCII.GetBytes(mobile), 0, messageBytes, clientPassword.Length + 1, Encoding.ASCII.GetByteCount(mobile));
            Send(messageBytes);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Este método es invocado por métodos que envían cualquier tipo de mensaje al dispositivo
        /// </summary>
        /// <param name="clientEndPoint"></param>
        /// <param name="Purpose"></param>
        /// <param name="StringToSend"></param>
        private void SendVariableStringMessage(EndPoint clientEndPoint, MessagePurpose Purpose, string StringToSend)
        {
            byte[] stringPieceBytes = Encoding.ASCII.GetBytes(StringToSend);
            byte[] messageBytes     = new byte[stringPieceBytes.Length + 1];

            // Ensamblar el mensaje
            messageBytes[0] = (byte)Purpose;
            System.Array.Copy(stringPieceBytes, 0, messageBytes, 1, stringPieceBytes.Length);

            // Enviar el mensaje
            serverSocket.SendTo(messageBytes, messageBytes.Length, SocketFlags.None, clientEndPoint);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Envia un mensaje al server para renovar el tiempo
 /// </summary>
 /// <param name="mobile">Identificador del móvil.</param>
 /// <param name="message">Mensaje a transmitir.</param>
 private void SendData(MessagePurpose message, string mobile)
 {
     Send(Convert.ToChar((byte)message) + mobile);
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Metodo que recibe los datos desde el servidor
        /// </summary>
        private void ListenForServerMessages()
        {
            // IPEndPoint nos permite leer datagramas de cualquier origen.
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse(ipServer), portServer);

            // IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
            Byte[] receiveBytes;

            // repetir mientras la aplicacion esta corriendo
            while (true)
            {
                try
                {
                    // bloquear mientras esperamos respuesta desde el host remoto
                    receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
                    MessagePurpose purpose = (MessagePurpose)receiveBytes[0];

                    // decidir si el mensaje es para pedir más tiempo o para autenticar
                    switch (purpose)
                    {
                    case MessagePurpose.AskingForTime:
                        // no debería pasar esto
                        Debug.WriteLine("WARNING : Server Ask for time.");
                        break;

                    case MessagePurpose.AskForPassword:
                        Debug.WriteLine("Server Ask for password");
                        break;

                    case MessagePurpose.AskingForAuthentication:
                        Debug.WriteLine("Server asked for authentication");
                        break;

                    case MessagePurpose.TimeGranted:
                        Debug.WriteLine("More time granted");
                        // renovar el contador de intentos fallidos
                        tryCount = 0;
                        break;

                    case MessagePurpose.PasswordAccepted:
                        Debug.WriteLine("Password accepted");
                        byte[] sessionArray = new byte[receiveBytes.Length - 1];
                        System.Array.Copy(receiveBytes, 1, sessionArray, 0, receiveBytes.Length - 1);

                        UtnEmall.Client.SmartClientLayer.Connection.Session     = Encoding.ASCII.GetString(sessionArray, 0, sessionArray.Length);
                        UtnEmall.Client.SmartClientLayer.Connection.IsConnected = true;
                        if (ConnectionStateChanged != null)
                        {
                            this.ConnectionStateChanged(this, null);
                        }
                        break;

                    case MessagePurpose.PasswordRejected:
                        Debug.WriteLine("Password rejected");
                        break;
                    }
                }
                catch (InvalidCastException castError)
                {
                    Debug.WriteLine(castError.Message);
                }
                catch (SocketException socketException)
                {
                    udpClient.Close();
                    udpClient        = null;
                    ipEndPointServer = null;

                    CreateClient();

                    Debug.WriteLine("SocketException: " + socketException.Message);

                    UtnEmall.Client.SmartClientLayer.Connection.IsConnected = false;
                    if (ConnectionStateChanged != null)
                    {
                        this.ConnectionStateChanged(this, null);
                    }
                }
                catch (FormatException formatException)
                {
                    Debug.WriteLine("FormatException: " + formatException.Message);

                    UtnEmall.Client.SmartClientLayer.Connection.IsConnected = false;
                    if (ConnectionStateChanged != null)
                    {
                        this.ConnectionStateChanged(this, null);
                    }
                }
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Comienza escucha para dispositivos móviles
        /// </summary>
        public void ListenForMobileDevices()
        {
            EndPoint clientEndPoint;

            byte[] inputBytes;
            byte[] userIDBytes;
            string mobileID;

            //  Loop while the application is running.
            //
            while (true)
            {
                clientEndPoint = new IPEndPoint(IPAddress.Any, discoveryPort);
                inputBytes     = new byte[512];

                try
                {
                    // Bloquea el puerto 20145 hasta que se reciben datos desde alguna dirección IP.
                    serverSocket.ReceiveFrom(inputBytes, inputBytes.Length, SocketFlags.None, ref clientEndPoint);
                    // String de finalización
                    inputBytes[inputBytes.Length - 1] = 0;

                    // Verifica si el mensaje tiene por lo menos una byte.
                    if (inputBytes.Length >= 2)
                    {
                        // Obtiene el cliente IP y el mensaje
                        IPEndPoint     clientIPEndPoint = (IPEndPoint)clientEndPoint;
                        MessagePurpose purpose          = (MessagePurpose)inputBytes[0];

                        // Decide si el mensaje requiere más tiempo para autenticación
                        switch (purpose)
                        {
                        case MessagePurpose.AskingForTime:
                            Debug.WriteLine("Received message asking for time from " + clientIPEndPoint.Address + ":" + clientIPEndPoint.Port + " at " + DateTime.Now);

                            // Extrae el id de dispositivo móvil
                            userIDBytes = new byte[inputBytes.Length - 1];
                            System.Array.Copy(inputBytes, 1, userIDBytes, 0, userIDBytes.Length);
                            mobileID = Encoding.ASCII.GetString(userIDBytes).Trim('\0');

                            // Verifica que el dispositivo está autenticado.
                            bool existsMobile = sessionManager.MobileHasAuthenticated(mobileID);

                            if (existsMobile)
                            {
                                bool mobileHasRenewed = sessionManager.RenewTimestamp(mobileID);

                                // Realiza una renovación y verifica si se realiza correctamente
                                if (mobileHasRenewed)
                                {
                                    // Informa al dispositivo sobre la extensión de tiempo.
                                    this.SendRaisedTimeFrameMessage(clientEndPoint, mobileID);
                                }
                                else
                                {
                                    // Informa al dispositivo de la necesidad de autenticación
                                    this.SendPasswordRequiredMessage(clientEndPoint, mobileID);
                                }
                            }
                            else
                            {
                                // Informa al dispositivo de la necesidad de autenticación
                                this.SendPasswordRequiredMessage(clientEndPoint, mobileID);
                            }
                            break;

                        case MessagePurpose.AskingForAuthentication:
                            Debug.WriteLine("Received message asking for authentication from " + clientIPEndPoint.Address + ":" + clientIPEndPoint.Port + " at " + DateTime.Now);

                            // Verifica la longitud mínima
                            if (inputBytes.Length < 22)
                            {
                                break;
                            }

                            // Extrae la contraseña del mensaje
                            byte[] passwordHashBytes = new byte[20];
                            System.Array.Copy(inputBytes, 1, passwordHashBytes, 0, 20);

                            // Extrae el id de dispositivo
                            userIDBytes = new byte[inputBytes.Length - 20 - 1];
                            System.Array.Copy(inputBytes, 20 + 1, userIDBytes, 0, userIDBytes.Length);
                            mobileID = Encoding.ASCII.GetString(userIDBytes).Trim('\0');

                            // Realiza el proceso de autenticación
                            bool hadLoggedIn = !String.IsNullOrEmpty(sessionManager.ValidateLogin(mobileID, passwordHashBytes, true));

                            if (hadLoggedIn)
                            {
                                this.SendAcceptedPasswordMessage(clientEndPoint, sessionManager.LoggedMobiles[mobileID]);
                            }
                            else
                            {
                                // Informa al dispositivo del inicio de sesión fallido
                                this.SendRejectedPasswordMessage(clientEndPoint, mobileID);
                            }
                            break;
                        }
                    }
                }
                catch (InvalidCastException castError)
                {
                    Debug.WriteLine(castError.Message);
                }
                catch (SocketException socketError)
                {
                    Debug.Write("Error: " + socketError.ErrorCode + " : " + socketError.Message);
                }
            }
        }
Ejemplo n.º 6
0
        public bool ShowMessage(string text, string caption, MessageType messageType, MessagePurpose purpose = MessagePurpose.INFORMATION)
        {
            // Choose an appropriate image to this message purpose.
            MessageBoxImage messagePurpose;

            switch (purpose)
            {
            case MessagePurpose.ERROR:
                messagePurpose = MessageBoxImage.Error;
                break;

            case MessagePurpose.DEBUG:
                messagePurpose = MessageBoxImage.Asterisk;
                break;

            case MessagePurpose.INFORMATION:
            default:
                messagePurpose = MessageBoxImage.Information;
                break;
            }

            // Choose and appropriate MessageBoxButton for this message type
            MessageBoxButton messageButtons;

            switch (messageType)
            {
            case MessageType.ACCEPT_CANCEL_MESSAGE:
                messageButtons = MessageBoxButton.OKCancel;
                break;

            case MessageType.YES_NO_MESSAGE:
                messageButtons = MessageBoxButton.YesNo;
                break;

            case MessageType.OK_MESSAGE:
            default:
                messageButtons = MessageBoxButton.OK;
                break;
            }

            // Display the message box and return the user's response.
            MessageBoxResult result = MessageBox.Show(text, caption, messageButtons, messagePurpose, MessageBoxResult.OK, MessageBoxOptions.RtlReading);

            if (result == MessageBoxResult.Yes || result == MessageBoxResult.OK)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }