コード例 #1
0
ファイル: Program.cs プロジェクト: i-johnxz/GrpcDemo
        static async Task Main(string[] args)
        {
            //We need this switch because we are connecting to an unsecure server. If the server runs on SSL, there's no need for this switch.
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            var channel = GrpcChannel.ForAddress("http://localhost:5000");
            var client  = new Board.BoardClient(channel);
            var request = new MessageRequest();

            request.Capabilities.Add(new MessageRequest.Types.SuperPower {
                Name = "Flying", Level = 1
            });
            request.Capabilities.Add(new MessageRequest.Types.SuperPower {
                Name = "Invisibility", Level = 10
            });
            request.Capabilities.Add(new MessageRequest.Types.SuperPower {
                Name = "Speed", Level = 5
            });

            var reply = await client.ShowMessageAsync(request);

            var displayDate = new DateTime(reply.ReceivedTime);

            Console.WriteLine(
                $"We sent a message to a gRPC server and  received  the following reply \n'\n{reply.Message}' \non {displayDate} ");
            Console.WriteLine("End");
            Console.Read();
        }
        public async Task <IActionResult> Message(MessageRequest request)
        {
            request.LegalEntityName = TempData[nameof(request.LegalEntityName)] as string;
            var model = await _modelMapper.Map <MessageViewModel>(request);

            return(View(model));
        }
コード例 #3
0
        public PartialViewResult Email(EmailViewModel model)
        {
            if (ModelState.IsValid)
            {
                var fullName = $"{model.FirstName} {model.LastName}".Trim();

                var message = new MessageRequest(Config.Email.TechnicalSupport)
                {
                    FromName = fullName,
                    FromAddress = model.Email,
                    Subject = model.Subject,
                    Message = model.Message
                };

                this.messageService.SendMessage(message);

                // send copy to user
                message = new MessageRequest(model.Email, fullName)
                {
                    FromAddress = "donotreply@" + Config.Website.DomainName,
                    Subject = $"Copy of message sent to {Config.Website.DomainName}: {message.Subject}"
                };

                this.messageService.SendMessage(message);

                return this.PartialView("email-confirm");
            }

            return this.PartialView();
        }
コード例 #4
0
 public Response <bool> Post(MessageRequest message)
 {
     return(Ejecutar(() =>
     {
         return new Response <bool>(_messageService.Send(message.Message, ""));
     }));
 }
コード例 #5
0
    private void OnMessageWithFullRequest(MessageResponse resp, string customData)
    {
        if (resp != null)
        {
            foreach (Intent mi in resp.intents)
            {
                Debug.Log("Full Request intent: " + mi.intent + ", confidence: " + mi.confidence);
            }

            if (resp.output != null && resp.output.text.Length > 0)
            {
                foreach (string txt in resp.output.text)
                {
                    Debug.Log("Full Request output: " + txt);
                }
            }

            string questionStr = questionArray[UnityEngine.Random.Range(0, questionArray.Length - 1)];
            Debug.Log(string.Format("**********User: {0}", questionStr));

            MessageRequest messageRequest = new MessageRequest();
            messageRequest.InputText         = questionStr;
            messageRequest.alternate_intents = m_UseAlternateIntents;
            messageRequest.ContextData       = resp.context;
        }
        else
        {
            Debug.Log("Full Request: Failed to invoke Message();");
        }
    }
コード例 #6
0
ファイル: ChatPanelController.cs プロジェクト: ekinel/Rythm
        public void MessageSend(string currentMessage, string loginTo)
        {
            var msgContainer = new TextMsgRequest(_connectionServiceController.Login, loginTo, currentMessage, MsgStatus.None);
            var mr           = new MessageRequest(msgContainer, MsgType.PersonalMessage);

            _currentTransport?.Send(mr);
        }
コード例 #7
0
    //private IEnumerator Examples()
    //{
    //    //if (!_service.Message(OnMessage, OnFail, _workspaceId, "hello"))
    //        //Log.Debug("ExampleConversation.Message()", "Failed to message!");

    //    while (_waitingForResponse)
    //        yield return null;

    //    _waitingForResponse = true;
    //    _questionCount++;

    //    AskQuestion();
    //    while (_waitingForResponse)
    //        yield return null;

    //    _questionCount++;

    //    _waitingForResponse = true;

    //    AskQuestion();
    //    while (_waitingForResponse)
    //        yield return null;
    //    _questionCount++;

    //    _waitingForResponse = true;

    //    AskQuestion();
    //    while (_waitingForResponse)
    //        yield return null;
    //    _questionCount++;

    //    _waitingForResponse = true;

    //    AskQuestion();
    //    while (_waitingForResponse)
    //        yield return null;

    //    Log.Debug("ExampleConversation.Examples()", "Conversation examples complete.");
    //}

    public void AskQuestion(string question)
    {
        audioSource.Stop();
        if (AppManager.Instance.currentAppMode == AppMode.SAA)
        {
            answertext[0].SetActive(false);
        }
        else if (AppManager.Instance.currentAppMode == AppMode.CSU)
        {
            answertext[1].SetActive(false);
        }

        MessageRequest messageRequest = new MessageRequest()
        {
            input = new Dictionary <string, object>()
            {
                { "text", question }
            },
            context = _context
        };

        if (!_service.Message(OnMessage, OnFail, _workspaceId, messageRequest))
        {
            Log.Debug("ExampleConversation.AskQuestion()", "Failed to message!");
        }
    }
コード例 #8
0
        public async void SendMmsListDelete()
        {
            String attachmentId = await CreateAttachment();

            var    res = MessageRequest.Resource(Session);
            String id  = await res.Create(new MessageRequest()
            {
                From = "sender_id:" + Setup.senderIdSms,
                To   = new List <String>()
                {
                    Setup.mdnRangeStart.ToString()
                },
                Body        = "Hello World",
                Attachments = new List <String>()
                {
                    attachmentId
                },
                TestMessageFlag = true
            });

            // If the server processed the request, verify the attachment
            for (int i = 0; i < 60; i++)
            {
                var mrq = await res.Get(id);

                var readyStates = new List <String>()
                {
                    "TRANSMITTING", "COMPLETED"
                };
                if (readyStates.Contains(mrq.State))
                {
                    Assert.True(GetNumItems(res.ListMessages(id)) == 1);
                    var msgRes = Message.Resource(Session);

                    foreach (var message in res.ListMessages(id))
                    {
                        int numAttachments = 0;
                        foreach (var att in msgRes.ListAttachments(message.Id))
                        {
                            numAttachments++;
                            Assert.Equal(attachmentId, att.Id);
                        }

                        Assert.Equal(1, numAttachments);
                    }

                    break;
                }

                var failedStates = new List <String>()
                {
                    "REJECTED", "CANCELED"
                };
                if (failedStates.Contains(mrq.State))
                {
                    break;
                }
            }
        }
コード例 #9
0
 public IHttpActionResult Process(MessageRequest element)
 {
     if (element == null)
     {
         throw new HttpResponseException(HttpStatusCode.BadRequest);
     }
     return(Ok(new { message = MessageEndPoint.LoadMessage(element) }));
 }
コード例 #10
0
        public Response StopDocumentSharing(DocumentSharingRequest request)
        {
            OpenDocumentSharing[request.DocId].Remove(request.UserId);
            MessageRequest req = new MessageRequest(request.UserId, request.DocId, "RemoveDocumentSharing");

            _wsService.Send(req);
            return(new DocumentSharingChangeResponseOK());
        }
コード例 #11
0
ファイル: TellCommand.cs プロジェクト: Davisjames0901/IrcBoss
 private void Tell(MessageRequest e)
 {
     if (string.Equals(Username, e.SourceUserName, StringComparison.OrdinalIgnoreCase))
     {
         SendMessage($"{Username}, {Context.Request.RequesterUsername} wanted me to tell you '{Message}'");
         _isActive = false;
     }
 }
コード例 #12
0
ファイル: Server.cs プロジェクト: WoLfulus/Almirante
 /// <summary>
 /// Chat packet.
 /// </summary>
 /// <param name="player"></param>
 /// <param name="packet"></param>
 protected void OnChat(Player client, MessageRequest packet)
 {
     if (client.Name != null)
     {
         this.BroadcastMessage(client.Name, packet.Message);
         Console.WriteLine("[" + client.Name + "] " + packet.Message);
     }
 }
コード例 #13
0
        public IActionResult Index()
        {
            var message = new MessageRequest(1, "test", "");
            var res     = MqBus.CreateRequest <MessageRequest, MessageResponse>(message);
            var test    = res.Result;

            return(View());
        }
コード例 #14
0
        public MessageResponse Insert(MessageRequest request)
        {
            var entityToSave = _messageMapper.Parse(request);

            entityToSave.Sms = RandomNumberGenerator.GetRandom(6, 7).ToString("D6");
            Insert(entityToSave);
            return(_messageMapper.Map(entityToSave));
        }
コード例 #15
0
        public async Task SendMessage(string match_id, string message)
        {
            MessageRequest request = new MessageRequest();

            request.Message = message;

            Msg response = await request.Send(match_id);
        }
コード例 #16
0
        public async Task <MessageResponse <T> > ReattachAsync <T>(MessageRequest request) where T : Payload
        {
            var message = await this.Client.GetMessageAsync <T>(request.MessageId);

            await this.Client.SendMessageAsync(message);

            return(new MessageResponse <T>(message, request.MessageId));
        }
コード例 #17
0
 private void MessageWithFullMessageRequest(MessageRequest messageRequest)
 {
     if (messageRequest == null)
     {
         throw new ArgumentNullException("messageRequest");
     }
     m_Conversation.Message(OnMessageWithOnlyInput, m_WorkspaceID, messageRequest);
 }
コード例 #18
0
 public TelegramMessageBuilder(string baseUrl, string text)
 {
     _baseUrl = baseUrl;
     _client  = new TelegramClient();
     _request = new MessageRequest {
         Text = text
     };
 }
コード例 #19
0
        public void Execute()
        {
            var request = new MessageRequest(_currentContext.LoggedUserNumber,
                                             _messageData.ReceiverNumber,
                                             _messageData.Content);

            _serverConnection.SendMessageRequest(request);
        }
コード例 #20
0
        public async Task CreateAsync(MessageRequest input)
        {
            //var targetId = (await _identityUserRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName(input.SenderName))).Id;
            var message = new Message(GuidGenerator.Create(), input.SenderName
                                      , input.Content, input.TimeStamp);

            await _distributedEventBus.PublishAsync(message);
        }
コード例 #21
0
        public IHttpActionResult Post(MessageRequest Message)
        {
            var result = MessageService.CreateMessage(Message);

            return(Created <Entidad>("", new Entidad {
                Id = result.Id
            }));
        }
コード例 #22
0
        public async Task <IActionResult> SendMessageAsync([FromBody] MessageRequest input)
        {
            _chatAppServices.CreateAsync(input);
            //await _distributedEventBus.PublishAsync(input);
            await _kafkaProducer.MessageToKafka(input);

            return(Ok());
        }
コード例 #23
0
 public async Task <HttpResult <Loja> > CreateSaleAsync([FromBody] MessageRequest request)
 {
     if (request == null)
     {
         return(new HttpResult <Loja>().Set(HttpStatusCode.BadRequest, $"Erro na requisição"));
     }
     return(await _transactionAppService.CreateSaleAsync(request));;
 }
コード例 #24
0
        static void Main(string[] args)
        {
            // Assistant Service のインスタンス作成
            var _assistant = new AssistantService();

            // Credential をセット
            _assistant.SetCredential(_username, _password);
            // VersionDate をセット
            _assistant.VersionDate = _versionDate;

            // MessageRequest を作成
            var messageRequest0 = new MessageRequest()
            {
                Input = new InputData()
                {
                    Text = "こんにちは",
                }
            };

            System.Console.WriteLine($"input: {messageRequest0.Input.Text}");

            // Assistant のインスタンスにメッセージを送信
            var result0 = _assistant.Message(_workspaceId, messageRequest0);
            var res0    = JsonConvert.DeserializeObject <AssistantResponseJson>(result0.ResponseJson);

            System.Console.WriteLine($"rerult: {res0.Outputs.Texts[0]}");

            // 別の input を作成
            var messageRequest1 = new MessageRequest()
            {
                Input = new InputData()
                {
                    Text = "またね",
                }
            };

            System.Console.WriteLine($"input: {messageRequest1.Input.Text}");

            // 同じくメッセージを送信
            var result1 = _assistant.Message(_workspaceId, messageRequest1);
            var res1    = JsonConvert.DeserializeObject <AssistantResponseJson>(result1.ResponseJson);

            System.Console.WriteLine($"rerult: {res1.Outputs.Texts[0]}");

            #region Net Standard Core
            // Watson.NetStandardCoreに作成したAssistantServiceをラップしたGetResponseAsyncメソッドを呼び出しても同じ結果が得られます。
            // `static void Main(string[] args)`を`static async Task Main(string[] args)`に変えて試してみてください。

            //var client = new Watson.NetStandardCore.WatsonAssistantClient();
            //var res2 = await client.GetResponseAsync("こんにちは");
            //var res3 = await client.GetResponseAsync("またね");

            //Console.WriteLine(res1);
            //Console.WriteLine(res2);
            #endregion

            Console.ReadKey();
        }
コード例 #25
0
        private void ExistChat(Guid clientGuid, Guid guidToSend)
        {
            MessageRequest messageRequest = new MessageRequest(MessageKey.Exit, "0");

            _requests.SendModelMessage(_client, messageRequest);

            _data.ClientsConnectedInChat.Remove(clientGuid, guidToSend);
            _logger.LogInformation($"client {clientGuid} leave chat with client {guidToSend}");
        }
コード例 #26
0
        public async Task <IActionResult> DialogQuery([FromBody] MessageRequest message)
        {
            var result = await _mediator.Send(new MessageQuery()
            {
                Message = message.request.command
            });

            return(Ok(new MessageResponce(result.Message, message.session)));
        }
コード例 #27
0
        /// <summary>
        /// Packs the UnconnectedSend request into a byte array
        /// </summary>
        /// <returns>Array of bytes representing the UnconnectedSend request</returns>
        public byte[] Pack()
        {
            if (MessageRequest == null)
            {
                throw new NullReferenceException("MessageRequest cannot be null");
            }

            if (RoutePath == null)
            {
                throw new NullReferenceException("RoutePath cannot be null");
            }

            if (RequestPath == null)
            {
                throw new NullReferenceException("RequestPath cannot be null");
            }

            byte[] mrRequestBytes = MessageRequest.Pack();
            MessageRequestSize = (ushort)mrRequestBytes.Length;

            bool needsPad = (MessageRequestSize % 2 != 0);
            int  padSize  = (needsPad ? 1 : 0);

            RoutePathSize   = (byte)((RoutePath.Length / 2) + (RoutePath.Length % 2));
            RequestPathSize = (byte)((RequestPath.Length / 2) + (RequestPath.Length % 2));

            byte[] retVal = new byte[4 + mrRequestBytes.Length + padSize + 2 + (2 * RoutePathSize) + 2 + (RequestPathSize * 2)];

            int offset = 0;

            retVal[offset] = Service;
            offset++;
            retVal[offset] = RequestPathSize;
            offset++;
            Buffer.BlockCopy(RequestPath, 0, retVal, offset, RequestPath.Length);
            offset += RequestPathSize * 2;

            retVal[offset] = Priority_TimeTick;
            offset++;
            retVal[offset] = Timeout_Ticks;
            offset++;

            Buffer.BlockCopy(BitConverter.GetBytes(MessageRequestSize), 0, retVal, offset, 2);
            offset += 2;
            Buffer.BlockCopy(mrRequestBytes, 0, retVal, offset, mrRequestBytes.Length);
            offset += mrRequestBytes.Length;
            if (needsPad)
            {
                offset += 1;
            }
            retVal[offset] = RoutePathSize;
            offset        += 1;
            offset        += 1; //reserved
            Buffer.BlockCopy(RoutePath, 0, retVal, offset, RoutePath.Length);

            return(retVal);
        }
コード例 #28
0
        public async Task MessageToKafka(MessageRequest message)
        {
            await _producer.ProduceAsync("message", new Message <Null, string>()
            {
                Value = JsonSerializer.Serialize(message)
            });

            _producer.Flush(TimeSpan.FromSeconds(10));
        }
コード例 #29
0
        public async Task PostAsync_OkWithMatchedParameters()
        {
            // Arrange
            IEnumerable <string> ids = new string[]
            {
                "00000000-0000-0000-0000-000000000001",
                "00000000-0000-0000-0000-000000000002"
            };
            MessageContainer result1 = new MessageContainer();

            result1.Narrowcasts.Add(new Entities.Messages.NarrowcastMessage
            {
                UserMessage = "This is one message."
            });
            MessageContainer result2 = new MessageContainer();

            result2.Narrowcasts.Add(new Entities.Messages.NarrowcastMessage
            {
                UserMessage = "This is another."
            });
            IEnumerable <MessageContainer> toReturn = new List <MessageContainer>
            {
                result1,
                result2
            };

            this._repo
            .Setup(s => s.GetRangeAsync(ids, CancellationToken.None))
            .Returns(Task.FromResult(toReturn));

            MessageRequest request = new MessageRequest();

            request.RequestedQueries.Add(new MessageInfo
            {
                MessageId        = ids.ElementAt(0),
                MessageTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
            request.RequestedQueries.Add(new MessageInfo
            {
                MessageId        = ids.ElementAt(1),
                MessageTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });

            // Act
            ActionResult <MessageResponse> controllerResponse = await this._controller
                                                                .PostAsync(request, CancellationToken.None);

            // Assert
            Assert.IsNotNull(controllerResponse);
            Assert.IsInstanceOfType(controllerResponse.Result, typeof(OkObjectResult));
            OkObjectResult castedResult = controllerResponse.Result as OkObjectResult;

            Assert.IsInstanceOfType(castedResult.Value, typeof(MessageResponse));
            MessageResponse listResult = castedResult.Value as MessageResponse;

            Assert.AreEqual(toReturn.Count(), listResult.NarrowcastMessages.Count);
        }
コード例 #30
0
ファイル: RequestBuilder.cs プロジェクト: Cliveburr/BlueDB
        public MessageReponse Process()
        {
            var request = new MessageRequest
            {
                Commands = _commands.ToArray()
            };

            return(_connection.SendMessage(request).Result);
        }
コード例 #31
0
        public async Task <MessageResponse> PostMessage([FromBody] MessageRequest request)
        {
            if (!request.Validate(out string validationError))
            {
                return(MessageResponse.Error(validationError));
            }

            return(MessageResponse.From(await _messageQueue.Enqueue(MessageRequest.ToStringMessage(request, Request.Host.Value))));
        }
コード例 #32
0
        private MessageRequest ParseRequest(string data)
        {
            var rawRequest = JObject.Parse(data);

            var request = new MessageRequest();
            request.Class = rawRequest.Value<string>("type");
            request.Method = rawRequest.Value<string>("method");
            request.Args = rawRequest["args"] == null ? new JTokenValue[] { } : rawRequest["args"].Children().Select(v => new JTokenValue(v)).ToArray();

            return request;
        }
コード例 #33
0
        private void InvokeMethod(MessageRequest request)
        {
            var method = _subscriberInfoResolver.GetMethod(request.Class, request.Method, request.Args);
            var handlerDescription = _subscriberInfoResolver.GetSubscriber(request.Class);
            var handler = _subscriberInfoResolver.CreateHandler(handlerDescription);

            if (method != null && handlerDescription != null && handler != null)
            {
                var args = _parameterResolver.ResolveMethodParameters(method, request.Args);

                method.Invoke(handler, args);
            }
        }
コード例 #34
0
ファイル: WIAdder.cs プロジェクト: AlmatoolboxCE/MailToWI
        public int AddNewWIFromMailBug(MessageRequest data)
        {
            var manager = new TFSConnectionManager();
            //var WIToAdd = GetNewWorkItem(Connection, ProjectName, "BUG", AreaPath, IterationPath, data.Subject, data.Body);

            using (var conn = manager.GetConnection())
            {
                WorkItemStore workItemStore = conn.GetService<WorkItemStore>();
                Project prj = workItemStore.Projects[ProjectName];
                WorkItemType workItemType = prj.WorkItemTypes["BUG"];


                var WIToAdd = new WorkItem(workItemType)
                {
                    Title = data.Subject,
                    Description = data.Body,
                    IterationPath = IterationPath,
                    AreaPath = AreaPath,
                };

                WIToAdd.Fields[this.StepsToReproduceName].Value = data.Body;
                if (!string.IsNullOrWhiteSpace(this.AssignedToValue))
                {
                    WIToAdd.Fields[this.AssignedToName].Value = this.AssignedToValue;
                }

                var filePath = TempFileManager.SaveFileAndGetName(data.FileFormat);
                try
                {
                    WIToAdd.Attachments.Add(new Microsoft.TeamFoundation.WorkItemTracking.Client.Attachment(filePath));
                    WIToAdd.Save();
                    return WIToAdd.Id;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    TempFileManager.ClearFile(filePath);
                }
            }
        }
コード例 #35
0
ファイル: VRProxy.cs プロジェクト: k4b/VRFSClient
 public void sendMessage(MessageRequest message)
 {
     clientSocket.SendMore(BitConverter.GetBytes(message.messageID));
     clientSocket.SendMore(BitConverter.GetBytes(message.operation.operationID));
     clientSocket.SendMore(message.operation.path, Encoding.Unicode);
     if (message.operation.operationID == 1)
     {
         clientSocket.SendMore(message.operation.file);
     }
     clientSocket.SendMore(BitConverter.GetBytes(message.clientID));
     clientSocket.SendMore(BitConverter.GetBytes(message.requestNumber));
     clientSocket.Send(BitConverter.GetBytes(message.viewNumber));
     try
     {
         waitForReply(3 * 1000);
     }
     catch (System.Exception e)
     {
         Console.WriteLine(e.Message);
     }
 }
コード例 #36
0
ファイル: MessageRouterTest.cs プロジェクト: netcasewqs/nlite
        public void ReturnResultTest4()
        {
            const string topic = "ReturnResultTest4";

            Func<int, int> handler = p => 1;
            Action<int> handler2 = p => { Thread.Sleep(1000); };
            Func<int, int> handler3 = p => 3;

            using (Bus.Subscribe(topic, SubscribeMode.Async, handler))//避免内存泄露
            using (Bus.Subscribe(topic, SubscribeMode.Async, handler2))//避免内存泄露
            using (Bus.Subscribe(topic, handler3))//避免内存泄露
            {
                var req = new MessageRequest<int> { Topic = topic, Data = 0,  };
                var resp = Bus.Publish(req);
                resp.Results.OfType<int>().ForEach(item => Console.WriteLine(item));
            }

        }
コード例 #37
0
 public MessageResponse SendMessage(MessageRequest message)
 {
     return null;
 }
コード例 #38
0
 public void SendAutoMessageReply(string fromJid, string toJid, string message, string style, int type)
 {
     if (message != null)
     {
         MessageRequest request = new MessageRequest();
         request.from_jid = fromJid;
         request.to_jid = toJid;
         request.message = message;
         request.style = style;
         request.type = type;
         this.connection.Send(PacketType.ENT_MESSAGE, request);
     }
 }
コード例 #39
0
 private void ReceiveThread()
 {
     try
      {
     udpReceiveClient = new UdpClient(port, AddressFamily.InterNetwork);
     IPEndPoint receivedFrom = new IPEndPoint(IPAddress.Any, 0);
     byte[] receivedBytes = new byte[100000];
     while (keepRecieving)
     {
        receivedBytes = udpReceiveClient.Receive(ref receivedFrom);
        int receivedLength = receivedBytes.Length;
        if (receivedLength > 36)
        {
           NetworkMessage message = new NetworkMessage(receivedBytes);
           Debug.WriteLine(String.Format("Received {0} from {1}", message.Type, receivedFrom));
           switch (message.Type)
           {
              case NetworkMessageType.Message:
                 ReceiveQueue.Enqueue(message);
                 messageReceivedEvent.Set();
                 break;
              case NetworkMessageType.DirectRequest:
                 if (message.DestinationID == this.localID)
                 {
                    Debug.WriteLine("Received direct request for " + message.DestinationID.ToString());
                    NetworkMessage replyMessage = new NetworkMessage(this.localID, message.SenderID, Guid.NewGuid(), NetworkMessageType.DirectReply, message.Data, 1, 1, 50000);
                    sendMessage(replyMessage);
                 }
                 break;
              case NetworkMessageType.DirectReply:
                 if (message.DestinationID == localID)
                 {
                    Debug.WriteLine("Recieved reply for " + message.DestinationID.ToString());
                    MessageRequest messageReq = new MessageRequest();
                    messageReq.Address = receivedFrom.Address;
                    messageReq.MessageID = new Guid(message.Data);
                    messageReq.Fragment = -1;
                    directUdpTargets.Enqueue(messageReq);
                    directUdpEvent.Set();
                 }
                 break;
              case NetworkMessageType.FragmentRequest:
                 if (message.SenderID != localID)
                 {
                    Guid messageRequestID = new Guid(message.Data);
                    Debug.WriteLine(String.Format("Request for resend of message {0} fragment {1}", messageRequestID, message.FragmentNumber));
                    MessageRequest fragmentReq = new MessageRequest();
                    fragmentReq.Address = receivedFrom.Address;
                    fragmentReq.MessageID = new Guid(message.Data);
                    fragmentReq.Fragment = message.FragmentNumber;
                    directUdpTargets.Enqueue(fragmentReq);
                    directUdpEvent.Set();
                    Thread.Sleep(0);
                 }
                 break;
           }
        }
     }
      }
      catch (SocketException ex)
      {
     Debug.WriteLine(String.Format("SocketException: {0} {1}\r\n{2}", ex.ErrorCode, ex.Message, ex.StackTrace));
      }
 }
コード例 #40
0
 public void SendStaffUpDownNotice(string fromJid, string toJid, string message, string style, int type)
 {
     MessageRequest request = new MessageRequest();
     request.from_jid = fromJid;
     request.to_jid = toJid;
     request.message = message;
     request.style = style;
     request.type = type;
     this.connection.Send(PacketType.ENT_MESSAGE, request);
 }
コード例 #41
0
        private MessageResponse SendActivateAccountToken(string email, string activateAccountToken, string firstName, string lastName)
        {
            var fullName = $"{firstName} {lastName}".Trim();

            var emailUrl = this.Url.Action("ActivateAccount", "Email", new
            {
                name = firstName,
                token = activateAccountToken
            });

            var message = new MessageRequest(email, fullName)
            {
                FromAddress = "donotreply@" + Website.DomainName,
                FromName = Website.Name,
                Subject = "Please activate your account with " + Website.Name,
                MessageUrl = new Uri(emailUrl)
            };

            return this.messageService.SendMessage(message);
        }
コード例 #42
0
 public void SendMessageStaff(Message message)
 {
     if (message != null)
     {
         MessageRequest request = new MessageRequest();
         request.from_jid = message.FromJid;
         request.to_jid = message.ToJid;
         request.message = this.utilService.MessageEncode(message.MessageBlocks);
         request.style = message.Style.ToString();
         request.type = message.VOType;
         this.connection.Send(PacketType.ENT_MESSAGE, request);
     }
 }
コード例 #43
0
 public IObservable<IEnumerable<Message>> GetRoomMessages(string roomId, MessageRequest request)
 {
     return _apiService.GetRoomMessagesAsync(roomId, request).ToObservable();
 }
コード例 #44
0
        public async Task<IEnumerable<Message>> GetRoomMessagesAsync(string roomId, MessageRequest request)
        {
            string url = _baseApiAddress + $"rooms/{roomId}/chatMessages?";

            url += $"limit={request.Limit}";

            if (!string.IsNullOrWhiteSpace(request.BeforeId))
                url += $"&beforeId={request.BeforeId}";

            if (!string.IsNullOrWhiteSpace(request.AfterId))
                url += $"&afterId={request.AfterId}";

            if (!string.IsNullOrWhiteSpace(request.AroundId))
                url += $"&aroundId={request.AroundId}";

            if (request.Skip > 0)
                url += $"&skip={request.Skip}";

            if (!string.IsNullOrWhiteSpace(request.Lang))
                url += $"&lang={request.Lang}";

            if (!string.IsNullOrWhiteSpace(request.Query))
                url += $"&q={request.Query}";

            return await HttpClient.GetAsync<IEnumerable<Message>>(url);
        }
コード例 #45
0
ファイル: MessageRouterTest.cs プロジェクト: netcasewqs/nlite
        public void ReturnResultTest3()
        {
            const string topic = "ReturnResultTest3";

            Func<int, int> handler = p => 1;
            Action<int> handler2 = p => { Thread.Sleep(1000); };
            Func<int, int> handler3 = p => 3;

            Bus.Subscribe(topic, SubscribeMode.Async, handler);
            Bus.Subscribe(topic, SubscribeMode.Async, handler2);
            Bus.Subscribe(topic, handler3);

            var req = new MessageRequest<int>
            {
                Topic = topic,
                Data = 0,
            };
            var resp = Bus.Publish(req);

            var results = resp.Results.OfType<int>();
            foreach (var item in results)
                Console.WriteLine(item);


        }
コード例 #46
0
ファイル: CommandProcessor.cs プロジェクト: k4b/VRFSClient
 private void processDelete(string[] commandTokens)
 {
     string destPath = commandTokens[1];
     client.incrementRequestNumber();
     Operation operationDelete = new Operation(destPath);
     MessageRequest request = new MessageRequest(1, operationDelete, client.ID, client.requestNumber, client.viewNumber);
     Console.WriteLine("Sending:");
     Console.WriteLine(request.ToString());
     proxy.sendMessage(request);
 }
コード例 #47
0
        public ActionResult RequestPassword(RequestPasswordViewModel model)
        {
            if (this.ModelState.IsValid)
            {
                var request = new RequestPasswordRequest
                {
                    UserName = model.UserName,
                    Expires = TimeSpan.FromHours(2)
                };

                var response = this.authenticationService.ResetPasswordRequest(request);
                if (response.Status == StatusCode.OK)
                {
                    var message = new MessageRequest
                    {
                        //ToAddress = string.Empty,
                        Subject = "You have requested to reset your password",
                        Message = response.ResetPasswordToken
                    };
                    this.messageService.SendMessage(message);
                    this.TempData["SuccessMessage"] = "You have successfully requested a new password. You should receive an email presently with instructions on how to reset your password. If you do not receive an email within 15 minutes, please check that you have the correct user name and try again.";
                    return this.RedirectToAction("Login");
                }
            }

            return this.View();
        }
コード例 #48
0
        public async Task<JsonResult> GetMessages()
        {
            Subscription subscription = System.Web.HttpContext.Current.Session["WebHookSubscription"] as Subscription;
            if (subscription != null)
            {
                string xmlpath = AppDomain.CurrentDomain.BaseDirectory + "App_Data\\Notifications.xml";
                try
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(xmlpath);
                    XmlNodeList items = doc.SelectNodes("//value");
                    List<XmlNode> removeItems = new List<XmlNode>();

                    List<string> resourceArray = new List<string>();
                    List<Message> retMessageList = new List<Message>();

                    foreach (XmlNode item in items)
                    {
                        string resource = string.Empty, clientState = string.Empty;
                        foreach (XmlNode ss in item.ChildNodes)
                        {
                            if (ss.Name.ToLower().Equals("clientstate"))
                            {
                                if (ss.InnerText != subscription.ClientState)
                                 {
                                    resource = string.Empty;
                                    break;
                                }
                            }
                            if (ss.Name.ToLower().Equals("resource"))
                            {
                                resource = ss.InnerText;
                            }
                        }
                        removeItems.Add(item);
                        if (resource != string.Empty && resourceArray.IndexOf(resource) == -1)
                        {
                            resourceArray.Add(resource);
                            break;
                        }
                    }
                    if (removeItems.Count > 0)
                    {
                        XmlNode root = doc.DocumentElement;
                        foreach (XmlNode node in removeItems)
                        {
                            root.RemoveChild(node);
                        }
                        doc.Save(xmlpath);
                    }

                    GraphServiceClient graphServiceClient = await AuthenticationHelper.GetGraphServiceAsync(AADAppSettings.GraphResourceUrl);
                    foreach (var resource in resourceArray)
                    {
                        var requst = new MessageRequest(graphServiceClient.BaseUrl + "/" + resource, graphServiceClient, null);
                        retMessageList.Add( await requst.GetAsync());
                    }
                    return Json(new { status = "ok", notifications = retMessageList }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            return Json(new { status = "ok" }, JsonRequestBehavior.AllowGet);
        }
コード例 #49
0
ファイル: CommandProcessor.cs プロジェクト: k4b/VRFSClient
        private void processCopy(string[] commandTokens)
        {
            string srcPath = commandTokens[1];
            string destPath = commandTokens[2];
            byte[] bytes = File.ReadAllBytes(srcPath);

            client.incrementRequestNumber();
            Operation operationCopy = new Operation(bytes, destPath);
            MessageRequest request = new MessageRequest(1, operationCopy, client.ID, client.requestNumber, client.viewNumber);
            Console.WriteLine("Sending:");
            Console.WriteLine(request.ToString());
            //proxy.startClient();
            proxy.sendMessage(request);
        }
コード例 #50
0
ファイル: EmailService.cs プロジェクト: porl88/Website-MVC
 private bool ValidateMessageRequest(MessageRequest request)
 {
     return !string.IsNullOrWhiteSpace(request.Subject) && (!string.IsNullOrWhiteSpace(request.Message) || request.MessageUrl != null) && !string.IsNullOrWhiteSpace(request.FromAddress) && request.ToAddresses.Any(x => !string.IsNullOrWhiteSpace(x.Address));
 }
コード例 #51
0
ファイル: EmailService.cs プロジェクト: porl88/Website-MVC
        public MessageResponse SendMessage(MessageRequest request)
        {
            var response = new MessageResponse();

            if (this.ValidateMessageRequest(request))
            {
                try
                {
                    var message = new MailMessage();

                    foreach (var address in request.ToAddresses)
                    {
                        if (string.IsNullOrWhiteSpace(address.DisplayName))
                        {
                            message.To.Add(new MailAddress(address.Address));
                        }
                        else
                        {
                            message.To.Add(new MailAddress(address.Address, address.DisplayName));
                        }
                    }

                    if (string.IsNullOrWhiteSpace(request.FromName))
                    {
                        message.From = new MailAddress(request.FromAddress);
                    }
                    else
                    {
                        message.From = new MailAddress(request.FromAddress, request.FromName);
                    }

                    message.Subject = request.Subject;

                    if (request.MessageUrl != null)
                    {
                        using (var client = new WebClient())
                        {
                            message.Body = client.DownloadString(request.MessageUrl.AbsoluteUri);
                        }
                    }
                    else
                    {
                        message.Body = request.Message;
                    }

                    message.IsBodyHtml = request.IsHtml;

                    var smtp = new SmtpClient();
                    smtp.Send(message);

                    response.Status = StatusCode.OK;
                }
                catch (Exception ex)
                {
                    response.Status = StatusCode.InternalServerError;
                    this.exceptionHandler.HandleException(ex);
                }
            }
            else
            {
                response.Status = StatusCode.BadRequest;
            }

            return response;
        }
コード例 #52
0
 public void SendStaffDownLoadNotice(string fromJid, string toJid, string message, string style, int type, string icon, string filename, string url)
 {
     MessageRequest request = new MessageRequest();
     request.from_jid = fromJid;
     request.to_jid = toJid;
     request.message = message;
     request.style = style;
     request.type = type;
     request.icon = icon;
     request.fileName = filename;
     request.url = url;
     this.connection.Send(PacketType.ENT_MESSAGE, request);
 }