public bool SendGetLimits(OnResponse response, string account, string product = "", string segment = "", string exchange = "") { if (loginResp == null) { return(false); } Limits limits = new Limits(); limits.actid = account; limits.uid = loginReq.uid; if (product != "") { limits.prd = product; } if (segment != "") { limits.seg = segment; } if (exchange != "") { limits.exch = exchange; } string uri = "Limits"; rClient.makeRequest(new NorenApiResponse <LimitsResponse>(response), uri, limits.toJson(), getJKey); return(true); }
/*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); } }
private void HandleResponseMessage(string message) { if (OnResponse != null) { OnResponse.Invoke(message); } }
// Set the Callback of the User. public Waiter SetOnResponse(OnResponse onResponse) { this.onResponse = onResponse; // Lets update our status with the manager. WaiterManager.Update(this); return(this); }
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); }
public void PacketReceived(byte[] payload, string packetType) { switch (packetType) { case "kubres": //Correct endianness for payload bytes ushort resId = BitConverter.ToUInt16(payload, 0); uint value = BitConverter.ToUInt32(new byte[4] { payload[5], payload[4], payload[3], payload[2] }, 0); if (!this.requests.ContainsKey(resId)) { return; } OnResponse callback = this.requests[resId]; if (callback == null) { return; } callback(value); break; default: break; } }
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) { } } }
public bool SendGetTPSeries(OnResponse response, string exch, string token, string starttime = null, string endtime = null, string interval = null) { if (loginResp == null) { return(false); } string uri = "TPSeries"; TPSeries quote = new TPSeries(); quote.uid = loginReq.uid; quote.exch = exch; quote.token = token; if (String.IsNullOrEmpty(starttime) != true) { quote.st = starttime; } if (String.IsNullOrEmpty(endtime) != true) { quote.et = endtime; } if (String.IsNullOrEmpty(interval) != true) { quote.intrv = endtime; } rClient.makeRequest(new NorenApiResponseList <GetTPSeriesResponse, TPSeriesItem>(response), uri, quote.toJson(), getJKey); return(true); }
public void Response(string response) { OnResponse.Invoke(new HttpRerquestEventArgs { Response = response }); }
private void OnMouseEvent(UIMouseEventType type, UpdateState state) { if (type == UIMouseEventType.MouseDown) { OnResponse?.Invoke(true); } }
public virtual object Complete(ProtoState state) { var res = state.Complete(); OnResponse?.Invoke(this, state); AllDone.Reset(); return(res); }
public MockVMController(IVMFactory vmFactory) : this() { _vmController = new VMController((connectionId, vmId, vmData) => { _response.Handler(connectionId, vmId, vmData); OnResponse?.Invoke(this, vmData); }, vmFactory); }
/// <summary> /// 删除协议监听 /// </summary> public void RemoveNetMsgEventListener(int msgId, OnResponse callback) { if (mResponseListDict.ContainsKey(msgId)) { var responseList = mResponseListDict[msgId]; responseList.Remove(callback); } }
// 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()); } }
// IEnumerator ReportEnterScene() // { // string phoneId = SystemInfo.deviceUniqueIdentifier; // string phoneType = SystemInfo.deviceModel; // string androidVersion = SystemInfo.operatingSystem; // int sceneNumber = 0; // int appVersion = 1; // int random = UnityEngine.Random.Range(int.MinValue, int.MaxValue); // string url = HOST + "/index.php/PatchRecord/login?"; // string param = "phone_id=" + Uri.EscapeDataString(phoneId) // + "&phone_type=" + Uri.EscapeDataString(phoneType) // + "&android_version=" + Uri.EscapeDataString(androidVersion) // + "&enter_scene=" + sceneNumber // + "&app_version=" + appVersion // + "&rand=" + random; // string req = url + param; // UnityWebRequest www = UnityWebRequest.Get(req); // yield return www.SendWebRequest(); // if (www.isNetworkError || www.isHttpError) // { // Debug.Log(www.error); // } // else // { // Debug.Log(www.downloadHandler.text); // } // //GetSupportedStat((rsp) => { if (rsp != null) { Debug.Log(JsonConvert.SerializeObject(rsp)); } }); // } public static void GetSupportedStat(OnResponse onRsp) { if (instance == null) { Debug.LogError("SupportPhoneStat instance = null"); onRsp(null); return; } // instance.StartCoroutine(FetchSupportedStat(onRsp)); }
internal Task SetReponseAsync(OicMessage message) { lock (_reponseLock) _response = message; _responseTcs.TrySetResult(true); return(Task.Run(() => OnResponse?.Invoke(this, new OicRequestResponseEventArgs { Message = message }))); }
/// <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(); }
public static void AddRequest(uint seq, OnResponse <Message> handler) { if (handler != null) { lock (handlers_mutex_) { handlers.Add(seq, handler); } } }
public void Send(OnResponse responseHandler) { if (responseHandler == null) { return; } ResponseHandler = responseHandler; RequestChain.Add(this); ExecuteChain(); }
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); }
public bool SendGetBasketMargin(OnResponse response, BasketMargin basket) { if (loginResp == null) { return(false); } string uri = "GetBasketMargin"; rClient.makeRequest(new NorenApiResponse <GetBasketMarginResponse>(response), uri, basket.toJson(), getJKey); return(true); }
public bool SendPlaceOrder(OnResponse response, PlaceOrder order) { if (loginResp == null) { return(false); } string uri = "PlaceOrder"; rClient.makeRequest(new NorenApiResponse <PlaceOrderResponse>(response), uri, order.toJson(), getJKey); return(true); }
public void RequestData(DataType type, OnResponse callback) { short reqId = nextRequestId++; byte[] idPayload = BitConverter.GetBytes(reqId); byte[] reqPayload = new byte[8] { 1, 0, 0, 0, 3, (byte)type, idPayload[0], idPayload[1] }; this.requests.Add(reqId, callback); mqttClient.Publish("kub/" + this.id + "/kubreq", reqPayload); }
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); }
public void LogOut(OnResponse <LoginResponseInfo> onLogOut) { DoRequest(LogOutUrl(), delegate(LoginResponseInfo loginResponseInfo) { IsAuthenticated = (loginResponseInfo.IsAuthenticated.Value); if (onLogOut != null) { onLogOut(loginResponseInfo); } }); }
public void LogIn(string username, string securityCode, OnResponse <LoginResponseInfo> onLogIn) { DoRequest(LoginUrl(username, securityCode), delegate(LoginResponseInfo loginResponse) { IsAuthenticated = (loginResponse.IsAuthenticated.Value); if (onLogIn != null) { onLogIn(loginResponse); } }); }
internal bool FireResponse(IncomingResponse response) { lock (Sync) { if (Responded) { return(false); } OnResponse?.Invoke(response); return(Responded = true); } }
public bool SendGetExchMsg(OnResponse response, ExchMsg exchmsg) { if (loginResp == null) { return(false); } string uri = "ExchMsg"; rClient.makeRequest(new NorenApiResponseList <ExchMsgResponse, ExchMsgItem>(response), uri, exchmsg.toJson(), getJKey); return(true); }
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); } } }
public bool SendModifyOrder(OnResponse response, ModifyOrder order) { if (loginResp == null) { return(false); } order.uid = loginReq.uid; string uri = "ModifyOrder"; rClient.makeRequest(new NorenApiResponse <ModifyOrderResponse>(response), uri, order.toJson(), getJKey); return(true); }
/// <summary> /// Read an object via websockets. /// </summary> /// <param name="obj">The object type (flow, track, or drop)</param> /// <param name="ids">The array of ids</param> /// <param name="callback">A callback to be called when a response is received</param> public void Read(string obj, string[] ids, OnResponse callback = null) { if (obj == "drop" || obj == "flow" || obj == "track") this.Send("find", obj, new JProperty[] { new JProperty("id", JArray.FromObject(ids)) }, callback); else throw new FlowThingsNotImplementedException(); }
/// <summary> /// Unsubscribe from websocket updates from the resource. /// </summary> /// <param name="resourceId">The resource ID</param> /// <param name="callback">A callback to call when subscribed, or null</param> public void Unsubscribe(string resourceId, OnResponse callback = null) { this.Send("unsubscribe", "drop", new JProperty[] { new JProperty("flowId", resourceId) }, callback); }
bool WaitForRecvEvent(int a_contextID, ref int a_timeoutMs, OnResponse a_callback) { Message resMsg; IPEndPoint sender; do { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Socket sock; bool isTimeout = ! m_poller.WaitForMessage(a_timeoutMs, out resMsg, out sock, out sender); if (isTimeout) return false; IPEndPoint publicAddress = null; if (resMsg.AddressIsEmpty() == false) { publicAddress = new IPEndPoint(IPAddress.Parse(resMsg.m_address), resMsg.m_port); } bool valid = resMsg.m_contextID == a_contextID; if (valid) { Response res; res.m_socket = sock; res.m_sender = sender; res.m_publicAddress = publicAddress; res.m_contextID = resMsg.m_contextID; res.m_contextSeq = resMsg.m_contextSeq; res.m_senderType = resMsg.m_senderType; valid = a_callback(res); } if (valid == false) { a_timeoutMs -= (int)stopwatch.ElapsedMilliseconds; if (a_timeoutMs < 0) a_timeoutMs = 0; continue; } break; } while (true); return true; }
/// <summary> /// Create a new object via websockets. /// </summary> /// <param name="obj">The object type (flow, track) -- for drops use CreateDrop</param> /// <param name="value">The value object</param> /// <param name="callback">A callback to be called when a response is received</param> public void Create(string obj, dynamic value, OnResponse callback = null) { if (obj == "flow" || obj == "track") this.Send("create", obj, new JProperty[] { new JProperty("value", JToken.FromObject(value)) }, callback); else if (obj == "drop") throw new ArgumentException("Drops require a flowId, use the CreateDrop function instead"); else throw new FlowThingsNotImplementedException(); }
/// <summary> /// Create a new object via websockets. /// </summary> /// <param name="flowId">The ID of the flow to create the drop in</param> /// <param name="value">The value object</param> /// <param name="callback">A callback to be called when a response is received</param> public void CreateDrop(string flowId, dynamic value, OnResponse callback = null) { JObject jo = new JObject( new JProperty("elems", JToken.FromObject(value))); this.Send("create", "drop", new JProperty[] { new JProperty("flowId", flowId), new JProperty("value", jo) }, callback); }
public void Send(OnResponse responseHandler) { if (responseHandler == null) return; ResponseHandler = responseHandler; Request.RequestChain.Add(this); ExecuteChain(); }
/// <summary> /// Update an object via websockets. /// </summary> /// <param name="obj">The object type (flow, track, or drop)</param> /// <param name="value">The value object</param> /// <param name="callback">A callback to be called when a response is received</param> public void Update(string obj, dynamic value, OnResponse callback = null) { if (obj == "drop" || obj == "flow" || obj == "track") this.Send("update", obj, new JProperty[] { new JProperty("value", JToken.FromObject(value)) }, callback); else throw new FlowThingsNotImplementedException(); }
/// <summary> /// Send a message to the WS server. /// </summary> /// <param name="type">The type field, (create, update, delete, find)</param> /// <param name="obj">The object field (flow, drop, track)</param> /// <param name="props">Properties to be added to the message to be sent to the server</param> /// <param name="callback">A callback called when a response is received</param> protected void Send(string type, string obj, JProperty[] props, OnResponse callback = null) { if (this.ws == null || !this.connected) throw new FlowThingsNotConnectedException(); JObject data = new JObject( new JProperty("type", type), new JProperty("object", obj)); foreach (JProperty prop in props) data.Add(prop); if (callback != null) { lock (_syncRID) { int rid = this.replyId; data["id"] = rid; this.replyCallbacks[rid] = callback; this.replyId++; } } ws.Send(data.ToString()); }