private void HandleResponseMessage(string message)
 {
     if (OnResponse != null)
     {
         OnResponse.Invoke(message);
     }
 }
Exemplo n.º 2
0
        /*Definition for Callback Methods*/
        public async void Call <T>()
        {
            CheckExeptions();
            HttpResponseDTO <object> responseDto = new HttpResponseDTO <object>();
            string urlRequest = FullUrl ?? RequestUri;

            HttpResponseMessage response = null;

            try
            {
                response = GetHttpResponse(urlRequest);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e);
            }

            string jsonString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            responseDto.StatusCode = response.StatusCode;
            if (response.StatusCode == (HttpStatusCode)401)
            {
                responseDto.Message = "You are not authorized to request this resource";
                OnFailure?.Invoke(responseDto);
            }
            else
            {
                T dynamicObj = JsonConvert.DeserializeObject <T>(jsonString);
                responseDto.Body = dynamicObj;
                OnResponse?.Invoke(responseDto);
            }
        }
Exemplo n.º 3
0
        public async void Send(string input)
        {
            //this.micClient.EndMicAndRecognition();
            if (!isStopped)
            {
                try
                {
                    OnResponse?.Invoke(input, MessageType.History);

                    if (!string.IsNullOrEmpty(input))
                    {
                        Activity userMessage = new Activity
                        {
                            From = new ChannelAccount(fromUser),
                            Text = input,
                            Type = ActivityTypes.Message
                        };

                        await client.Conversations.PostActivityAsync(conversation.ConversationId, userMessage);
                    }
                }
                catch (Exception)
                {
                }
            }
        }
Exemplo n.º 4
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (this._apiKey != null)
            {
                request.Headers.Add("X-Api-Key", this._apiKey);
            }

            IEndpoint endpoint = request.Properties.ContainsKey("Endpoint") ? (IEndpoint)request.Properties["Endpoint"] : null;

            if (endpoint?.RequireAuth == true || (authInfo != null))
            {
                if (!request.Headers.Contains("Authorization"))
                {
                    request.Headers.Add("Authorization", $"Bearer {authInfo.AccessToken}");
                }
            }

            //  Dispatch to on send listeners
            OnSend?.Invoke(this, request, endpoint);

            //
            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

            //  Dispatch to on response listeners
            OnResponse?.Invoke(this, response, endpoint);

            return(response);
        }
Exemplo n.º 5
0
 public void Response(string response)
 {
     OnResponse.Invoke(new HttpRerquestEventArgs
     {
         Response = response
     });
 }
Exemplo n.º 6
0
 private void OnMouseEvent(UIMouseEventType type, UpdateState state)
 {
     if (type == UIMouseEventType.MouseDown)
     {
         OnResponse?.Invoke(true);
     }
 }
Exemplo n.º 7
0
        public virtual object Complete(ProtoState state)
        {
            var res = state.Complete();

            OnResponse?.Invoke(this, state);
            AllDone.Reset();
            return(res);
        }
Exemplo n.º 8
0
 public MockVMController(IVMFactory vmFactory) : this()
 {
     _vmController = new VMController((connectionId, vmId, vmData) =>
     {
         _response.Handler(connectionId, vmId, vmData);
         OnResponse?.Invoke(this, vmData);
     }, vmFactory);
 }
Exemplo n.º 9
0
        // OLD METHODS ------------------------------------------------------

        public void StartClient(string toSend = "")
        {
            // Connect to a remote device.
            try
            {
                // Establish the remote endpoint for the socket.

                IPHostEntry ipHostInfo = Dns.GetHostEntry(Server);

                Console.WriteLine("Host info:");
                int i = 0;
                for (i = 0; i < ipHostInfo.AddressList.Length; i++)
                {
                    var item = ipHostInfo.AddressList[i].ToString();
                    Console.WriteLine(item);

                    if (item.Contains("."))
                    {
                        break;
                    }
                }

                IPAddress  ipAddress = ipHostInfo.AddressList[i];
                IPEndPoint remoteEP  = new IPEndPoint(ipAddress, port);

                // Create a TCP/IP socket.
                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // Connect to the remote endpoint.
                client.BeginConnect(remoteEP,
                                    new AsyncCallback(ConnectCallback), client);
                connectDone.WaitOne();

                // Send test data to the remote device.
                Send(client, toSend + "<EOF>");
                sendDone.WaitOne();

                // Receive the response from the remote device.
                Receive(client);
                receiveDone.WaitOne();

                // Write the response to the console.
                //Console.WriteLine("Response received : {0}", response);

                // Release the socket.
                client.Shutdown(SocketShutdown.Both);
                client.Close();

                if (OnResponse != null)
                {
                    OnResponse.Invoke(this, new StringBuilder(response));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Exemplo n.º 10
0
        internal Task SetReponseAsync(OicMessage message)
        {
            lock (_reponseLock)
                _response = message;

            _responseTcs.TrySetResult(true);
            return(Task.Run(() => OnResponse?.Invoke(this, new OicRequestResponseEventArgs {
                Message = message
            })));
        }
Exemplo n.º 11
0
 /// <summary>
 /// Sends a command asynchronously. Uses standard Eventpattern. OnResponse will
 /// be raised when the command has executed
 /// </summary>
 /// <param name="cmd"></param>
 public void sendCommandAsync(Command cmd)
 {
     System.Threading.Thread t = new System.Threading.Thread((System.Threading.ThreadStart) delegate
     {
         var response = sendCommand(cmd);
         OnResponse?.Invoke(this, new ResponseEventArgs <Command, Command.Response>(cmd, response));
     });
     t.IsBackground = true;
     t.Start();
 }
Exemplo n.º 12
0
 public string Receive()
 {
     // Receive the response from the remote device.
     Receive(client);
     receiveDone.WaitOne();
     if (OnResponse != null)
     {
         OnResponse.Invoke(this, new StringBuilder(response));
     }
     return(response);
 }
Exemplo n.º 13
0
 internal bool FireResponse(IncomingResponse response)
 {
     lock (Sync)
     {
         if (Responded)
         {
             return(false);
         }
         OnResponse?.Invoke(response);
         return(Responded = true);
     }
 }
Exemplo n.º 14
0
 public async void Accept()
 {
     _guiDispatcher.Invoke(() =>
     {
         OnResponse?.Invoke(Room);
         GameVM gameVm        = new GameVM(Room);
         GameRoom gameRoom    = new GameRoom();
         gameRoom.DataContext = gameVm;
         gameRoom.Visibility  = Visibility.Visible;
     });
     await gameBl.AcceptInvitation(Room, Sender);
 }
Exemplo n.º 15
0
        public void ReadCallback(IAsyncResult ar)
        {
            String content = String.Empty;

            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            StateObject state   = (StateObject)ar.AsyncState;
            Socket      handler = state.workSocket;

            // Read data from the client socket.
            int bytesRead = handler.EndReceive(ar);

            if (bytesRead > 0)
            {
                // There  might be more data, so store the data received so far.
                state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                // Check for end-of-file tag. If it is not there, read
                // more data.
                content = state.sb.ToString();
                if (content.IndexOf("<EOF>") > -1)
                {
                    // All the data has been read from the
                    // client. Display it on the console.
                    // but remove <EOF> tag
                    Console.WriteLine("Read {0} bytes from socket.", content.Length);
                    content = content.Substring(0, content.Length - 5);
                    // Echo the data back to the client.
                    // with modif event
                    var close = false;
                    if (content.IndexOf("close") > -1)
                    {
                        close = true;
                    }
                    state.sb.Clear();
                    state.sb.Append(content);
                    OnResponse.Invoke(this, state.sb);
                    content = state.sb.ToString();
                    Send(handler, content);

                    if (close)
                    {
                        CloseClient(handler);
                    }
                }
                else
                {
                    // Not all data received. Get more.
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                }
            }
        }
Exemplo n.º 16
0
        /// <inheritdoc />
        public override void Respond(string message, string sender = null, string font = null)
        {
            if (sender == "Server")
            {
                sender = null;
                font   = null;
            }

            var msg = new TorchChatMessage(sender ?? TorchBase.Instance.Config.ChatName, message, font ?? TorchBase.Instance.Config.ChatColor);

            Responses.Add(msg);
            OnResponse?.Invoke(msg);
        }
Exemplo n.º 17
0
        public MockVMController(IVMFactory vmFactory, string hubConnectionId = null, Action <string, string> responseDelegate = null) : this()
        {
            _connectionId = hubConnectionId ?? $"conn{IdCount++}";

            _vmController = new VMController((connectionId, vmId, vmData) =>
            {
                _response.Handler(connectionId, vmId, vmData);
                if (responseDelegate != null)
                {
                    responseDelegate(connectionId, vmData);
                }
                else
                {
                    OnResponse?.Invoke(this, vmData);
                }
            }, vmFactory);
        }
Exemplo n.º 18
0
        private void SetText(MessageType type, string text)
        {
            OnResponse?.Invoke(text, type);

            // Read Text
            if (type == MessageType.History)
            {
                if (text.ToLower().Contains("code is"))
                {
                    voice.Speak("I'm sorry. I could not hear you properly.");
                }
                else
                {
                    voice.SpeakAsync(text);
                }
            }
        }
Exemplo n.º 19
0
        public async Task <bool> TryResponse(SocketMessage msg)
        {
            ButtonResponse BR;
            await _locker.WaitAsync().ConfigureAwait(false);

            try
            {
                if (msg == null || msg.Author.IsBot || msg.Channel.Id != Game.Channel)
                {
                    return(false);
                }

                int response = ResponseParse(msg.Content);
                if (response == -1)
                {
                    return(false);
                }

                var usr = msg.Author as IGuildUser;
                if (usr == null)
                {
                    return(false);
                }

                BR = new ButtonResponse()
                {
                    UserID = msg.Author.Id,
                    Pushed = Convert.ToBoolean(response)
                };

                if (Game.Responses.Any(x => x.UserID == msg.Author.Id))
                {
                    return(false);
                }

                if (!Game.Responses.Add(BR))
                {
                    return(false);
                }

                var _ = OnResponse?.Invoke(msg as IUserMessage, usr);
            }
            finally { _locker.Release(); }
            return(true);
        }
Exemplo n.º 20
0
 private void InternalResponse(FormState formState)
 {
     OnResponse?.Invoke(Response);
     if (Response.Succeed && Response.Response.Status.Succeeded())
     {
         Record    = Response.Response.Data;
         FormState = formState;
         OnResponseSucceeded?.Invoke(Response);
     }
     else if (Response.HasException)
     {
         OnResponseException?.Invoke(Response);
     }
     else
     {
         OnResponseFailed?.Invoke(Response);
     }
 }
Exemplo n.º 21
0
        public MockVMController(TViewModel vmInstance = default(TViewModel))
        {
            if (vmInstance?.Equals(default(TViewModel)) == false)
            {
                VMController.CreateInstance = (type, args) => type == typeof(TViewModel) ? vmInstance : throw new InvalidOperationException();
            }
            else
            {
                VMController.CreateInstance = (type, args) => Activator.CreateInstance(type, args);
            }

            VMController.Register <TViewModel>();

            _vmId         = typeof(TViewModel).Name;
            _vmController = new VMController((connectionId, vmId, vmData) =>
            {
                _response.Handler(connectionId, vmId, vmData);
                OnResponse?.Invoke(this, vmData);
            });
        }
        public override void Respond(string message, string sender = "Server", string font = "Blue")
        {
            _response.AppendLine(message);

            if (_cancelToken != null)
            {
                _cancelToken.Cancel();
            }
            _cancelToken = new CancellationTokenSource();

            var a = Task.Delay(500, _cancelToken.Token)
                    .ContinueWith((t) =>
            {
                string chunk;
                lock (_response)
                {
                    chunk = _response.ToString();
                    _response.Clear();
                }
                OnResponse.Invoke(ResponeChannel, chunk, sender, font);
            });
        }
Exemplo n.º 23
0
            protected void Execute()
            {
                var requestThread = new Thread(delegate()
                {
                    try
                    {
                        var url  = BackendUrl + Path + "?s=" + CurrentSessionId;
                        var data = "";
                        foreach (var i in Parameters)
                        {
                            var p = i.Split(new[] { "=" }, StringSplitOptions.None);
                            if (p.Length == 2)
                            {
                                data += "&" + HttpUtility.UrlEncode(p[0]) + "=" + HttpUtility.UrlEncode(p[1]);
                            }
                        }
                        if (Method == "GET")
                        {
                            url += data;
                        }
                        var request             = (HttpWebRequest)HttpWebRequest.Create(url);
                        request.CookieContainer = new CookieContainer(3);
                        request.CookieContainer.Add(new Cookie("wcf_cookieHash", CurrentSessionId, "/", ".www.modapi.cc"));
                        request.CookieContainer.Add(new Cookie("wcf_userID", UserId + "", "/", ".www.modapi.cc"));
                        request.CookieContainer.Add(new Cookie("wcf_password", Hash, "/", ".www.modapi.cc"));
                        request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return(true); };
                        request.UserAgent = "ModAPI";
                        if (Method == "POST")
                        {
                            request.Method      = "POST";
                            request.ContentType = "application/x-www-form-urlencoded";
                            if (data.Length > 1)
                            {
                                var postData          = data.Substring(1);
                                var postBytes         = Encoding.UTF8.GetBytes(postData);
                                request.ContentLength = postBytes.Length;
                                var dataStream        = request.GetRequestStream();
                                dataStream.Write(postBytes, 0, postBytes.Length);
                                dataStream.Close();
                            }
                        }

                        var response       = (HttpWebResponse)request.GetResponse();
                        var responseStream = response.GetResponseStream();

                        var serializer = new DataContractJsonSerializer(ResponseType);
                        var obj        = (Response)serializer.ReadObject(responseStream);

                        if (obj.Header != null && obj.Header.SessionId != null)
                        {
                            CurrentSessionId = obj.Header.SessionId;
                            if (obj.Header.Status != null)
                            {
                                ResponseHandler.Invoke(obj);
                                RequestCompleted();
                                return;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                    ResponseHandler.Invoke(null);
                    RequestCompleted();
                });

                requestThread.Start();
            }
Exemplo n.º 24
0
 public void Response(ZpiObject zpiObject)
 {
     OnResponse?.Invoke(this, zpiObject);
 }
Exemplo n.º 25
0
        private void ProcessReceivingMessages()
        {
            Task.Run(async() =>
            {
                while (socket.State == WebSocketState.Open)
                {
                    ArraySegment <byte> buffer;
                    WebSocketReceiveResult result = null;
                    try
                    {
                        buffer = new ArraySegment <byte>(new byte[1024]);
                        result = await socket.ReceiveAsync(buffer, ReceiveTokenSource.Token);
                    }
                    catch (Exception ex)
                    {
                        socket      = null;
                        IsActive    = false;
                        IsConnected = false;
                        return;
                    }

                    if (result == null || result.Count == 0)
                    {
                        continue;
                    }

                    Kaenx.Konnect.Remote.MessageCodes code = (Konnect.Remote.MessageCodes)buffer.Array[0];

                    Debug.WriteLine("Got Remote Message: " + code);

                    //Check if assemby from this genügt
                    var q = from t in Assembly.LoadFrom("Kaenx.Konnect.dll").GetTypes()
                            where t.IsClass && t.IsNested == false && t.Namespace == "Kaenx.Konnect.Remote"
                            select t;

                    IRemoteMessage message = null;

                    foreach (Type t in q.ToList())
                    {
                        IRemoteMessage down = (IRemoteMessage)Activator.CreateInstance(t);
                        if (down != null && code == down.MessageCode)
                        {
                            message = down;
                            break;
                        }
                    }

                    if (message == null)
                    {
                        Debug.WriteLine("Unbekannte Nachricht: " + code);
                    }
                    try
                    {
                        message.Parse(buffer.Array.Take(result.Count).ToArray());
                    }
                    catch (Exception ex)
                    {
                    }

                    if (message is TunnelRequest && (message as TunnelRequest).Type == TunnelTypes.Connect)
                    {
                        TunnelRequest req = message as TunnelRequest;
                        KnxRemote rem     = new KnxRemote(Encoding.UTF8.GetString(req.Data), this);
                        await rem.Init(getUsbHandler);
                        int connId = await rem.ConnectToInterface(req);
                        Remotes.Add(connId, rem);
                        continue;
                    }


                    if (message.ToString().EndsWith("Response"))
                    {
                        Responses[message.SequenceNumber] = message;
                        OnResponse?.Invoke(message);
                    }
                    else
                    {
                        OnRequest?.Invoke(message);
                    }
                }

                Debug.WriteLine("Verbindung abgebrochen");
            });
        }
Exemplo n.º 26
0
 public void SetResponse(MnlMessage response)
 {
     Response = response;
     OnResponse?.Invoke(response);
 }
Exemplo n.º 27
0
 public void Handle(GetStatusResponse message)
 {
     OnResponse?.Invoke(message);
 }
Exemplo n.º 28
0
        internal void DataReception()
        {
            while (ListeningForData)
            {
                ReceivedData data;
                try {
                    data = ReceiveData();
                }
                catch (ObjectDisposedException) {
                    ListeningForData = false;
                    return;
                }
                catch (IOException e) {
                    if (e.InnerException is SocketException socketE)
                    {
                        if (socketE.SocketErrorCode == SocketError.Interrupted)
                        {
                            ListeningForData = false;
                            return;
                        }
                    }
                    continue;
                }

                if (!ListeningForData)
                {
                    return;
                }

                if (data.DataType == typeof(SocketException))
                {
                    ListeningForData = false;
                    return;
                }

                if (data.DataType == typeof(UndefinedPacketEventArgs))
                {
                    OnUndefinedPacketReceived?.Invoke(this, new UndefinedPacketEventArgs(infoAboutOtherSide.ID, data.DataID, (byte[])data.ReceivedObject));
                }

                #region Primitives

                if (data.DataID == 0)
                {
                    if (OnStringReceived == null)
                    {
                        throw new NullReferenceException("Received a string packet, but the OnStringReceived event is not consumed!");
                    }
                    OnStringReceived(this, new PacketReceivedEventArgs <string>((string)data.ReceivedObject, data.SenderID));
                }
                else if (data.DataID == 1)
                {
                    if (OnInt64Received == null)
                    {
                        throw new NullReferenceException("Received an Int64(long) packet, but the OnInt64Received event is not consumed!");
                    }
                    OnInt64Received(this, new PacketReceivedEventArgs <Int64>((Int64)data.ReceivedObject, data.SenderID));
                }

                #endregion

                if (dataIDs.customIDs.ContainsKey(data.DataID))
                {
                    dataIDs.customIDs[data.DataID].ActionCallback.Invoke(data.SenderID, data.ReceivedObject);
                    continue;
                }

                if (data.DataID == DataIDs.RESPONSE_RECEPTION_ID)
                {
                    OnResponse?.Invoke(this, (TCPResponse)data.ReceivedObject);
                }
                else if (data.DataID != DataIDs.REQUEST_RECEPTION_ID)
                {
                    HigherLevelDataReceived(data);
                }
            }
        }
Exemplo n.º 29
0
 private void CancelButton_OnButtonClick(UIElement button)
 {
     OnResponse?.Invoke(false);
 }
Exemplo n.º 30
0
        public void Response()
        {
            while (true)
            {
                try
                {
                    byte[] receivebuffer = new byte[this.buffersize];
                    //this..Receive(receivebuffer, 0, receivebuffer.Length, 0);
                    //string response = Encoding.ASCII.GetString(receivebuffer);

                    StringBuilder messageData = new StringBuilder();
                    int           bytes       = -1;
                    do
                    {
                        bytes = sslStream.Read(receivebuffer, 0, receivebuffer.Length);
                        Decoder decoder     = Encoding.UTF8.GetDecoder();
                        char[]  messagepart = new char[decoder.GetCharCount(receivebuffer, 0, bytes)];
                        decoder.GetChars(receivebuffer, 0, bytes, messagepart, 0);
                        messageData.Append(messagepart);
                        if (messageData.ToString().IndexOf("<EOF>") != -1)
                        {
                            break;
                        }
                    } while (bytes != 0);

                    string response = messageData.ToString();
                    response = response.Substring(0, response.Length - 5);



                    Console.WriteLine(response);
                    JObject obj = JObject.Parse(response);
                    if (obj["action"] == null)
                    {
                        /*
                         *  Error shit
                         *  To do:
                         *  Write a file with the logs
                         *  Creating the MedicalProblems object
                         *
                         *
                         */
                        Console.WriteLine("No action has been sent!");

                        return;
                    }
                    string action = (string)obj["action"];
                    switch (action)
                    {
                    case "response":
                        MedicalProblems problem = new MedicalProblems();
                        Console.WriteLine("yes");
                        Console.WriteLine(obj["rezultat"][0][0].GetType());
                        Console.WriteLine(obj["rezultat"][1][1]);
                        problem.Chanse_To_Have         = obj["rezultat"][0][0].ToObject <double>();
                        problem.Chanse_To_Have_Nothing = obj["rezultat"][1][1].ToObject <double>();

                        //Console.WriteLine("Problem with invoke shit");
                        OnResponse?.Invoke(this, new OnReceiveMessageClientEventArgs {
                            Medical = problem
                        });

                        break;

                    case "regresponse":
                        Console.WriteLine("Receiving register response");
                        OnRegisterResponse?.Invoke(this, new OnReceiveRegisterMessageArgs {
                            errorcode = (int)obj["errorcode"], errormessage = (string)obj["errormessage"]
                        });

                        break;

                    case "loginresponse":
                        //Console.WriteLine("Receiving login response");
                        Console.WriteLine("Code..... \n");
                        string errorcodeestring = (string)obj["error"];
                        Console.WriteLine(errorcodeestring);
                        int errorcodee = Int32.Parse(errorcodeestring);
                        Console.WriteLine("Cod de eroare: " + errorcodee);

                        if (errorcodee == 0)
                        {
                            this.Cookie  = (string)obj["cookie"];
                            this.isloged = true;
                        }

                        OnLoginResponse?.Invoke(this, new OnReceiveLoginMessageArgs {
                            errorcode = errorcodee, errormessage = (string)obj["errormessage"], username = (string)obj["username"]
                        });

                        break;

                    case "code_verify_response":
                        Console.WriteLine("Receiving code_verify response");
                        OnCodeVerifyResponse?.Invoke(this, new OnCodeVerifyResponseArgs {
                            errorcode = (int)obj["errorcode"], errormessage = (string)obj["errormessage"]
                        });


                        break;


                    case "results":
                        int errorcode = (int)obj["error"];

                        if (errorcode == 0)
                        {
                            OnReceiveResultArgs args = JsonConvert.DeserializeObject <OnReceiveResultArgs>(response);

                            OnReceiveResults?.Invoke(this, args);
                        }
                        else
                        {
                        }



                        break;

                    default:
                        /*
                         * Some error comming from server
                         * or maybe from client?
                         * IDK
                         *
                         * */
                        break;
                    }
                }
                catch (Exception ex)
                {
                    OnConnectionLost?.Invoke(this, EventArgs.Empty);
                    Console.WriteLine("Wrong format " + ex.Message);
                    this.isloged = false;
                    break;
                }
            }
        }