/// <summary>
        /// Método ActualizarEstadoPedido.
        /// </summary>
        /// <returns>Task{Orders}</returns>
        private async Task <Orders> ActualizarEstadoPedido(Orders ordenPedido)
        {
            var estadoActualOrden = await this.tiendaVirtualRepositorio.ObtenerPorId <Entities.Models.Status>(ordenPedido.Status_Id);

            if (estadoActualOrden.Status_Description == ESTADO_OK_PAGO_APROVADO)
            {
                ordenPedido.OrderStatus = estadoActualOrden;
                return(await Task.FromResult(ordenPedido));
            }
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
            var gateWay = new P2P(ConfigurationManager.AppSettings["Login_Ws_PlaceToPay"],
                                  ConfigurationManager.AppSettings["TranKey_Ws_PlaceToPay"],
                                  new Uri(ConfigurationManager.AppSettings["Url_Ws_PlaceToPay"]), Gateway.TP_REST);
            RedirectInformation response = gateWay.Query(ordenPedido.Request_Id);
            var estadoOrden = await this.tiendaVirtualRepositorio.ProcesarEstadoOrden(response.Status.status);

            ordenPedido.OrderStatus = estadoOrden;
            if (estadoOrden.Id != ordenPedido.Status_Id)
            {
                ordenPedido.Status_Id  = estadoOrden.Id;
                ordenPedido.Updated_At = DateTime.Now;
                this.tiendaVirtualRepositorio.Actualizar(ordenPedido);
            }
            return(await Task.FromResult(ordenPedido));
        }
Ejemplo n.º 2
0
        private void SendPing()
        {
            m_LastPing = DateTimeEx.UtcNowMilli;
            MemoryStream Output  = new MemoryStream();
            BinaryWriter BOutput = new BinaryWriter(Output);

            BOutput.Write((byte)Protocol.PING);
            Send(ref Output);
            m_Counter++;
            if ((m_Counter > 2) && m_OnLine)
            {
#if DEBUG
                if (m_Counter > 2)
                {
                    Log.LogMessage("Peer [" + CallSign + "] Passage en état OffLine = Timeout", Color.DarkBlue, 1);
                }
                else
                {
                    Log.LogMessage("Peer [" + CallSign + "] Passage en état OffLine = Déconnexion", Color.DarkBlue, 1);
                }
#endif
                m_OnLine   = false;
                m_Version  = 0;
                m_MiniPing = 1000;
                P2P.UpdateListItem(CallSign);
                Spawn_AI(false);
            }
        }
        /// <summary>
        /// Método CrearOrdenPedido.
        /// </summary>
        /// <returns>Task{Orders}</returns>
        public async Task <Orders> CrearOrdenPedido(Orders ordenPedido, string direccionIP, string agenteUsuario)
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
            var gateWay = new P2P(ConfigurationManager.AppSettings["Login_Ws_PlaceToPay"],
                                  ConfigurationManager.AppSettings["TranKey_Ws_PlaceToPay"],
                                  new Uri(ConfigurationManager.AppSettings["Url_Ws_PlaceToPay"]), Gateway.TP_REST);
            Amount  montoPago            = new Amount(TOTAL_PAGO);
            Payment pagoPedido           = new Payment(PRODUCTO, PRODUCTO, montoPago);
            var     tiempoExpiracionPago = DateTime.Now.AddMinutes(10);

            ordenPedido.OrderStatus = await this.tiendaVirtualRepositorio.ProcesarEstadoOrden(ESTADOINICIALORDEN);

            ordenPedido.Status_Id  = ordenPedido.OrderStatus.Id;
            ordenPedido.Created_At = DateTime.Now;
            this.tiendaVirtualRepositorio.Insertar(ordenPedido);
            var             urlRedireccionamientoLocal  = string.Format("{0}/{1}{2}", ordenPedido.UrlRaiz, "ordenes/visualizarestado/false/", ordenPedido.Id);
            RedirectRequest solicitudRedireccionamiento = new RedirectRequest(pagoPedido, urlRedireccionamientoLocal, direccionIP,
                                                                              agenteUsuario, tiempoExpiracionPago.ToString("s", CultureInfo.InvariantCulture));

            solicitudRedireccionamiento.Buyer = new Person(string.Empty, string.Empty, ordenPedido.Customer_Name,
                                                           string.Empty, ordenPedido.Customer_Email, mobile: ordenPedido.Customer_Mobile);
            solicitudRedireccionamiento.Locale    = "es_CO";
            solicitudRedireccionamiento.CancelUrl = urlRedireccionamientoLocal;
            RedirectResponse response = gateWay.Request(solicitudRedireccionamiento);

            if (response.Status.status != ESTADO_OK_CREACION_ORDENPEDIDO)
            {
                this.tiendaVirtualRepositorio.Eliminar(ordenPedido);
                throw new Exception(response.Status.Message);
            }
            ordenPedido.Request_Id       = response.RequestId;
            ordenPedido.UrlProcesamiento = response.ProcessUrl;
            this.tiendaVirtualRepositorio.Actualizar(ordenPedido);
            return(await Task.FromResult(ordenPedido));
        }
 /// <summary>
 /// Creates and initializes a new instance of NetworkP2PHandoverInstance.
 /// </summary>
 /// <param name="networkView">The network view to use for the object being handovered.</param>
 /// <param name="p2p">The NetworkP2P component used for handing this object over.</param>
 /// <param name="offsetPos">Offset position of the object compared to the <c>p2p</c> which is handing it over.</param>
 /// <param name="offsetRot">Offset rotation of the object compared to the <c>p2p</c> which is handing it over.</param>
 public NetworkP2PHandoverInstance(NetworkViewBase networkView, NetworkP2PBase p2p, Vector3 offsetPos, Quaternion offsetRot)
     : this(networkView, p2p)
 {
     position   += offsetPos;
     rotation   *= offsetRot;
     _networkP2P = p2p as P2P;
 }
        internal NetworkP2PHandoverInstance(NetBuffer buffer)
        {
            _networkView = null;

            position   = new Vector3(buffer.ReadFloat(), buffer.ReadFloat(), buffer.ReadFloat());
            rotation   = new Quaternion(buffer.ReadFloat(), buffer.ReadFloat(), buffer.ReadFloat(), buffer.ReadFloat());
            relativeTo = (NetworkP2PSpace)buffer.ReadByte();

            remoteViewID           = new NetworkViewID(buffer);
            group                  = new NetworkGroup(buffer);
            authFlags              = (NetworkAuthFlags)buffer.ReadByte();
            isInstantiatedRemotely = buffer.ReadBoolean();

            proxyPrefab  = buffer.ReadString();
            ownerPrefab  = buffer.ReadString();
            serverPrefab = buffer.ReadString();

            cellAuthPrefab  = buffer.ReadString();
            cellProxyPrefab = buffer.ReadString();

            uint initialSize = buffer.ReadVariableUInt32();

            _initialData = initialSize != 0 ? buffer.ReadBytes((int)initialSize) : new byte[0];

            uint handoverSize = buffer.ReadVariableUInt32();

            _handoverData = handoverSize != 0 ? buffer.ReadBytes((int)handoverSize) : new byte[0];

            _isInstantiatable = true;
            _networkP2P       = null;
        }
Ejemplo n.º 6
0
        private void timerUpdateData_Tick(object sender, EventArgs e)
        {
            Perfomance           = PsApiWrapper.GetPerformanceInfo();
            statusTextStrip.Text = string.Format(Resources.Home_timerUpdateData_Tick__0____1____2____3_,
                                                 Perfomance.PhysicalTotalMb, Perfomance.PhysicalAvailableMb,
                                                 Perfomance.PhysicalPercentFree, Perfomance.PhysicalOccupied); //избыточные данные

            P2P.SendMessage();
        }
        public void MyTestInitialize()
        {
            var pair = P2P.GeneratePair(provider);

            Connection1 = pair.Item1;
            Connection2 = pair.Item2;

            runnertask1 = Task.Run(() => Connection1.RunCollector());
            runnertask2 = Task.Run(() => Connection2.RunCollector());
        }
Ejemplo n.º 8
0
        private void disconnectMenu_Click(object sender, EventArgs e)
        {
            timerSetData.Stop();

            P2P.Closing();

            menuStrip.Items.Insert(menuStrip.Items.IndexOf(disconnectMenu), connectMenu);
            menuStrip.Items.Remove(disconnectMenu);

            refreshMenu.Enabled = false;
        }
Ejemplo n.º 9
0
        public async Task <IPodcastModel> GetP2PBySlug(string slug)
        {
            if (slug == null)
            {
                throw new ArgumentNullException(nameof(slug));
            }

            P2P p2p = await _podcastRepository.GetP2PBySlug(slug);

            IPodcastModel podcastModel = await _podcastModelMapper.Map(p2p);

            return(podcastModel);
        }
Ejemplo n.º 10
0
    private void DispatchEvent(Packet packet)
    {
        ushort packetid = packet.ReadPacketid();

        Log.Debug("Net Received server protocol id: " + packetid);

        if (this._msg_eventhandler_map.ContainsKey(packetid))
        {
            EventHandler eventHandler = this._msg_eventhandler_map[packetid];
            if (eventHandler != null)
            {
                eventHandler(packetid, P2P.PacketToProtocol(packetid, packet));
            }
        }
    }
Ejemplo n.º 11
0
        private void connectMenu_Click(object sender, EventArgs e)
        {
            if (DlgSetting.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            P2P.Opening();

            menuStrip.Items.Insert(menuStrip.Items.IndexOf(connectMenu), disconnectMenu);
            menuStrip.Items.Remove(connectMenu);

            refreshMenu.Enabled = true;

            P2P.Refresh();
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Save or update device to database
        /// </summary>
        /// <param name="device">Device object that need to update or save</param>
        /// <returns></returns>
        public bool RegisterDevice(P2P.Model.Device device)
        {
            //check if device already exist
            PersistantDevice _device = persist.GetDeviceDetailsByDeviceId(device.Id);

            if (_device == null)
            {
                //if exist then update else insert new record
                persist.RegisterDevice(ConvertModelToPersistant(device));
            }
            else
            {
                //if exist then update else insert new record
                persist.UpdateDeviceDetails(ConvertModelToPersistant(device));
            }
            return true;
        }
Ejemplo n.º 13
0
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);

            if (e.CloseReason == CloseReason.WindowsShutDown)
            {
                P2P.Closing();
                return;
            }

            if (MessageBox.Show(string.Format(Resources.Home_OnFormClosing_, DlgSetting.UserName),
                                @"Внимание", MessageBoxButtons.YesNo) != DialogResult.Yes)
            {
                e.Cancel = true;
                return;
            }

            P2P.Closing();
        }
Ejemplo n.º 14
0
        /// Callback Déconnexion du serveur
        /// </summary>
        /// <param name="asyncResult"></param>
        private void DisconnectCB(HttpWebResponse Response)
        {
            if (m_btnConnect != null)
            {
                m_btnConnect.Invoke(new Action(() =>
                {
                    m_btnConnect.Enabled = true;;
                }));
            }
            XmlDocument xmlDoc = null;

            if (Response != null)
            {
                xmlDoc = GetResultXml(ref Response);
                Response.Close();
            }
            m_bConnected   = false;
            m_SyncAIDone   = false;
            m_AIManagement = false;
            Key            = "";
            Log.LogMessage("Déconnecté du serveur");
            m_btnConnect.Invoke(new Action(() =>
            {
                m_btnConnect.ImageIndex = 0;
                ButtonsTips.SetToolTip(m_btnConnect, "Connexion au serveur");
                P2P.Clear();
                if (DelayedExit)
                {
                    System.Windows.Forms.Application.Exit();
                    DelayedExit = false;
                }
                else if (DelayReco)
                {
                    m_btnConnect.Invoke(new Action(() => { m_btnConnect.PerformClick(); }));
                    DelayReco = false;
                }
            }));
        }
Ejemplo n.º 15
0
        private void peerList_SelectedIndexChanged(object sender, EventArgs e)
        {
            timerSetData.Start();

            var peerName = peerList.GetItemText(peerList.SelectedItem);

            if (peerName == "Пиры не найдены!")
            {
                return;
            }

            var peerData = AllPeerData.GetPeerData(peerName);

            if (peerData == "_Please_Update_Peer_")
            {
                P2P.Refresh();
                //return;
            }
            else
            {
                peerDataBox.Text = peerData;
            }
        }
        public async Task GetP2PBySlug_Should_Return_Call_IPodcastModelMapper_Map()
        {
            PodcastServiceMock mock = PodcastServiceMock.Create();

            var slug = "yalin-kod-bilgem-cakir";

            var p2p = new P2P {
                Id = 1, Title = "Yalın Kod - Bilgem Çakır"
            };

            mock.PodcastRepository
            .Setup(repository => repository.GetP2PBySlug(It.Is <string>(s => s == slug)))
            .ReturnsAsync(() => p2p);

            mock.PodcastModelMapper
            .Setup(mapper => mapper.Map(It.Is <P2P>(p => p.Id == p2p.Id && p.Title == p2p.Title)))
            .ReturnsAsync(() => new P2PModel());

            IPodcastModel p2pModel = await mock.GetP2PBySlug(slug);

            mock.PodcastModelMapper.Verify(repository => repository.Map(It.IsAny <P2P>()), Times.Once);
            Assert.NotNull(p2pModel);
        }
        /// <summary>
        /// Creates and initializes a new instance of NetworkP2PHandoverInstance.
        /// </summary>
        /// <param name="networkView">The network view to use for the object being handovered.</param>
        /// <param name="position">Position of the object being handovered.</param>
        /// <param name="rotation">Rotation to use for the object being handovered.</param>
        /// <param name="relativeTo">The space that position and rotation should be relative to.</param>
        public NetworkP2PHandoverInstance(NetworkViewBase networkView, Vector3 position, Quaternion rotation, NetworkP2PSpace relativeTo)
        {
            this.position   = position;
            this.rotation   = rotation;
            this.relativeTo = relativeTo;

            _networkView           = networkView.root as NV;   // make sure it's the parent networkview and not a child
            remoteViewID           = _networkView.viewID;
            group                  = _networkView.group;
            authFlags              = _networkView._data.authFlags; // TODO: ugly hack to void authority permission check
            isInstantiatedRemotely = _networkView.isInstantiatedRemotely;

            proxyPrefab     = _networkView.proxyPrefab;
            ownerPrefab     = _networkView.ownerPrefab;
            serverPrefab    = _networkView.serverPrefab;
            cellAuthPrefab  = _networkView.cellAuthPrefab;
            cellProxyPrefab = _networkView.cellProxyPrefab;

            _initialData  = null;
            _handoverData = null;

            _isInstantiatable = false;
            _networkP2P       = null;
        }
Ejemplo n.º 18
0
    private static void DoMsg(Socket clientSocket, ushort packetid, Packet packet)
    {
        Console.WriteLine("packetid: {0}", packetid);

        switch (packetid)
        {
        case 40040:
            // ReqTestXX reqTestXX = new ReqTestXX(packet);
            ReqTestXX reqTestXX = P2P.PacketToProtocol(packetid, packet) as ReqTestXX;

            Console.WriteLine("{0} {1} {2} {3} {4}", reqTestXX.id_u8, reqTestXX.id_u16, reqTestXX.id_u32, reqTestXX.repeat_id_u8, reqTestXX.optional_id_u8);

            AckTestXX ackTestXX = new AckTestXX();
            ackTestXX.id_u8          = 111;
            ackTestXX.id_u16         = 11111;
            ackTestXX.id_u32         = 1111111;
            ackTestXX.optional_id_u8 = 222;
            ackTestXX.repeat_id_u8   = new List <byte>();

            clientSocket.Send(ackTestXX.Encode().GetBufferBytes());

            break;
        }
    }
Ejemplo n.º 19
0
        /// <summary>
        /// Callback Demande de connexion
        /// </summary>
        /// <param name="asyncResult"></param>
        private void ConnectCB(HttpWebResponse Response)
        {
            if (m_btnConnect != null)
            {
                m_btnConnect.Invoke(new Action(() =>
                {
                    m_btnConnect.Enabled = true;;
                }));
            }
            XmlDocument xmlDoc = null;

            if (Response != null)
            {
                if (Response.StatusCode != HttpStatusCode.OK)
                {
                    Log.LogMessage("Erreur de connexion : " + Response.StatusDescription, Color.DarkViolet);
                }
                xmlDoc = GetResultXml(ref Response);
                Response.Close();
            }
            if (xmlDoc == null)
            {
                Log.LogMessage("Erreur de connexion", Color.DarkViolet);
                return;
            }
            bool    bError = CheckError(xmlDoc);
            XmlNode Node   = GetFirstElement(ref xmlDoc, "loginStatus");

            if (Node != null)
            {
                if (Node.InnerText == "1")
                {
                    m_bConnected = true;
                }
                else
                {
                    m_bConnected = false;
                }
                if (m_bConnected && (!bError))
                {
                    Log.LogMessage("ffs2play est connecté au serveur");
                    XmlNode xmlExternalIP = GetFirstElement(ref xmlDoc, "your_ip");
                    if (xmlExternalIP != null)
                    {
                        IPAddress ExternalIP = IPAddress.Parse("0.0.0.0");
                        if (IPAddress.TryParse(xmlExternalIP.InnerText, out ExternalIP))
                        {
#if DEBUG
                            Log.LogMessage("PManager: Reçu IP Exterieure = " + ExternalIP.ToString(), Color.DarkBlue, 2);
#endif
                        }
                        else
                        {
#if DEBUG
                            Log.LogMessage("PManager: Reçu IP Exterieure invalide", Color.DarkViolet, 2);
#endif
                        }
                        P2P.ExternalIP = ExternalIP;
                    }
                    else
                    {
                        Log.LogMessage("Le serveur n'a pas retourné votre IP extérieure");
                        m_bConnected = false;
                        return;
                    }

                    XmlNode xmlKey = GetFirstElement(ref xmlDoc, "key");
                    if (xmlKey != null)
                    {
                        Key = xmlKey.InnerText;
                        OnLiveUpdate(null, null);
                    }
                    else
                    {
                        Log.LogMessage("Le serveur n'a pas retourné de clé d'authentification");
                    }

                    XmlNode xmlAtc = GetFirstElement(ref xmlDoc, "atc");
                    if (xmlAtc != null)
                    {
                        if (xmlAtc.InnerText != "")
                        {
                            if (Convert.ToBoolean(xmlAtc.InnerText))
                            {
                                ATCTimer.Start();
                            }
                        }
                    }

                    XmlNode AIManagement = GetFirstElement(ref xmlDoc, "AI_Management");
                    if (AIManagement != null)
                    {
                        if (AIManagement.InnerText != "")
                        {
                            m_AIManagement = Convert.ToBoolean(AIManagement.InnerText);
                        }
                    }

                    // Passage du fond du bouton en vert
                    m_btnConnect.Invoke(new Action(() =>
                    {
                        m_btnConnect.ImageIndex = 1;
                        ButtonsTips.SetToolTip(m_btnConnect, "Déconnexion du serveur");
                    }));
                    // On charge la liste des joueurs depuis le wazzup
                    XmlNode Wazzup = GetFirstElement(ref xmlDoc, "whazzup");
                    if (Wazzup != null)
                    {
                        P2P.Wazzup_Update(Wazzup, m_sAESKey);
                    }
                }
                else
                {
                    Log.LogMessage("Le serveur a refusé la connexion");
                    return;
                }
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Réception d'un datagramme entrant sur le socket udp
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnReceiveMessage(object sender, UDPReceiveEvent evt)
        {
            // Si l'adresse du peer est nulle cela signifie que le wazzhup update a détecté un PEER local
            if (m_EP == null)
            {
                // Si le peer à une addresse locale qui correspond
                // Il s'agit d'un client sur le même réseau local
                // On prend alors cette IP locale comme référence
                if (m_InternalIP.Contains(evt.Client.Address))
                {
                    m_EP = new IPEndPoint(evt.Client.Address, m_Port);
                }
                else
                {
                    return;
                }
            }
            else if ((!evt.Client.Address.Equals(m_EP.Address)) || (evt.Client.Port != m_Port))
            {
                return;
            }
            BinaryReader reader = new BinaryReader(new MemoryStream(evt.Data));

            try
            {
                switch ((Protocol)reader.ReadByte())
                {
                case Protocol.PING:
                {
                    SendPong(evt.Time);
                    break;
                }

                case Protocol.PONG:
                {
                    m_Latence = (evt.Time - m_LastPing) / 2;
                    m_Counter = 0;
                    long TimePong = reader.ReadInt64();
                    if (m_MiniPing > m_Latence)
                    {
                        m_Decalage = evt.Time - m_Latence - TimePong;
                        m_MiniPing = m_Latence;
                    }
                    if (!m_OnLine)
                    {
#if DEBUG
                        Log.LogMessage("Peer [" + CallSign + "] Passage en état OnLine", Color.DarkBlue, 1);
#endif
                        m_OnLine      = true;
                        m_Distance    = -1;
                        m_Counter_In  = 0;
                        m_Counter_Out = 0;
                    }
                    if (m_Version == 0)
                    {
                        RequestVersion();
                    }
                    P2P.UpdateListItem(m_CallSign);
                    break;
                }

                case Protocol.CHAT:
                {
                    string Message = reader.ReadString();
                    P2P.AddLineChat(CallSign, Message);
                    m_SC.SendScrollingText(CallSign + " : " + Message);
                    break;
                }

                case Protocol.DATA:
                {
                    if (m_Version == PROTO_VERSION)
                    {
                        if (m_bBlockData)
                        {
                            return;
                        }
                        m_Mutex.WaitOne();
                        try
                        {
                            byte CounterIn = reader.ReadByte();
                            // Si le compteur reçu est supérieur nous avons une donnée récente
                            if (((CounterIn - m_Counter_In) > 0) || (m_Counter_In == 255))
                            {
                                m_OldData.Clone(m_Data);
                                int Len = reader.ReadInt32();
                                reader.BaseStream.Seek(2, 0);

                                m_Data            = (AirData)Serializer.Deserialize <AirData>(reader.BaseStream);
                                m_Data.TimeStamp += m_Decalage;
                                if (m_Data.TimeStamp <= m_OldData.TimeStamp)
                                {
#if DEBUG
                                    Log.LogMessage("Peer[" + CallSign + "] Donées en retard ignorées", Color.DarkBlue, 1);
#endif
                                    return;
                                }
                                if ((m_Spawned >= 4) && (m_Spawned < 5))
                                {
                                    m_Spawned++;
                                }
                                m_RefreshRate       = evt.Time - m_LastData;
                                m_LastData          = evt.Time;
                                m_RemoteRefreshRate = m_Data.TimeStamp - m_OldData.TimeStamp;
                                m_Distance          = Outils.distance(m_Data.Latitude, m_Data.Longitude, m_SendData.Latitude, m_SendData.Longitude, 'N');
#if DEBUG
                                if ((CounterIn - m_Counter_In) > 1)
                                {
                                    Log.LogMessage("Peer [" + CallSign + "] Paquets Udp Manquants =" + (CounterIn - m_Counter_In - 1).ToString(), Color.DarkViolet, 1);
                                }
#endif
                                if (m_Spawned >= 5)
                                {
                                    RefreshData();
                                }
                            }
#if DEBUG
                            else
                            {
                                Log.LogMessage("Peer [" + CallSign + "] Paquets Udp ignoré en retard de " + (m_Counter_In - CounterIn).ToString(), Color.DarkViolet, 1);
                            }
#endif
                            m_Counter_In = CounterIn;
                        }
                        finally
                        {
                            m_Mutex.ReleaseMutex();
                        }
                    }
                    break;
                }

                case Protocol.VERSION:
                {
                    m_Version = reader.ReadByte();
                    if (m_Version == PROTO_VERSION)
                    {
                        m_Data.Title = reader.ReadString();
                        if (m_Spawned >= 3)
                        {
                            Spawn_AI(false);
                        }
                        m_Data.Type     = reader.ReadString();
                        m_Data.Model    = reader.ReadString();
                        m_Data.Category = reader.ReadString();
                    }
                    P2P.UpdateListItem(m_CallSign);
#if DEBUG
                    Log.LogMessage("Peer [" + CallSign + "] reçu numéro de version = " + m_Version.ToString(), Color.DarkBlue, 1);
#endif
                    break;
                }

                case Protocol.REQ_VERSION:
                {
                    SendVersion();
                    break;
                }
                }
            }
            catch (Exception e)
            {
                Log.LogMessage("Peer [" + CallSign + "] Erreur d'analyse du datagramme : " + e.Message, Color.DarkViolet, 0);
            }
        }
Ejemplo n.º 21
0
        public override void Update(GameTime gameTime)
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Z))
            {
                P2P peer = new P2P();
                Global.host = int.Parse(boxValue[1]);
                Thread server = new Thread(() => peer.Listener(Global.host, Global.name));
                server.Start();
                Thread client = new Thread(() => peer.Client()); //Start the client, this is responcible for sending out all packets.
                client.Start();
                if (boxValue[0] != null && boxValue[0] != "")
                {
                    if (int.Parse(boxValue[0]) != 0)
                    {
                        Console.WriteLine("doing");
                        Thread connector = new Thread(() => peer.Connector(int.Parse(boxValue[0]), boxValue[2], Global.name)); //Start a new Connector connecing to the port of the first box and the IP of the third box
                        connector.Start();
                    }
                }
                SubmitTexture();
            }
            else if (GamePad.GetState(PlayerIndex.One).IsConnected&& GamePad.GetState(PlayerIndex.One).IsButtonDown(Buttons.A))
            {
                SubmitTexture();
            }

            if (Keyboard.GetState().IsKeyDown(Keys.X))
            {
                ReloadImage();
            }
            KeyboardState kbState = Keyboard.GetState();

            Keys[] pressedKeys = kbState.GetPressedKeys();

            foreach (Keys key in lastPressedKey)
            {
                if (!pressedKeys.Contains(key))
                {
                    if (key == Keys.Back || key == Keys.Delete)
                    {
                        if (boxValue[target].Length > 0)
                        {
                            boxValue[target] = boxValue[target].Substring(0, boxValue[target].Length - 1);
                        }
                    }
                    else if (key == Keys.OemPeriod)
                    {
                        boxValue[target] += ".";
                    }
                    else if (key == Keys.Tab)
                    {
                        target++;
                        target = target % boxBox.Count();
                    }
                    else
                    {
                        if (boxValue[target].Length < maxLength[target])
                        {
                            boxValue[target] = boxValue[target] + (string)key.ToString().Substring(key.ToString().Length - 1);
                        }
                    }
                }
            }
            Console.WriteLine(boxValue[target]);
            lastPressedKey = pressedKeys;
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Callback Requete de mise à jour
        /// </summary>
        /// <param name="asyncResult"></param>
        private void LiveUpdateCB(HttpWebResponse Response)
        {
            // Si pas connecté au serveur on ignore le CB
            if (!m_bConnected)
            {
                return;
            }
            XmlDocument xmlDoc = null;

            // On récupère le contenu XML
            if (Response != null)
            {
                xmlDoc = GetResultXml(ref Response);
                Response.Close();
            }
            // Si le contenu est vide on ignore le CB
            if (xmlDoc == null)
            {
                return;
            }

            LastGoodUpdate = DateTimeEx.UtcNowMilli;
            //On vérifie les erreurs retournées par le serveur
            if (CheckError(xmlDoc))
            {
                Disconnect();
                return;
            }
            // On charge la liste des joueurs depuis le wazzup
            XmlNode Wazzup = GetFirstElement(ref xmlDoc, "whazzup");

            if (Wazzup != null)
            {
                P2P.Wazzup_Update(Wazzup, m_sAESKey);
            }
            //On synchronise le serveur avec les AI disponibles
            if ((!m_SyncAIDone) && m_AIManagement)
            {
                if (!Mapping.IsInit)
                {
                    return;
                }
                XmlBuild(ref SendSyncAI, XmlCode.syncai);
                XmlNodeList Nodes = SendSyncAI.GetElementsByTagName("syncai");
                foreach (XmlNode node in Nodes)
                {
                    foreach (XmlNode child in node.ChildNodes)
                    {
                        switch (child.Name)
                        {
                        case "md5list":
                            child.InnerText = Outils.PhpSerialize(Mapping.GetList.Keys);
                            break;
                        }
                    }
                }
                HTTPRequestThread Requete = new HTTPRequestThread(SendSyncAI, m_sURL, SyncAICB);
                Requete.Start();
#if DEBUG
                Log.LogMessage("PManager: Synchronisation des AI : \n" + Beautify(SendSyncAI), Color.DarkRed, 2);
#endif
            }
            // On check la méteo
            XmlNode Metar = GetFirstElement(ref xmlDoc, "metar");
            if (Metar != null)
            {
                MetarUpdate(ref Metar);
            }
        }
Ejemplo n.º 23
0
 private void refresh_Click(object sender, EventArgs e)
 {
     timerSetData.Stop();
     P2P.Refresh();
 }
 /// <summary>
 /// Creates and initializes a new instance of NetworkP2PHandoverInstance.
 /// </summary>
 /// <param name="networkView">The network view to use for the object being handovered.</param>
 /// <param name="p2p">The NetworkP2P component used for handing this object over.</param>
 public NetworkP2PHandoverInstance(NetworkViewBase networkView, NetworkP2PBase p2p)
     : this(networkView, networkView.position, networkView.rotation, NetworkP2PSpace.NetworkP2P)
 {
     p2p.InverseTransform(ref position, ref rotation);
     _networkP2P = p2p as P2P;
 }