private CloudMessage InvokeRawRequest(CloudMessage requestMessage) { try { object content; // TODO: Refactor this and build converter for JSON to WirehomeDictionary and WirehomeList if (!(PythonConvert.ToPython(requestMessage.Content) is PythonDictionary parameters)) { content = new WirehomeDictionary().WithType(ControlType.ParameterInvalidException); } else { if (!_messageHandlers.TryGetValue(parameters.GetValueOr("type", string.Empty), out var messageHandler)) { content = new WirehomeDictionary().WithType(ControlType.NotSupportedException); } else { content = messageHandler.Invoke(parameters); } } return(_messageFactory.CreateResponseMessage(requestMessage, content)); }
internal void setNewCloud(CloudMessage cloud) { //if (!_clouds.ContainsKey (cloud.KinectId)) { // Vector3 position = new Vector3 (Mathf.Ceil (_clouds.Count / 2.0f) * (_clouds.Count % 2 == 0 ? -1.0f : 1.0f), 1, 0); // //criar nova cloud // _clouds[cloud.KinectId] = new PointCloudSimple (); //} int step = cloud.headerSize + 3; // TMA: Size in bytes of heading: "CloudMessage" + L0 + 2 * L1. Check the UDPListener.cs from the Client. string[] pdu = cloud.message.Split(MessageSeparators.L1); string KinectId = pdu[0]; uint id = uint.Parse(pdu[1]); step += pdu[0].Length + pdu[1].Length; if (_clouds.ContainsKey(KinectId)) { if (pdu[2] == "") { _clouds[KinectId].setToView(); } else { _clouds[KinectId].setPoints(cloud.receivedBytes, step, id, cloud.receivedBytes.Length); } } }
private async Task TryProcessCloudMessageAsync(CloudMessage message, CancellationToken cancellationToken) { try { CloudMessage response; if (message.Type == CloudMessageType.Ping) { response = InvokePingRequest(message); } else if (message.Type == CloudMessageType.HttpInvoke) { response = await InvokeHttpRequestAsync(message, cancellationToken).ConfigureAwait(false); } else if (message.Type == CloudMessageType.Raw) { response = InvokeRawRequest(message); } else { response = _messageFactory.CreateMessage(ControlType.NotSupportedException, null); } await SendMessageAsync(response, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { } catch (Exception exception) { _logger.LogError(exception, "Error while processing cloud message."); } }
public static void Delete(CloudMessage command, List <string> messages) { messages.Add(Delete(command.UserGames)); messages.Add(Delete(command.UserDevices)); messages.Add(Delete(command.UserComputers)); messages.Add(Delete(command.UserInstances)); }
public void PeekMessageAsync() { // Arrange var queueName = "myqueue"; var mockQueue = GetMockQueue(queueName); var mockQueueClient = GetMockQueueClient(mockQueue); var mockBlobContainer = GetMockBlobContainer(); var mockBlobClient = GetMockBlobClient(mockBlobContainer); var storageAccount = GetMockStorageAccount(mockBlobClient, mockQueueClient); var cloudMessage = new CloudQueueMessage("Hello world"); var message = new CloudMessage("Hello world"); mockQueue .Setup(c => c.PeekMessageAsync(It.IsAny <QueueRequestOptions>(), It.IsAny <OperationContext>(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult(cloudMessage)) .Verifiable(); // Act var queueManager = new QueueManager(queueName, storageAccount.Object); var result = queueManager.PeekMessageAsync().Result; // Assert mockQueue.Verify(); mockQueueClient.Verify(); mockBlobContainer.Verify(); mockBlobClient.Verify(); result.Content.GetType().ShouldBe(message.Content.GetType()); result.Content.ShouldBe(message.Content); }
public async Task SendAsync(CloudMessage cloudMessage, CancellationToken cancellationToken) { if (cloudMessage == null) { throw new ArgumentNullException(nameof(cloudMessage)); } try { var transportCloudMessage = CreateTransportCloudMessage(cloudMessage); var sendBuffer = _cloudMessageSerializer.Pack(transportCloudMessage); await _lock.EnterAsync(cancellationToken).ConfigureAwait(false); try { await _webSocket.SendAsync(sendBuffer, WebSocketMessageType.Binary, true, cancellationToken).ConfigureAwait(false); Interlocked.Add(ref _bytesSent, sendBuffer.Count); Interlocked.Increment(ref _messagesSent); _lastMessageSent = DateTime.UtcNow; } finally { _lock.Exit(); } } catch { Interlocked.Increment(ref _sendErrors); throw; } }
private async Task TryProcessCloudMessageAsync(CloudMessage requestMessage, CancellationToken cancellationToken) { try { CloudMessage responseMessage = null; if (requestMessage.Type == CloudMessageType.Ping) { responseMessage = new CloudMessage(); } else if (requestMessage.Type == CloudMessageType.HttpInvoke) { responseMessage = await InvokeHttpRequestAsync(requestMessage, cancellationToken).ConfigureAwait(false); } else if (requestMessage.Type == CloudMessageType.Raw) { responseMessage = InvokeRawRequest(requestMessage); } if (responseMessage != null) { responseMessage.CorrelationId = requestMessage.CorrelationId; await SendMessageAsync(responseMessage, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) { } catch (Exception exception) { _logger.LogError(exception, "Error while processing cloud message."); } }
public void Add <T>(CloudAction action, T[] items, Guid[] checksums = null) { var o = SettingsManager.Options; var allow = o.InternetAutoSave; if (!allow) { return; } var message = new CloudMessage(action); // Try to assign list. message.Checksums = checksums; message.UserGames = items as UserGame[]; message.UserSettings = items as UserSetting[]; message.UserDevices = items as UserDevice[]; message.UserComputers = items as UserComputer[]; message.UserInstances = items as UserInstance[]; message.MailMessages = items as MailMessageSerializable[]; var item = new CloudItem() { Date = DateTime.Now, Message = message, State = CloudState.None, }; TasksTimer.DoActionNow(item); }
private CloudMessage InvokeRawRequest(CloudMessage requestMessage) { try { var jsonRequestPayload = Encoding.UTF8.GetString(requestMessage.Payload); var jsonRequest = JObject.Parse(jsonRequestPayload); var pythonDictionary = PythonConvert.ToPythonDictionary(jsonRequest); CloudMessageHandler cloudMessageHandler; lock (_rawMessageHandlers) { if (!_rawMessageHandlers.TryGetValue(pythonDictionary.GetValueOr("type", string.Empty), out cloudMessageHandler)) { throw new NotSupportedException("RAW message type handler not supported."); } } var responseContent = cloudMessageHandler.Invoke(pythonDictionary); var jsonResponse = PythonConvert.FromPythonToJson(responseContent); return(new CloudMessage() { CorrelationId = requestMessage.CorrelationId, Payload = Encoding.UTF8.GetBytes(jsonResponse.ToString()) }); } catch (Exception exception) { return(_cloudMessageFactory.Create(exception)); } }
public async Task SendMessageAsync(CloudMessage message, CancellationToken cancellationToken) { if (message == null) { throw new ArgumentNullException(nameof(message)); } using (var messageBuffer = new MemoryStream()) using (var streamWriter = new StreamWriter(messageBuffer)) { _serializer.Serialize(streamWriter, message); streamWriter.Flush(); messageBuffer.Position = 0; var compressedBuffer = Compress(messageBuffer); await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); try { var sendBuffer = new ArraySegment <byte>(compressedBuffer.GetBuffer(), 0, (int)compressedBuffer.Length); await _webSocket.SendAsync(sendBuffer, WebSocketMessageType.Binary, true, cancellationToken).ConfigureAwait(false); } finally { _semaphore.Release(); } } }
private CloudMessage InvokeRawRequest(CloudMessage requestMessage) { try { WirehomeDictionary responseContent; var requestContent = requestMessage.GetContent <JToken>(); // TODO: Refactor this and build converter for JSON to WirehomeDictionary and WirehomeList if (!(PythonConvert.ToPython(requestContent) is PythonDictionary parameters)) { responseContent = new WirehomeDictionary().WithType(ControlType.ParameterInvalidException); } else { if (!_messageHandlers.TryGetValue(parameters.GetValueOr("type", string.Empty), out var messageHandler)) { responseContent = new WirehomeDictionary().WithType(ControlType.NotSupportedException); } else { responseContent = messageHandler.Invoke(parameters); } } var responseMessage = new CloudMessage(); responseMessage.SetContent(responseContent); return(responseMessage); }
public void DeleteMessageAsync() { // Arrange var queueName = "myqueue"; var mockQueue = GetMockQueue(queueName); var mockQueueClient = GetMockQueueClient(mockQueue); var mockBlobContainer = GetMockBlobContainer(); var mockBlobClient = GetMockBlobClient(mockBlobContainer); var storageAccount = GetMockStorageAccount(mockBlobClient, mockQueueClient); var message = new CloudMessage("Hello world"); mockQueue .Setup(c => c.DeleteMessageAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <QueueRequestOptions>(), It.IsAny <OperationContext>(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult(true)) .Verifiable(); // Act var queueManager = new QueueManager(queueName, storageAccount.Object); queueManager.DeleteMessageAsync(message).Wait(); // Assert mockQueue.Verify(); mockQueueClient.Verify(); mockBlobContainer.Verify(); mockBlobClient.Verify(); }
public void UpdateMessageVisibilityTimeoutAsync() { // Arrange var queueName = "myqueue"; var mockQueue = GetMockQueue(queueName); var mockQueueClient = GetMockQueueClient(mockQueue); var mockBlobContainer = GetMockBlobContainer(); var mockBlobClient = GetMockBlobClient(mockBlobContainer); var storageAccount = GetMockStorageAccount(mockBlobClient, mockQueueClient); var permissions = new QueuePermissions(); var message = new CloudMessage("Hello world"); var visibilityTimeout = TimeSpan.FromSeconds(2); mockQueue .Setup(c => c.UpdateMessageAsync(It.IsAny <CloudQueueMessage>(), It.IsAny <TimeSpan>(), MessageUpdateFields.Visibility, It.IsAny <QueueRequestOptions>(), It.IsAny <OperationContext>(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult(true)) .Verifiable(); // Act var queueManager = new QueueManager(queueName, storageAccount.Object); queueManager.UpdateMessageVisibilityTimeoutAsync(message, visibilityTimeout).Wait(); // Assert mockQueue.Verify(); mockQueueClient.Verify(); mockBlobContainer.Verify(); mockBlobClient.Verify(); }
public static void Upsert(CloudMessage command, List <string> messages) { // Games can be inserted by using computer id only. messages.Add(Upsert(command.UserGames)); messages.Add(Upsert(command.UserDevices)); messages.Add(Upsert(command.UserComputers)); messages.Add(Upsert(command.UserInstances)); }
/// <summary>Execute INSERT/UPDATE commands on database.</summary> public static void Upsert(CloudMessage command, List <string> messages) { messages.Add(Upsert(command.UserGames)); messages.Add(Upsert(command.UserDevices)); messages.Add(Upsert(command.UserInstances)); // UPSERT settings last, because it depends on other records. messages.Add(Upsert(command.UserSettings)); }
private CloudMessage InvokePingRequest(CloudMessage message) { return(_messageFactory.CreateResponseMessage(message, new PongCloudMessageContent { Timestamp = DateTime.Now.ToString("O"), Message = "pong", Version = WirehomeCoreVersion.Version })); }
public Task SendMessageAsync(CloudMessage message, CancellationToken cancellationToken) { if (message == null) { throw new ArgumentNullException(nameof(message)); } return(_channel.SendMessageAsync(message, cancellationToken)); }
/// <summary>Execute DELETE commands on database.</summary> public static void Delete(CloudMessage command, List <string> messages) { // Delete user settings first, because it links to other records. messages.Add(Delete(command.UserSettings)); // Delete user instances because it links to used devices. messages.Add(Delete(command.UserInstances)); // Delete other records. messages.Add(Delete(command.UserGames)); messages.Add(Delete(command.UserDevices)); }
public void broadCastCloudRequests(bool continuous) { UdpClient udp = new UdpClient(); string message = CloudMessage.createRequestMessage(continuous ? 1 : 0, Network.player.ipAddress, TrackerProperties.Instance.listenPort); byte[] data = Encoding.UTF8.GetBytes(message); IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Broadcast, TrackerProperties.Instance.listenPort + 1); udp.Send(data, data.Length, remoteEndPoint); }
public void broadCastCloudRequests(bool continuous) { UdpClient udp = new UdpClient(); string message = CloudMessage.createRequestMessage(continuous ? 1 : 0, Network.player.ipAddress, int.Parse(_properties.localSetupInfo.ravatarListenPort)); byte[] data = Encoding.UTF8.GetBytes(message); IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(_properties.remoteSetupInfo.machineAddress), int.Parse(_properties.remoteSetupInfo.trackerListenPort)); // +1 udp.Send(data, data.Length, remoteEndPoint); }
public async Task DeleteMessageAsync(CloudMessage message, QueueRequestOptions options = null, OperationContext operationContext = null, CancellationToken cancellationToken = default(CancellationToken)) { if (message.IsLargeMessage) { var blob = _blobContainer.GetBlobReference(message.LargeContentBlobName); await blob.DeleteAsync(DeleteSnapshotsOption.IncludeSnapshots, null, null, null, cancellationToken); } await _queue.DeleteMessageAsync(message.Id, message.PopReceipt, options, operationContext, cancellationToken); }
private void AddRsaPublicKey(CloudMessage results) { var rsa = new JocysCom.ClassLibrary.Security.Encryption(CloudKey.Cloud); if (string.IsNullOrEmpty(rsa.RsaPublicKeyValue)) { rsa.RsaNewKeysSave(2048); } results.Values.Add(CloudKey.RsaPublicKey, rsa.RsaPublicKeyValue); }
Task SendMessageAsync(CloudMessage message, CancellationToken cancellationToken) { var channel = _channel; if (channel == null) { return(Task.CompletedTask); } return(_channel.SendAsync(message, cancellationToken)); }
public Task GetPing() { var request = new CloudMessage { Type = CloudMessageType.Ping }; var deviceSessionIdentifier = HttpContext.GetDeviceSessionIdentifier(); return(_deviceConnectorService.Invoke(deviceSessionIdentifier, request, HttpContext.RequestAborted)); }
/// <summary> /// Submit changed data to the cloud. /// </summary> Exception Execute <T>(CloudAction action) { var ws = new WebServiceClient(); ws.Url = SettingsManager.Options.InternetDatabaseUrl; CloudMessage result = null; try { var citems = data.Where(x => x.Action == action); var items = citems.Select(x => x.Item).OfType <T>().ToList(); if (items.Count > 0) { // Add security. var o = SettingsManager.Options; var command = CloudHelper.NewMessage(action, o.UserRsaPublicKey, o.CloudRsaPublicKey, o.Username, o.Password); command.Values.Add(CloudKey.HashedDiskId, o.HashedDiskId, true); //// Add secure credentials. //var rsa = new JocysCom.ClassLibrary.Security.Encryption("Cloud"); //if (string.IsNullOrEmpty(rsa.RsaPublicKeyValue)) //{ // var username = rsa.RsaEncrypt("username"); // var password = rsa.RsaEncrypt("password"); // ws.SetCredentials(username, password); //} // Add changes. if (typeof(T) == typeof(UserGame)) { command.UserGames = items as List <UserGame>; } else if (typeof(T) == typeof(UserDevice)) { command.UserControllers = items as List <UserDevice>; } result = ws.Execute(command); if (result.ErrorCode > 0) { queueTimer.ChangeSleepInterval(5 * 60 * 1000); return(new Exception(result.ErrorMessage)); } foreach (var item in citems) { data.Remove(item); } } } catch (Exception ex) { // Sleep for 5 minutes; queueTimer.ChangeSleepInterval(5 * 60 * 1000); return(ex); } return(null); }
public async Task GetPing() { var request = new CloudMessage { Type = CloudMessageType.Ping }; var deviceSessionIdentifier = await _authorizationService.GetChannelIdentifier(HttpContext).ConfigureAwait(false); await _deviceConnectorService.Invoke(deviceSessionIdentifier, request, HttpContext.RequestAborted).ConfigureAwait(false); }
public void ProcessUpdateResults(CloudMessage results) { lock (UpdateFormLock) { if (_UpdateWindow == null) { return; } _UpdateWindow.Step2ProcessUpdateResults(results); } }
public async Task <object> GetPing() { var request = new CloudMessage { Type = CloudMessageType.Ping }; var deviceSessionIdentifier = HttpContext.GetDeviceSessionIdentifier(); var response = await _deviceConnectorService.Invoke(deviceSessionIdentifier, request, HttpContext.RequestAborted).ConfigureAwait(false); return(response.Content); }
private async Task <CloudMessage> ConvertToPictonMessage(CloudQueueMessage cloudMessage, CancellationToken cancellationToken) { // We get a null value when the queue is empty if (cloudMessage == null) { return(null); } // Deserialize the content of the cloud message var content = (object)null; try { content = Deserialize(cloudMessage.AsBytes); } catch { content = cloudMessage.AsString; } // If the serialized content exceeded the max Azure Storage size limit, it was saved in a blob var largeContentBlobName = (string)null; if (content.GetType() == typeof(LargeMessageEnvelope)) { var envelope = (LargeMessageEnvelope)content; var blob = _blobContainer.GetBlobReference(envelope.BlobName); byte[] buffer; using (var ms = new MemoryStream()) { await blob.DownloadToStreamAsync(ms, null, null, null, cancellationToken).ConfigureAwait(false); buffer = ms.ToArray(); } content = Deserialize(buffer); largeContentBlobName = envelope.BlobName; } var message = new CloudMessage(content) { DequeueCount = cloudMessage.DequeueCount, ExpirationTime = cloudMessage.ExpirationTime, Id = cloudMessage.Id, InsertionTime = cloudMessage.InsertionTime, LargeContentBlobName = largeContentBlobName, NextVisibleTime = cloudMessage.NextVisibleTime, PopReceipt = cloudMessage.PopReceipt }; return(message); }
public static void Select(CloudMessage command, CloudMessage results, List <string> messages, out string error) { var computerId = CloudHelper.GetComputerId(command, out error).Value; // Get all user games. if (command.UserGames != null) { UserGame[] userGames; error = Select(computerId, command.UserGames, out userGames); messages.Add(error); results.UserGames = FilterByChecksum(userGames, command.Checksums, out error); if (!string.IsNullOrEmpty(error)) { messages.Add(error); } } // Get all user devices. if (command.UserDevices != null) { UserDevice[] userDevices; error = Select(computerId, command.UserDevices, out userDevices); messages.Add(error); results.UserDevices = FilterByChecksum(userDevices, command.Checksums, out error); if (!string.IsNullOrEmpty(error)) { messages.Add(error); } } // Get all user computers. if (command.UserComputers != null) { UserComputer[] userComputers; error = Select(computerId, command.UserComputers, out userComputers); messages.Add(error); results.UserComputers = FilterByChecksum(userComputers, command.Checksums, out error); if (!string.IsNullOrEmpty(error)) { messages.Add(error); } } // Get all user instances. if (command.UserInstances != null) { UserInstance[] userInstances; error = Select(computerId, command.UserInstances, out userInstances); messages.Add(error); results.UserInstances = FilterByChecksum(userInstances, command.Checksums, out error); if (!string.IsNullOrEmpty(error)) { messages.Add(error); } } }
internal void updateCloud(CloudMessage cl) { lastCloud.setPoints (cl.Points_highres, cl.Points_lowres, cl.id); lastCloud.setToView (); }
void Update() { while (_stringsToParse.Count > 0) { try { byte[] toProcess = _stringsToParse.First(); if(toProcess != null) { // TMA: THe first char distinguishes between a BodyMessage and a CloudMessage if (Convert.ToChar(toProcess[0]) == 'B') { try { string stringToParse = Encoding.ASCII.GetString(toProcess); string[] splitmsg = stringToParse.Split(MessageSeparators.L0); BodiesMessage b = new BodiesMessage(splitmsg[1]); gameObject.GetComponent<Tracker>().setNewFrame(b); } catch (BodiesMessageException e) { Debug.Log(e.Message); } } else if(Convert.ToChar(toProcess[0]) == 'C') { string stringToParse = Encoding.ASCII.GetString(toProcess); string[] splitmsg = stringToParse.Split(MessageSeparators.L0); CloudMessage c = new CloudMessage(splitmsg[1], toProcess); gameObject.GetComponent<Tracker>().setNewCloud(c); } } _stringsToParse.RemoveAt(0); } catch (Exception exc) { _stringsToParse.RemoveAt(0); } } }
internal void setNewCloud(CloudMessage cloud) { if (!Sensors.ContainsKey (cloud.KinectId)) { Vector3 position = new Vector3 (Mathf.Ceil (Sensors.Count / 2.0f) * (Sensors.Count % 2 == 0 ? -1.0f : 1.0f), 1, 0); Sensors [cloud.KinectId] = new Sensor (cloud.KinectId, (GameObject)Instantiate (Resources.Load ("Prefabs/KinectSensorPrefab"), position, Quaternion.identity)); } Sensors[cloud.KinectId].updateCloud (cloud); }