Exemple #1
0
		public void RegisterChannel(Strive.Network.Messages.CommunicationType communicationType, string name, MessageReceived callback)
		{
			if(!_registrations.Contains(CalculateChannelKey(communicationType, name)))
			{
				_registrations.Add(CalculateChannelKey(communicationType, name), callback);
			}
		}
        public override InputHandlerResult handleInput(UserSession user_session, MessageReceived message_recieved)
        {
            string input = extractReply(message_recieved);
            //Console.WriteLine("in input handler: " + input);
            Console.WriteLine("User with ID: " + user_session.user_profile.id + " Entered: " + input);
            //get reply
            string curr_user_page = user_session.current_menu_loc;

            InputHandlerResult output = handleDisplayMessageLinks(
               user_session,
               input,
               "Your input was invalid. You message has been sent already but please click Back/Main to continue",
               true);

            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
            {
                if(output.action == InputHandlerResult.BACK_WITHOUT_INIT_MENU_ACTION)
                    user_session.setVariable(Browse_Bible_Handler.BROWSE_CLEAR_SCREEN, true);
                return output;
            }
            output = handleStdNavLinks(user_session, input,true);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            output = handleMyProfileLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            //handle back or home here.

            return new InputHandlerResult(
                    "Invalid entry...Please enter a valid input"); //invalid choice
        }
        public void CreateAsyncMessageConsumer(OpenMQNative.MQHandle sessionHandle,
            OpenMQNative.MQHandle destinationHandle,
            MessageReceived MsgRecCallback, ref OpenMQNative.MQHandle consumerHandle)
        {
            try
            {
                msgRecDelegate = new MessageReceived(MsgRecCallback);

                OpenMQNative.MQMessageListenerDelegate callback =
                    new OpenMQNative.MQMessageListenerDelegate(AsyncMessageCallback);

                OpenMQNative.MQStatus res = OpenMQNative.MQCreateAsyncMessageConsumer(sessionHandle,
                    destinationHandle, null, (Int32)OpenMQNative.MQ_FALSE, callback,
                    IntPtr.Zero,
                    ref consumerHandle);
                if (OpenMQNative.MQ_ERR_CHK(res))
                    throw new OpenMQException("Error creating Async Message Consumer " + res.errorCode);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                throw new OpenMQException(e.Message);
            }
        }
        public async void Init(MessageReceived messageReceivedHandler) {
            this.random = new Random();

            //ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect;
            
            // Tcp mode does not work when I run in a VM (VirtualBox) and the host 
            // is using a wireless connection. Hard coding to Http.
            ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;

            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            this.factory = MessagingFactory.CreateFromConnectionString(connectionString);
            this.namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            if (!namespaceManager.TopicExists(topicName)) {
                namespaceManager.CreateTopic(topicName);
            }

            this.subscriptionName = Guid.NewGuid().ToString();

            // Not needed really, it's a GUID...
            if (!namespaceManager.SubscriptionExists(topicName, subscriptionName)) {
                namespaceManager.CreateSubscription(topicName, subscriptionName);
            }

            this.topicClient = factory.CreateTopicClient(topicName);

            this.subClient = factory.CreateSubscriptionClient(topicName, subscriptionName);

            while (true) {
                await ReceiveMessageTaskAsync(messageReceivedHandler);
            }
        }
Exemple #5
0
        public override InputHandlerResult handleInput(UserSession user_session, MessageReceived message_recieved)
        {
            string input = extractReply(message_recieved);
            //Console.WriteLine("in input handler: " + input);
            Console.WriteLine("User with ID: " + user_session.user_profile.id + " Entered: " + input);
            //get reply
            string curr_user_page = user_session.current_menu_loc;

            InputHandlerResult output = handleStdNavLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            output = handleStdPageLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            output = handleFriendLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            //handle back or home here.

            return new InputHandlerResult(
                    "Invalid entry...Please enter a valid input"); //invalid choice
        }
Exemple #6
0
		public void InitializeConnect()
		{
			OutputWindow.Clear();

			// Assign events
			eventReceiving += new IRCReceived(IrcCommandReceived);
			eventServerMessage += new ServerMessage(IrcServerMessage);
			eventIrcMessageReceived += new MessageReceived(IrcMessageReceived);
			eventIrcNoticeReceived += new NoticeReceived(IrcNoticeReceived);
			eventSendReceivedCommand += new SendReceivedCommand(IrcSendReceivedCommand);
			eventSendModMessage += new SendModMessage(IrcSendModMessage);
			eventJoin += new Join(IrcJoin);
			eventPart += new Part(IrcPart);
			eventMode += new Mode(IrcMode);

			//Try to set the LogFile 
			try
			{
				logOutput = new StreamWriter(logFileName, true);
			}
			catch (Exception e)
			{
				log = false;

				if (ToggleDebugCheckBox.Checked)
					IrcCommandReceived(e.Message);
			}

			// Connect to server	
			Connect();
		}
        public override InputHandlerResult handleInput(UserSession user_session, MessageReceived message_recieved)
        {
            string input = extractReply(message_recieved);
            //Console.WriteLine("in input handler: " + input);
            Console.WriteLine("User with ID: " + user_session.user_profile.id + " Entered: " + input);
            //get reply
            string curr_user_page = user_session.current_menu_loc;

            InputHandlerResult output = handleStdNavLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            output = handleStdPageLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            MenuManager mm = MenuManager.getInstance();
            //for now we assume this. must correct this later
            OptionMenuPage omp = (OptionMenuPage)mm.menu_def.getMenuPage(curr_user_page);
            List<MenuOptionItem> options = omp.options;
            foreach (MenuOptionItem option in options)
            {
                if (option.link_val.Equals(input))
                    return new InputHandlerResult(
                    InputHandlerResult.NEW_MENU_ACTION,
                    option.select_action,
                    InputHandlerResult.DEFAULT_PAGE_ID);
            }
            //handle back or home here.

            return new InputHandlerResult(
                    "Invalid entry...Please enter a valid input"); //invalid choice
        }
Exemple #8
0
 protected override void NewMessage(string tagid, NdefMessage message)
 {
     if (_result != null)
     {
         MessageReceived result = new MessageReceived(tagid,message,this);
         _result.TrySetResult(result);
     }
 }
Exemple #9
0
        public override InputHandlerResult handleInput(UserSession user_session, MessageReceived message_recieved)
        {
            string input = extractReply(message_recieved);
            input = input.Trim();
            Console.WriteLine("User with ID: " + user_session.user_profile.id + " Entered: " + input);
            //get reply
            string curr_user_page = user_session.current_menu_loc;

            InputHandlerResult output = handleStdNavLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            /*output = handleStdPageLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;*/

            MenuManager mm = MenuManager.getInstance();
            //for now we assume this. must correct this later
            VerseMenuPage vmp = (VerseMenuPage)mm.menu_def.getMenuPage(curr_user_page);

            if (input.Count() > UserNameManager.MAX_USER_NAME_LENGTH)
            {
                return new InputHandlerResult(
                   "Your user name is too long, please keep it less than " + UserNameManager.MAX_USER_NAME_LENGTH + " characters.\r\n"); //invalid choice
            }
            else if (input.Equals("") || input.Equals(MyProfileHandler.USER_NAME_CHANGE))
            {
                return new InputHandlerResult(
                   "You entered a blank user name, this is not allowed. please try again.\r\n"); //blank input
            }
            else if (!UserNameManager.getInstance().isUserNameUnique(input))
            {
                return new InputHandlerResult(
                   "Sorry but that user name is already taken. Please try again.\r\n"); //blank input
            }
            else
            {
                try
                {
                    user_session.user_profile.setUserName(input);
                    return new InputHandlerResult(
                     InputHandlerResult.NEW_MENU_ACTION,
                     vmp.input_item.target_page,
                     InputHandlerResult.DEFAULT_PAGE_ID);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                    return new InputHandlerResult(
                   "Your user name is invalid or has been taken already, please try again."); //invalid choice
                }
            }
        }
        public override InputHandlerResult handleInput(UserSession user_session, MessageReceived message_recieved)
        {
            string input = extractReply(message_recieved);
            Console.WriteLine("User with ID: " + user_session.user_profile.id + " Entered: " + input);
            //get reply
            string curr_user_page = user_session.current_menu_loc;

            MenuManager mm = MenuManager.getInstance();
            MenuPage mp = mm.menu_def.getMenuPage(curr_user_page);
            //for now we assume this. must correct this later
            DynMenuPage dmp = (DynMenuPage)mm.menu_def.getMenuPage(curr_user_page);

            //handle extra commands
            InputHandlerResult output = dmp.dynamic_set.handleExtraCommandInput(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            output = handleStdNavLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            output = handleStdPageLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            output = handleShortcutLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            /*            List<MenuOptionItem> options = mp.getOptionList(user_session);
            string output_var = dmp.output_var;
            //this is a waste, if we do change input then its found so we can already return.
            input = dmp.dynamic_set.parseInput(input, user_session);
            foreach (MenuOptionItem option in options)
            {
                if (option.is_valid && option.link_val.Equals(input))
                {
                    user_session.setVariable(output_var, input);
                    return new InputHandlerResult(
                        InputHandlerResult.NEW_MENU_ACTION,
                        option.select_action,
                        InputHandlerResult.DEFAULT_PAGE_ID);
                }
            }

            */

            return new InputHandlerResult(
                    "Invalid entry...Please enter a valid input"); //invalid choice
        }
Exemple #11
0
        public void InitializeConnect()
        {
            OutputWindow.Clear();

            // Assign events
            eventReceiving += new IRCReceived(IrcCommandReceived);
            eventServerMessage += new ServerMessage(IrcServerMessage);
            eventIrcMessageReceived += new MessageReceived(IrcMessageReceived);
            eventIrcNoticeReceived += new NoticeReceived(IrcNoticeReceived);
            eventSendReceivedCommand += new SendReceivedCommand(IrcSendReceivedCommand);
            eventSendModMessage += new SendModMessage(IrcSendModMessage);
            eventJoin += new Join(IrcJoin);
            eventPart += new Part(IrcPart);
            eventMode += new Mode(IrcMode);

            // Connect to server
            Connect();
        }
Exemple #12
0
 protected string extractReply(MessageReceived messageReceived)
 {
     if (messageReceived.Type == MessageType.Normal || messageReceived.Type == MessageType.Chat)
     {
         return messageReceived.Body;
     }
     else if (messageReceived.Type == MessageType.MXitCommand)
     {
         Dictionary<string, IReply> request = messageReceived.ExtractReply();
         return request[OptionScreenOutputAdapter.MENU_LINK_NAME].Value;
     }
     else if (messageReceived.Type == MessageType.ServiceRedirect
                 || messageReceived.Type == MessageType.Service2Service)
     {
         return MainMenuHandler.REFER_A_FRIEND_COMPLETED;
     }
     else
     {
         throw new Exception("Unsupported Message Received");
     }
 }
 private void OnMessageReceived(string user, long channelId, string message)
 {
     MessageReceived?.Invoke(this, new MixerMessage(user, channelId.ToString(), message));
 }
Exemple #14
0
        public async Task ConnectAsync(string input, IBrowserProfile browserProfile)
        {
            CanConnect    = false;
            CanDisconnect = true;

            _disconnectReason = DisconnectReason.Unknown;
            InputType inputType;

            try
            {
                while (true)
                {
                    _first.Reset();
                    string liveId;
                    if (Tools.IsValidUserId(input))
                    {
                        inputType = InputType.UserId;
                        var userId = Tools.ExtractUserId(input);
                        liveId = await GetLiveIdAsync(userId);//TODO:

                        //GetLiveIdAsync()を実行中にユーザがDisconnect()するとliveIdがnullになる
                        if (string.IsNullOrEmpty(liveId))
                        {
                            break;
                        }
                    }
                    else if (Tools.IsValidLiveId(input))
                    {
                        inputType = InputType.LiveId;
                        liveId    = Tools.ExtractLiveId(input);
                    }
                    else
                    {
                        inputType = InputType.Unknown;
                        //
                        break;
                    }

                    var liveInfo = await Api.GetLiveInfo(_server, liveId);

                    MetadataUpdated?.Invoke(this, LiveInfo2Meta(liveInfo));
                    Connected?.Invoke(this, new ConnectedEventArgs
                    {
                        IsInputStoringNeeded = false,
                        UrlToRestore         = null,
                    });
                    var initialComments = await Api.GetLiveComments(_server, liveId);

                    foreach (var c in initialComments)
                    {
                        var userId         = c.UserId;
                        var isFirstComment = _first.IsFirstComment(userId);
                        var user           = GetUser(userId);

                        var context = CreateMessageContext(c, true, "");
                        MessageReceived?.Invoke(this, context);
                    }
                    _provider = CreateMessageProvider(liveInfo.Broadcastkey);
                    _provider.MessageReceived += Provider_MessageReceived;
                    _provider.MetadataUpdated += Provider_MetadataUpdated;

                    var commentTask  = _provider.ReceiveAsync();
                    var metaProvider = new MetadataProvider(_server, _siteOptions, liveId);
                    metaProvider.MetadataUpdated += MetaProvider_MetadataUpdated;
                    var metaTask = metaProvider.ReceiveAsync();
                    var tasks    = new List <Task>();
                    tasks.Add(commentTask);
                    tasks.Add(metaTask);

                    while (tasks.Count > 0)
                    {
                        var t = await Task.WhenAny(tasks);

                        if (t == commentTask)
                        {
                            try
                            {
                                await commentTask;
                            }
                            catch (Exception ex)
                            {
                                _logger.LogException(ex, "", $"input={input}");
                            }
                            tasks.Remove(commentTask);
                            metaProvider.Disconnect();
                            try
                            {
                                await metaTask;
                            }
                            catch (Exception ex)
                            {
                                _logger.LogException(ex, "", $"input={input}");
                            }
                            tasks.Remove(metaTask);
                        }
                        else if (t == metaTask)
                        {
                            try
                            {
                                await metaTask;
                            }
                            catch (Exception ex)
                            {
                                _logger.LogException(ex, "", $"input={input}");
                            }
                            tasks.Remove(metaTask);
                            //MetadataProviderの内部でcatchしないような例外が投げられた。メタデータの取得は諦めたほうが良い。多分。
                        }
                    }
                    //inputTypeがUserIdの場合は
                    if (inputType != InputType.UserId)
                    {
                        break;
                    }
                    if (_disconnectReason == DisconnectReason.User)
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
            }
            finally
            {
                CanConnect    = true;
                CanDisconnect = false;
            }
        }
 private void SendMessage(Message message)
 {
     MessageReceived?.Invoke(this, new MessageReceivedEventArgs(message));
 }
Exemple #16
0
		/// <summary>
		/// Retrieves a set of mail messages by their unique identifier message attributes
		/// providing fine-grained control over which message parts to retrieve of each
		/// respective message.
		/// </summary>
		/// <param name="uids">An array of unique identifiers of the mail messages to
		/// retrieve</param>
		/// <param name="callback">A delegate which will be invoked for every MIME body
		/// part of a mail message to determine whether it should be fetched from the
		/// server or skipped.</param>
		/// <param name="seen">Set this to true to set the \Seen flag for the fetched
		/// messages on the server.</param>
		/// <param name="mailbox">The mailbox the messages will be retrieved from. If this
		/// parameter is omitted, the value of the DefaultMailbox property is used to
		/// determine the mailbox to operate on.</param>
		/// <exception cref="NotAuthenticatedException">Thrown if the method was called
		/// in a non-authenticated state, i.e. before logging into the server with
		/// valid credentials.</exception>
		/// <exception cref="BadServerResponseException">Thrown if the mail messages could
		/// not be fetched. The message property of the exception contains the error message
		/// returned by the server.</exception>
		/// <returns>An array of initialized instances of the MailMessage class representing
		/// the fetched mail messages</returns>
		/// <remarks>A unique identifier (UID) is a 32-bit value assigned to each
		/// message which uniquely identifies the message within a mailbox. No two
		/// messages in a mailbox share the the same UID.</remarks>
		/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="GetMessages-3"]/*'/>
		public List<MessageInfo> GetMessages(long[] uids, ExaminePartDelegate callback,
			bool seen = true, MessageReceived messageReceived = null) {
                if (!Authed)
                    throw new NotAuthenticatedException();
                lock (sequenceLock)
                {
                    if (this.selectedMailbox == null)
                        throw new InvalidOperationException("No mailbox or folder currently selected.");

                    List<MessageInfo> infos = GetMailHeader(uids, seen);

                    Dictionary<long,string> structures = GetBodystructure(uids);
                    try
                    {
                        foreach (MessageInfo info in infos)
                        {
                            Bodypart[] parts = Bodystructure.Parse(structures[info.UID]);
                            foreach (Bodypart part in parts)
                            {
                                /* Let delegate decide if part should be fetched or not */
                                if (callback(part) == true)
                                {
                                    string content = GetBodypart(info.UID, part.PartNumber, seen);
                                    info.Envelope.AddBodypart(part, content);
                                }
                            }

                            if (messageReceived != null)
                                messageReceived.Invoke(info);
                        }
                    }
                    catch (FormatException)
                    {
                        throw new BadServerResponseException("Server returned erroneous " +
                            "body structure.");
                    }
                   
                    return infos;
                }
		}
Exemple #17
0
 internal void OnMessageReceived(ChatType type, string sender, string msg) => MessageReceived?.Invoke(type, sender, msg);
Exemple #18
0
 private void RaiseMessageRecived(Socket socket, byte[] buffer)
 {
     MessageReceived?.Invoke(socket, buffer);
 }
        public void handleUserClickedOnAdLink(MessageReceived messageReceived, MXit.User.UserInfo userInfo)
        {
            String adClickURL = messageReceived.Body.Split('~')[1];

            createAndQueueRequestToMobiApp(userInfo, adClickURL);

            //We need to wait a short while before calling the redirect to make sure the Mobi App has saved the URL to redirect to:
            Thread.Sleep(20);

            MXit.Navigation.RedirectRequest redirectRequest;
            String messageForMobiApp = ".gotourl~" + adClickURL;
            redirectRequest = messageReceived.CreateRedirectRequest(AdvertConfig.mobiAppServiceName, messageForMobiApp);

            //Redirect the users context

            //************* Replace with your own client.RedirectRequest based on where your client object resides: ***************
            MXitConnectionModule.ConnectionManager.Instance.RedirectRequest(redirectRequest);
            //****************************
        }
Exemple #20
0
        public override InputHandlerResult handleInput(UserSession user_session, MessageReceived message_recieved)
        {
            user_session.search_results = null;
            string input = extractReply(message_recieved);
            Console.WriteLine("User with ID: " + user_session.user_profile.id + " Entered: " + input);
            //get reply
            string curr_user_page = user_session.current_menu_loc;

            InputHandlerResult output = handleStdNavLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            /*output = handleStdPageLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;*/

            MenuManager mm = MenuManager.getInstance();
            //for now we assume this. must correct this later
            VerseMenuPage vmp = (VerseMenuPage)mm.menu_def.getMenuPage(curr_user_page);
            List<MenuOptionItem> options = vmp.options;
            foreach (MenuOptionItem option in options)
            {
                if (option.link_val.Equals(input))
                    return new InputHandlerResult(
                         InputHandlerResult.NEW_MENU_ACTION,
                         option.select_action,
                         InputHandlerResult.DEFAULT_PAGE_ID);
            }

            if (input.Count() > MAX_MESSAGE_LENGTH)
            {
                return new InputHandlerResult(
                   "Your search query is too long " + MAX_MESSAGE_LENGTH + " characters.\r\n"); //invalid choice
            }
            else if (input== null || "".Equals(input.Trim()) )
            {
                return new InputHandlerResult(
                   "You search query was blank. You need to send the words that you would like to search for. \r\n"); //invalid choice
            }
            else
            {
                try
                {
                    searchBible(user_session, input);
                    return new InputHandlerResult(
                     InputHandlerResult.NEW_MENU_ACTION,
                     vmp.input_item.target_page,
                     InputHandlerResult.DEFAULT_PAGE_ID);
                }
                catch (Exception e)
                {
                    try
                    {
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.StackTrace);
                        searchBible(user_session, input);
                        return new InputHandlerResult(
                         InputHandlerResult.NEW_MENU_ACTION,
                         vmp.input_item.target_page,
                         InputHandlerResult.DEFAULT_PAGE_ID);
                    }
                    catch (Exception e2)
                    {
                        Console.WriteLine(e2.Message);
                        Console.WriteLine(e2.StackTrace);
                        return new InputHandlerResult(
                       "Something went wrong when searching the Bible, please try again later. ");
                    }
                }
            }
        }
Exemple #21
0
        private List<MessageInfo> GetMailHeader(long[] uids, bool seen = true, MessageReceived callback = null)
        {
            if (!Authed)
                throw new NotAuthenticatedException();
            lock (sequenceLock)
            {
                if (this.selectedMailbox == null)
                    throw new InvalidOperationException("No mailbox or folder currently selected.");

                string EXTRAHEADERS = "";

                if(this.supportsXGMEXT)
                    EXTRAHEADERS = "X-GM-LABELS X-GM-THRID X-GM-MSGID ";

                Dictionary<long,MessageInfo> headers = new Dictionary<long,MessageInfo>();
                Dictionary<long, string> rawResponse = new Dictionary<long, string>();
                string uidRange = Util.BuildUIDRange(uids);
                string tag = GetTag();
                string response = SendCommandGetResponse(tag + "UID FETCH " + uidRange + " (FLAGS " + EXTRAHEADERS + "BODY" +
                    (seen ? null : ".PEEK") + "[HEADER])");
                while (response.StartsWith("*"))
                {
                    MessageInfo info = new MessageInfo();
                    Match m = ImapParsing.Fetch.Match(response);
                    string builder = "";
                    if (m.Success)
                    {
                        int size = Convert.ToInt32(m.Groups[2].Value);
                        builder = GetData(size);
                        info.MessageNumber = Convert.ToInt64(m.Groups[1].Value);
                    }
                    m = ImapParsing.FetchUID.Match(response);
                    if (m.Success)
                        info.UID = Convert.ToInt64(m.Groups[1].Value);

                    info.RawHeader = builder;

                    headers.Add(info.UID, info);
                    rawResponse.Add(info.UID, response);

                    response = GetResponse();

                    //We need to go ahead and swallow this response
                    //Since we have already gathered the data from the stream
                    if (response == ")")
                        response = GetResponse();
                }

                if (!IsResponseOK(response, tag))
                    throw new BadServerResponseException(response);

                foreach (long uid in headers.Keys)
                {
                    MessageInfo info = headers[uid];
                    Match m = null;
                    response = rawResponse[uid];

                    if (this.supportsXGMEXT)
                    {
                        m = ImapParsing.FetchLabels.Match(response);
                        if (m.Success)
                        {
                            List<string> labels = Util.ParseLabels(Regex.Replace(m.Groups[1].Value, "(?!\\\\\")(\\\\)", string.Empty));

                            info.Labels = new List<string>();

                            foreach (string label in labels)
                            {
                                info.Labels.Add(Regex.Replace(label, "\"", string.Empty));
                            }
                        }

                        m = ImapParsing.FetchThreadID.Match(response);
                        if (m.Success)
                            info.ThreadID = m.Groups[1].Value;

                        m = ImapParsing.FetchMessageID.Match(response);
                        if (m.Success)
                            info.MessageID = m.Groups[1].Value;
                    }

                    m = ImapParsing.FetchFlags.Match(response);
                    if (m.Success)
                    {
                        info.Flags = m.Groups[1].Value.Split(' ').ToList();
                    }

                    info.Envelope = MessageBuilder.FromHeader(info.RawHeader);
                    info.Date = Util.ParseDateTime(info.Envelope.Headers["Date"]);

                    if (callback != null)
                        callback.Invoke(info);
                }

                return headers.Values.ToList();
            }
        }
Exemple #22
0
 public List<MessageInfo> PeekHeaders(long[] uids, MessageReceived callback)
 {
     return this.GetMessages(uids, FetchOptions.HeadersOnly, false, callback);
 }
Exemple #23
0
		/// <summary>
		/// Retrieves a set of mail messages by their unique identifier message attributes
		/// with the specified fetch option.
		/// </summary>
		/// <param name="uids">An array of unique identifiers of the mail messages to
		/// retrieve</param>
		/// <param name="options">A value from the FetchOptions enumeration which allows
		/// for fetching selective parts of a mail message.</param>
		/// <param name="seen">Set this to true to set the \Seen flag for the fetched
		/// messages on the server.</param>
		/// <param name="mailbox">The mailbox the messages will be retrieved from. If this
		/// parameter is omitted, the value of the DefaultMailbox property is used to
		/// determine the mailbox to operate on.</param>
		/// <exception cref="NotAuthenticatedException">Thrown if the method was called
		/// in a non-authenticated state, i.e. before logging into the server with
		/// valid credentials.</exception>
		/// <exception cref="BadServerResponseException">Thrown if the mail messages could
		/// not be fetched. The message property of the exception contains the error message
		/// returned by the server.</exception>
		/// <returns>An array of initialized instances of the MailMessage class representing
		/// the fetched mail messages</returns>
		/// <remarks>A unique identifier (UID) is a 32-bit value assigned to each
		/// message which uniquely identifies the message within a mailbox. No two
		/// messages in a mailbox share the the same UID.</remarks>
		/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="GetMessages-2"]/*'/>
		public List<MessageInfo> GetMessages(long[] uids, FetchOptions options,
			bool seen = true, MessageReceived callback = null) {
            if (!Authed)
                throw new NotAuthenticatedException();
            lock (sequenceLock)
            {
                if (this.selectedMailbox == null)
                    throw new InvalidOperationException("No mailbox or folder currently selected.");

                List<MessageInfo> infos = GetMailHeader(uids, seen);

                if (options == FetchOptions.HeadersOnly)
                {
                    return infos;
                }
                /* Retrieve and parse the body structure of the mail message */
                Dictionary<long,string> structures = GetBodystructure(uids);
                try
                {
                    foreach (MessageInfo info in infos)
                    {
                        Bodypart[] parts = Bodystructure.Parse(structures[info.UID]);
                            
                        foreach (Bodypart part in parts)
                        {
                            if (options != FetchOptions.Normal &&
                                part.Disposition.Type == ContentDispositionType.Attachment)
                                continue;
                            if (options == FetchOptions.TextOnly && part.Type != ContentType.Text)
                                continue;
                            /* fetch the content */
                            string content = GetBodypart(info.UID, part.PartNumber, seen);

                            info.Envelope.AddBodypart(part, content);
                        }

                        if (callback != null)
                            callback.Invoke(info);
                    }
                }
                catch (FormatException)
                {
                    throw new BadServerResponseException("Server returned erroneous " +
                        "body structure.");
                }
           
                return infos;
            }
		}
Exemple #24
0
        /// <summary>
        /// Handles the incoming messages
        /// </summary>
        /// <returns></returns>
        public async Task HandleMessagesAsync()
        {
            while (WebsocketClient.State == WebSocketState.Open)
            {
                var stream = new MemoryStream();
                WebSocketReceiveResult receiveResult;
                do
                {
                    var buffer = WebSocket.CreateClientBuffer(1024, 16);
                    receiveResult = await WebsocketClient.ReceiveAsync(buffer, CancellationToken.None);

                    stream.Write(buffer.Array ?? Array.Empty <byte>(), buffer.Offset, receiveResult.Count);
                } while (!receiveResult.EndOfMessage);

                switch (receiveResult.MessageType)
                {
                case WebSocketMessageType.Close:
                    await DisposeAsync();

                    break;

                case WebSocketMessageType.Text:
                {
                    var message  = Encoding.UTF8.GetString(stream.ToArray());
                    var document = new XmlDocument();
                    try
                    {
                        document.LoadXml(message.Trim());
                    }
                    catch
                    {
                        return;
                    }

                    switch (document.DocumentElement?.Name)
                    {
                    case "stream:features":
                        await SendAuthentication();

                        break;

                    case "success":
                        await SendIqAsync("_xmpp_bind1");

                        break;

                    case "iq":
                        if (document.DocumentElement.GetAttribute("id").Equals("_xmpp_bind1"))
                        {
                            await SendIqAsync("_xmpp_session1");
                        }

                        if (document.DocumentElement.GetAttribute("id").Equals("_xmpp_session1"))
                        {
                            await SendPresenceAsync(new Presence
                                {
                                    Status     = "",
                                    SessionId  = "",
                                    Properties = new Dictionary <string, object>()
                                });
                        }

                        break;

                    case "message":
                        await HandleMessageAsync(document);

                        break;
                    }

                    var args = new MessageReceivedEventArgs
                    {
                        Raw      = message,
                        Document = document
                    };
                    MessageReceived?.Invoke(args);
                    break;
                }
                }
            }

            Debugger.Break();
        }
Exemple #25
0
        public int CheckStates(DBUtil.UData ud, MessageReceived received, MessageToSend mes)
        {
            string b = "";
            if (received.Body.Contains("type=reply|nm="))
            {
                //TODO: Regex
                b = received.Body.Split("|"[0])[2].Split("="[0])[1].ToLower();
            }
            else
            {
                b = received.Body.ToLower();
            }
            //Console.WriteLine(b);
            switch (ud.state)
            {
                case -2: //first time user
                    {
                        if (b.Contains("nick"))
                        {
                            if (Program.gameActions.Core_Nick(b, ud.mxitid) == 0)
                            {
                                mes.AppendLine("Nick changed successfully!", System.Drawing.Color.Green, TextMarkup.Bold);
                            }
                            else
                            {
                                mes.AppendLine("Nick change unsuccessful! Usage: nick <newnick>", System.Drawing.Color.Red, TextMarkup.Bold);
                            }
                            return -2; //Stay on this screen
                        }
                        if (b == "menu")
                        {
                            return 0;
                        }
                        if (b == "help")
                        {
                            return 1;
                        }
                        return -2;
                    }
                    //break;
                case 0: //Main Menu
                    {
                        if (b.Contains(".news"))
                        {
                            Program.gameActions.Core_News(b, ud.mxitid);
                        }
                        if (b == "help")
                        {
                            return 1;
                        }
                        if (b == "1")
                        {
                            return 2;
                        }
                        if (b == "2")
                        {
                            return 3;
                        }
                        if (b == "3")
                        {
                            return 4;
                        }
                        if (b == "4")
                        {
                            return 5;
                        }
                        if (b == "5")
                        {
                            return 6;
                        }
                    }
                    break;
                case 1: //Help Menu
                    {
                        return 0;
                    }
                    //break;
                case 2:
                    {
                        if (b == "menu")
                        {
                            return 0;
                        }
                        return 2;
                    }
                case 3: //bank
                    {
                        if (b == "menu")
                        {
                            return 0;
                        }
                        if (b.Contains("with"))
                        {
                            int o = Program.gameActions.Bank_Withdraw(b, ud.mxitid);
                            if (o >= 0)
                            {
                                mes.AppendLine("NOTICE:", System.Drawing.Color.Green ,TextMarkup.Bold);
                                mes.AppendLine("You withdraw $" + o.ToString() + " from the bank", System.Drawing.Color.Green);
                            }
                            else if (o == -1)
                            {
                                mes.AppendLine("USAGE:", System.Drawing.Color.Blue, TextMarkup.Bold);
                                mes.AppendLine("Command: with <amount>", System.Drawing.Color.Blue);
                            }
                            else if (o == -2)
                            {
                                mes.AppendLine("ERROR:", System.Drawing.Color.Red, TextMarkup.Bold);
                                mes.AppendLine("You cannot withdraw negative amounts", System.Drawing.Color.Red);
                            }
                            else if (o == -3)
                            {
                                mes.AppendLine("NOTICE:", System.Drawing.Color.Red, TextMarkup.Bold);
                                mes.AppendLine("You have insufficient funds to withdraw that amount", System.Drawing.Color.Red);
                            }
                            mes.AppendLine();
                        }
                        if (b.Contains("dep"))
                        {
                            int o = Program.gameActions.Bank_Deposit(b, ud.mxitid);
                            if (o >= 0)
                            {
                                mes.AppendLine("NOTICE:", System.Drawing.Color.Green, TextMarkup.Bold);
                                mes.AppendLine("You deposit $" + o.ToString() + " into the bank", System.Drawing.Color.Green);
                            }
                            else if (o == -1)
                            {
                                mes.AppendLine("USAGE:", System.Drawing.Color.Blue, TextMarkup.Bold);
                                mes.AppendLine("Command: dep <amount>", System.Drawing.Color.Blue);
                            }
                            else if (o == -2)
                            {
                                mes.AppendLine("ERROR:", System.Drawing.Color.Red, TextMarkup.Bold);
                                mes.AppendLine("You cannot deposit negative amounts", System.Drawing.Color.Red);
                            }
                            else if (o == -3)
                            {
                                mes.AppendLine("NOTICE:", System.Drawing.Color.Red, TextMarkup.Bold);
                                mes.AppendLine("You have insufficient funds to deposit that amount", System.Drawing.Color.Red);
                            }
                            mes.AppendLine();
                        }
                        return 3;
                    }
                case 4: //tech
                    {
                        if (b == "menu")
                        {
                            return 0;
                        }
                        return 4;
                    }
                case 5: //gang
                    {
                        if (b == "menu")
                        {
                            return 0;
                        }
                        return 5;
                    }
                case 6: //streets
                    {
                        if (b == "menu")
                        {
                            return 0;
                        }
                        return 6;
                    }
            }

            return 0; //all else fails go to the menu
        }
 internal void OnMessageReceived(object sender, IChromiumEvent e)
 {
     MessageReceived?.Invoke(this, e);
 }
        private void ProcessResponse(string response)
        {
            JObject obj = null;

            try
            {
                obj = JObject.Parse(response);
            }
            catch (JsonException exc)
            {
                _logger.LogError(exc, "Failed to deserialize response", response);
                return;
            }

            _logger.LogTrace("◀ Receive {Message}", response);

            var id = obj[MessageKeys.Id]?.Value <int>();

            if (id.HasValue)
            {
                //If we get the object we are waiting for we return if
                //if not we add this to the list, sooner or later some one will come for it
                if (_callbacks.TryGetValue(id.Value, out var callback) && _callbacks.Remove(id.Value))
                {
                    if (obj[MessageKeys.Error] != null)
                    {
                        callback.TaskWrapper.TrySetException(new MessageException(callback, obj));
                    }
                    else
                    {
                        callback.TaskWrapper.TrySetResult(obj[MessageKeys.Result].Value <JObject>());
                    }
                }
            }
            else
            {
                var method = obj[MessageKeys.Method].AsString();
                var param  = obj[MessageKeys.Params];

                if (method == "Target.receivedMessageFromTarget")
                {
                    var sessionId = param[MessageKeys.SessionId].AsString();
                    if (_sessions.TryGetValue(sessionId, out var session))
                    {
                        session.OnMessage(param[MessageKeys.Message].AsString());
                    }
                }
                else if (method == "Target.detachedFromTarget")
                {
                    var sessionId = param[MessageKeys.SessionId].AsString();
                    if (_sessions.TryGetValue(sessionId, out var session) && _sessions.Remove(sessionId) && !session.IsClosed)
                    {
                        session.OnClosed();
                    }
                }
                else
                {
                    MessageReceived?.Invoke(this, new MessageEventArgs
                    {
                        MessageID   = method,
                        MessageData = param
                    });
                }
            }
        }
Exemple #28
0
 /// <summary>
 /// Raises MessageReceived event.
 /// </summary>
 /// <param name="message">Received message</param>
 protected virtual void OnMessageReceived(IScsMessage message)
 {
     MessageReceived?.Invoke(this, new MessageEventArgs(message, DateTime.Now));
 }
Exemple #29
0
 void OnReceivedMessage(RedisSubscriptionMessage message)
 {
     MessageReceived?.Invoke(this, new RedisSubscriptionReceivedEventArgs(message));
 }
Exemple #30
0
        void skype_MessageStatus(ChatMessage pMessage, TChatMessageStatus Status)
        {
            MessageEvent messageevent = new MessageEvent(pMessage, Status);

            //Now, we shoot our shit here.
            if (Status == TChatMessageStatus.cmsSending)
            {
                try
                {
                    if (!MessageReceived.Invoke(this, messageevent))
                    {
                        Logger.Log(string.Format(Utils.XOR("ତୄଛ଻ହଲଔ଎ତ଍ଥହ଒ଢ଄େଠଳଽ଻ହଲୃ଎ତ଍ଥ଻଒ଢ଄େତଳଽ଻ହଲ୆ୂତ଍ଥମ଺ଜ଄େମଣଽ଻ହ଱ଐ଎ତ଍ଥଏ଒ଢ଄େ଒ଯଛ଻ହିଓୂତ଍ଦ଎଒ଢ଄େଖୄଛ଻ହରଃୂତ଍ଥୂ଒ଢ଄େହଙଛ଻ହ଱ଐ଎ତ଍ଥୁ଒ଢ଄େ଒ଯଛ଻ହ଴ଃୂତ଍ଦ୆଒ଢ଄େ଒ଯଛ଻ହିଇୂତ଍ଥ଍଒ଢ଄େ", 619580279), pMessage.Sender.Handle, pMessage.Body.ToString().Replace("\n", "")));
                        return;
                    }
                }
                catch { }
                Logger.LogMessage(string.Format(Utils.XOR("昪昕昔昏昶昭昌昌昛昼昮昽昙映昹晉是是晉昏昶昭昶昌昛昼昮昿昙映昹晉昫昕晉昏昶昭昪昈昛昼昮昢昚映昹晉昚昿昔昏昶昭昢昈昛昼昮昲昚映昹晉昪昿昔昏昶是昈昈昛昼昮昢昚映昹晉昮昕晉昏昶昮昔昌昛昼昮昋昙映昹晉昷是昔昏昶昫晁昈昛昼昭晉昙映昹晉昛昕昔昏昶映昲昈昛昼昭晍昙映昹晉昵是昔昏昶是昈昈昛昼昭晅", 1355376248), (pMessage.Chat.Topic == "" ? pMessage.Sender.FullName : pMessage.Chat.Topic), pMessage.Sender.Handle, pMessage.Body.ToString().Replace("\n", "")));
                //invoke all stuffs
                if (pMessage.Body == "" || pMessage.Body[0].ToString() != bot.CommandDelimiter || pMessage.Body.ToString() == bot.CommandDelimiter)
                {
                    //pMessage.Chat.SendMessage(InvalidMessage.Invoke(this, messageevent));
                    return;
                }
                //Check the incoming command against the existing command list.
                List <string> args = Utils.ParseParameters(pMessage.Body.ToString());
                if (args[0] == string.Format(Utils.XOR("嬡嬨嬜嬘嬾嬧嬾孅嬩嬤嬦嬧嬕嬧嬵孁嬧嬨嬜嬘嬾嬥孅孅嬩嬤嬦嬲嬽嬝嬵孁嬤嬸嬜嬘嬾嬡孍孍", 1244617584), bot.CommandDelimiter))
                {
                    //Execute defined help message.
                    try
                    {
                        pMessage.Chat.SendMessage(HelpMessage.Invoke(this, messageevent));
                    }
                    catch { }
                    for (int i = 0; i < commands.help.Count; i++)
                    {
                        pMessage.Chat.SendMessage(bot.CommandDelimiter + commands.help[i]);
                    }
                    return;
                }
                if (commands.sendhandlers.ContainsKey(string.Format("{0}", args[0].Substring(1))))
                {
                    Logger.Log(string.Format(Utils.XOR("", 132183750), pMessage.Sender.Handle, pMessage.Body.ToString().Replace("\n", "")));
                    //Create a new instance of the message handler.
                    new Thread(new ThreadStart(delegate()
                    {
                        BotCommandSent v = Activator.CreateInstance(commands.sendhandlers[args[0].Substring(1)]) as BotCommandSent;
                        if (v.NumberOfArgs + 1 != args.Count)
                        {
                            pMessage.Chat.SendMessage(bot.CommandDelimiter + "Usage: " + v.Usage); return;
                        }
                        string output = v.Handle(pMessage, args.ToArray());
                        if (output != null && output != "")
                        {
                            pMessage.Chat.SendMessage(output);
                        }
                    })).Start();
                    return;
                }
                else
                {
                    try
                    {
                        //Didn't do jack shit. Send help message invoke?
                        //pMessage.Chat.SendMessage(InvalidMessage.Invoke(this, messageevent));
                    }
                    catch { }
                }
            }
            if (Status == TChatMessageStatus.cmsReceived) //Make sure the message is receiving
            {
                try
                {
                    if (!MessageReceived.Invoke(this, messageevent))
                    {
                        Logger.Log(string.Format(Utils.XOR("ତୄଛ଻ହଲଔ଎ତ଍ଥହ଒ଢ଄େଠଳଽ଻ହଲୃ଎ତ଍ଥ଻଒ଢ଄େତଳଽ଻ହଲ୆ୂତ଍ଥମ଺ଜ଄େମଣଽ଻ହ଱ଐ଎ତ଍ଥଏ଒ଢ଄େ଒ଯଛ଻ହିଓୂତ଍ଦ଎଒ଢ଄େଖୄଛ଻ହରଃୂତ଍ଥୂ଒ଢ଄େହଙଛ଻ହ଱ଐ଎ତ଍ଥୁ଒ଢ଄େ଒ଯଛ଻ହ଴ଃୂତ଍ଦ୆଒ଢ଄େ଒ଯଛ଻ହିଇୂତ଍ଥ଍଒ଢ଄େ", 619580279), pMessage.Sender.Handle, pMessage.Body.ToString().Replace("\n", "")));
                        return;
                    }
                }
                catch { }
                Logger.LogMessage(string.Format(Utils.XOR("昪昕昔昏昶昭昌昌昛昼昮昽昙映昹晉是是晉昏昶昭昶昌昛昼昮昿昙映昹晉昫昕晉昏昶昭昪昈昛昼昮昢昚映昹晉昚昿昔昏昶昭昢昈昛昼昮昲昚映昹晉昪昿昔昏昶是昈昈昛昼昮昢昚映昹晉昮昕晉昏昶昮昔昌昛昼昮昋昙映昹晉昷是昔昏昶昫晁昈昛昼昭晉昙映昹晉昛昕昔昏昶映昲昈昛昼昭晍昙映昹晉昵是昔昏昶是昈昈昛昼昭晅", 1355376248), (pMessage.Chat.Topic == "" ? pMessage.Sender.FullName : pMessage.Chat.Topic), pMessage.Sender.Handle, pMessage.Body.ToString().Replace("\n", "")));
                //If the user is blocked then just f**k him up and ignore ALL shit.
                if (pMessage.Sender.IsBlocked)
                {
                    return;
                }
                //If the message sender is set to ignore, then just ignore the F**K outta him.
                if (Ignore.Contains(pMessage.Sender.Handle))
                {
                    try
                    {
                        pMessage.Chat.SendMessage(IgnoredMessage.Invoke(this, messageevent));
                    }
                    catch { }
                    return;
                }
                if (pMessage.Body[0].ToString() != bot.CommandDelimiter || pMessage.Body.ToString() == bot.CommandDelimiter)
                {
                    //pMessage.Chat.SendMessage(InvalidMessage.Invoke(this, messageevent));
                    return;
                }
                //Check the incoming command against the existing command list.
                List <string> args = Utils.ParseParameters(pMessage.Body.ToString());
                if (args[0] == string.Format(Utils.XOR("嬡嬨嬜嬘嬾嬧嬾孅嬩嬤嬦嬧嬕嬧嬵孁嬧嬨嬜嬘嬾嬥孅孅嬩嬤嬦嬲嬽嬝嬵孁嬤嬸嬜嬘嬾嬡孍孍", 1244617584), bot.CommandDelimiter))
                {
                    //Execute defined help message.
                    try
                    {
                        pMessage.Chat.SendMessage(HelpMessage.Invoke(this, messageevent));
                    }
                    catch { }
                    for (int i = 0; i < commands.help.Count; i++)
                    {
                        pMessage.Chat.SendMessage(bot.CommandDelimiter + commands.help[i]);
                    }
                    return;
                }
                if (commands.handlers.ContainsKey(string.Format("{0}", args[0].Substring(1))))
                {
                    Logger.Log(string.Format(Utils.XOR("", 132183750), pMessage.Sender.Handle, pMessage.Body.ToString().Replace("\n", "")));
                    //Create a new instance of the message handler.
                    new Thread(new ThreadStart(delegate()
                    {
                        BotCommand v = Activator.CreateInstance(commands.handlers[args[0].Substring(1)]) as BotCommand;
                        if (v.NumberOfArgs + 1 != args.Count)
                        {
                            pMessage.Chat.SendMessage(bot.CommandDelimiter + v.Usage); return;
                        }
                        string output = v.Handle(pMessage, args.ToArray());
                        if (output != null && output != "")
                        {
                            pMessage.Chat.SendMessage(output);
                        }
                    })).Start();
                    return;
                }
                else
                {
                    try
                    {
                        //Didn't do jack shit. Send help message invoke?
                        pMessage.Chat.SendMessage(InvalidMessage.Invoke(this, messageevent));
                    }
                    catch { }
                }
            }
        }
Exemple #31
0
        public void StartListening(MessageReceived CallBack)
        {
            //STORE THE CALLBACK
            mCallback = CallBack;

            //CREATE A NEW THREAD USING OUR THREADSTART METHOD MAKE SURE ITS A BACKGROUND THREAD SO WHEN WE EXIT IT DOES TO
            mThread = new System.Threading.Thread(ThreadStart);
            mRunning = true;
            mThread.IsBackground = true;

            //START LISTENING FOR SYSLOG PACKETS
            mThread.Start();
        }
Exemple #32
0
 private void OnMessageReceived(T message)
 {
     MessageReceived?.Invoke(this, new ConnectionMessageEventArgs <T>(this, message));
 }
Exemple #33
0
 protected virtual void OnMessageReceived(MessageReceievedEventArgs e)
 {
     MessageReceived?.Invoke(this, e);
 }
Exemple #34
0
 protected void RaiseMessageReceived(T message)
 {
     MessageReceived?.Invoke(this, message);
 }
Exemple #35
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="message"></param>
 private void RaiseMessageReceived(IMessage message)
 {
     MessageReceived?.Invoke(this, message);
 }
 private void OnMessageReceived(RocketMessage rocketmessage)
 {
     MessageReceived?.Invoke(rocketmessage);
 }
Exemple #37
0
        private async Task ReaderAsync()
        {
            try
            {
                if (string.Empty != LastEventId)
                {
                    if (Hc.DefaultRequestHeaders.Contains("Last-Event-Id"))
                    {
                        Hc.DefaultRequestHeaders.Remove("Last-Event-Id");
                    }

                    Hc.DefaultRequestHeaders.TryAddWithoutValidation("Last-Event-Id", LastEventId);
                }
                using (HttpResponseMessage response = await Hc.GetAsync(Uri, HttpCompletionOption.ResponseHeadersRead))
                {
                    response.EnsureSuccessStatusCode();
                    if (response.Headers.TryGetValues("content-type", out IEnumerable <string> ctypes) || ctypes?.Contains("text/event-stream") == false)
                    {
                        throw new ArgumentException("Specified URI does not return server-sent events");
                    }

                    Stream = await response.Content.ReadAsStreamAsync();

                    using (var sr = new StreamReader(Stream))
                    {
                        string evt  = DefaultEventType;
                        string id   = string.Empty;
                        var    data = new StringBuilder(string.Empty);

                        while (true)
                        {
                            string line = await sr.ReadLineAsync();

                            if (line == string.Empty)
                            {
                                // double newline, dispatch message and reset for next
                                if (data.Length > 0)
                                {
                                    MessageReceived?.Invoke(this, new EventSourceMessageEventArgs(data.ToString().Trim(), evt, id));
                                }
                                data.Clear();
                                id  = string.Empty;
                                evt = DefaultEventType;
                                continue;
                            }
                            else if (line.First() == ':')
                            {
                                // Ignore comments
                                continue;
                            }

                            int    dataIndex = line.IndexOf(':');
                            string field;
                            if (dataIndex == -1)
                            {
                                dataIndex = line.Length;
                                field     = line;
                            }
                            else
                            {
                                field      = line.Substring(0, dataIndex);
                                dataIndex += 1;
                            }

                            string value = line.Substring(dataIndex).Trim();

                            switch (field)
                            {
                            case "event":
                                // Set event type
                                evt = value;
                                break;

                            case "data":
                                // Append a line to data using a single \n as EOL
                                data.Append($"{value}\n");
                                break;

                            case "retry":
                                // Set reconnect delay for next disconnect
                                int.TryParse(value, out ReconnectDelay);
                                break;

                            case "id":
                                // Set ID
                                LastEventId = value;
                                id          = LastEventId;
                                break;

                            default:
                                // Ignore other fields
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Disconnect(ex);
            }
        }
Exemple #38
0
 private void ClientStreamReceived(object sender, MessageReceivedEventArgs args)
 {
     MessageReceived?.Invoke(this, new MessageReceivedEventArgs(args.Metadata, args.ContentLength, args.DataStream));
 }
Exemple #39
0
 void WebSocket_MessageReceived(object sender, MessageReceivedEventArgs e)
 {
     MessageReceived?.Invoke(e.Message);
 }
Exemple #40
0
        private void SocketReceiveThreadLoop()
        {
            try
            {
                ISLogger.Write("Socket receive thread started");
                byte[] header = new byte[4];
                while (!cancelToken.IsCancellationRequested)
                {
                    int hRem = 4;
                    int hPos = 0;
                    do
                    {
                        int hIn = tcpSocket.Receive(header, hPos, hRem, 0);   //make sure we read all 4 bytes of header
                        hPos += hIn;
                        hRem -= hIn;
                    } while (hRem > 0);
                    int pSize = BitConverter.ToInt32(header, 0);

                    if (pSize > Settings.ClientMaxPacketSize)
                    {
                        OnConnectionError(new Exception("Connection error: Server sent invalid packet size of " + pSize), ServerSocketState.ConnectionError);
                        return;
                    }
                    int dRem = pSize;
                    int bPos = 4;
                    do
                    {
                        int bIn = tcpSocket.Receive(socketBuffer, bPos, dRem, 0);
                        bPos += bIn;
                        dRem  = pSize - bPos + 4;
                    } while (dRem > 0);
                    MessageType cmd = (MessageType)socketBuffer[4];
                    switch (cmd)
                    {
                    case MessageType.Input:
                    {
                        InputMessage msg = InputMessage.FromBytes(socketBuffer);
                        InputReceived?.Invoke(this, msg.Input);
                        break;
                    }

                    case MessageType.ServerOK:
                        ISLogger.Write("Server sent OK");
                        SetState(ServerSocketState.Connected);
                        MessageReceived?.Invoke(this, cmd);
                        break;

                    case MessageType.SetClipboardText:
                        ProcessCbCopy(ClipboardSetTextMessage.FromBytes(socketBuffer));
                        break;

                    case MessageType.FileTransferPart:
                        FileTransferPartMessage fileMsg = FileTransferPartMessage.FromBytes(ref socketBuffer);
                        ReadFilePart(fileMsg);
                        break;

                    default:
                        MessageReceived?.Invoke(this, cmd);
                        break;
                    }
                }
            }catch (ObjectDisposedException)
            {
            }catch (Exception ex)
            {
                if (!disconnecting)
                {
                    disconnecting = true;
                }
                else
                {
                    return;
                }

                if (cancelToken.IsCancellationRequested)
                {
                    return;
                }

                if (!ex.Message.Contains("WSACancelBlockingCall"))
                {
                    //ISLogger.Write("Serversocket error: " + ex.Message);
                }
                OnConnectionError(ex, ServerSocketState.ConnectionError);
            }
        }
Exemple #41
0
        private void EventReceivedCallback(object sender, EventReceivedEventArgs e)
        {
            try
            {
                switch (e.Event.MessageType)
                {
                case MessageType.UserControlMessage:
                    UserControlMessage userControlMessage = (UserControlMessage)e.Event;
                    if (userControlMessage.EventType != UserControlMessageType.PingRequest)
                    {
                        break;
                    }
                    this.WriteProtocolControlMessage((RtmpEvent) new UserControlMessage(UserControlMessageType.PingResponse, userControlMessage.Values));
                    break;

                case MessageType.CommandAmf3:
                case MessageType.DataAmf0:
                case MessageType.CommandAmf0:
                    Command command    = (Command)e.Event;
                    Method  methodCall = command.MethodCall;
                    object  obj1       = methodCall.Parameters.Length == 1 ? methodCall.Parameters[0] : (object)methodCall.Parameters;
                    if (methodCall.Name == "_result" && !(obj1 is AcknowledgeMessageExt))
                    {
                        AcknowledgeMessageExt acknowledgeMessageExt = new AcknowledgeMessageExt();
                        object obj2 = obj1;
                        acknowledgeMessageExt.Body = obj2;
                        AcknowledgeMessageExt result = acknowledgeMessageExt;
                        this._callbackManager.SetResult(command.InvokeId, result);
                        break;
                    }
                    if (methodCall.Name == "_result")
                    {
                        AcknowledgeMessageExt result = (AcknowledgeMessageExt)obj1;
                        this._callbackManager.SetResult(command.InvokeId, result);
                        break;
                    }
                    if (methodCall.Name == "_error")
                    {
                        ErrorMessage errorMessage = (ErrorMessage)obj1;
                        this._callbackManager.SetException(command.InvokeId, errorMessage != null ? (Exception) new InvocationException(errorMessage) : (Exception) new InvocationException());
                        break;
                    }
                    if (methodCall.Name == "receive")
                    {
                        AsyncMessageExt message = (AsyncMessageExt)obj1;
                        if (message == null)
                        {
                            break;
                        }
                        object obj2;
                        message.Headers.TryGetValue("DSSubtopic", out obj2);
                        string dsSubtopic = obj2 as string;
                        string clientId   = message.ClientId;
                        this.WrapCallback((Action)(() =>
                        {
                            if (this.MessageReceived == null)
                            {
                                return;
                            }
                            MessageReceived?.Invoke(this, new MessageReceivedEventArgs(clientId, dsSubtopic, message));
                        }));
                        break;
                    }
                    int num = methodCall.Name == "onstatus" ? 1 : 0;
                    break;
                }
            }
            catch (ClientDisconnectedException ex)
            {
                this.Close();
            }
        }
Exemple #42
0
        public static void HandleMessage(Entity parent, string text, string name, ushort hue, MessageType type, byte font, bool unicode = false, string lang = null)
        {
            if (ProfileManager.Current != null && ProfileManager.Current.OverrideAllFonts)
            {
                font    = ProfileManager.Current.ChatFont;
                unicode = ProfileManager.Current.OverrideAllFontsIsUnicode;
            }

            switch (type)
            {
            case MessageType.Spell:

            {
                //server hue color per default
                if (!string.IsNullOrEmpty(text) && SpellDefinition.WordToTargettype.TryGetValue(text, out SpellDefinition spell))
                {
                    if (ProfileManager.Current != null && ProfileManager.Current.EnabledSpellFormat && !string.IsNullOrWhiteSpace(ProfileManager.Current.SpellDisplayFormat))
                    {
                        StringBuilder sb = new StringBuilder(ProfileManager.Current.SpellDisplayFormat);
                        sb.Replace("{power}", spell.PowerWords);
                        sb.Replace("{spell}", spell.Name);
                        text = sb.ToString().Trim();
                    }

                    //server hue color per default if not enabled
                    if (ProfileManager.Current != null && ProfileManager.Current.EnabledSpellHue)
                    {
                        if (spell.TargetType == TargetType.Beneficial)
                        {
                            hue = ProfileManager.Current.BeneficHue;
                        }
                        else if (spell.TargetType == TargetType.Harmful)
                        {
                            hue = ProfileManager.Current.HarmfulHue;
                        }
                        else
                        {
                            hue = ProfileManager.Current.NeutralHue;
                        }
                    }
                }

                goto case MessageType.Label;
            }

            case MessageType.Focus:
            case MessageType.Whisper:
            case MessageType.Yell:
            case MessageType.Regular:
            case MessageType.Label:

                if (parent == null)
                {
                    break;
                }

                TextOverhead msg = CreateMessage(text, hue, font, unicode, type);
                msg.Owner = parent;

                if (parent is Item it && !it.OnGround)
                {
                    msg.X = Mouse.LastClickPosition.X;
                    msg.Y = Mouse.LastClickPosition.Y;

                    Gump gump = UIManager.GetGump <Gump>(it.Container);

                    if (gump is PaperDollGump paperDoll)
                    {
                        msg.X -= paperDoll.ScreenCoordinateX;
                        msg.Y -= paperDoll.ScreenCoordinateY;
                        paperDoll.AddText(msg);
                    }
                    else if (gump is ContainerGump container)
                    {
                        msg.X -= container.ScreenCoordinateX;
                        msg.Y -= container.ScreenCoordinateY;
                        container.AddText(msg);
                    }
                    else
                    {
                        Entity ent = World.Get(it.RootContainer);

                        if (ent == null || ent.IsDestroyed)
                        {
                            break;
                        }

                        var trade = UIManager.GetGump <TradingGump>(ent);

                        if (trade == null)
                        {
                            Item item = ent.Items.FirstOrDefault(s => s.Graphic == 0x1E5E);

                            if (item == null)
                            {
                                break;
                            }

                            trade = UIManager.Gumps.OfType <TradingGump>().FirstOrDefault(s => s.ID1 == item || s.ID2 == item);
                        }

                        if (trade != null)
                        {
                            msg.X -= trade.ScreenCoordinateX;
                            msg.Y -= trade.ScreenCoordinateY;
                            trade.AddText(msg);
                        }
                        else
                        {
                            Log.Warn("Missing label handler for this control: 'UNKNOWN'. Report it!!");
                        }
                    }
                }

                parent.AddMessage(msg);

                break;

            case MessageType.Emote:
                if (parent == null)
                {
                    break;
                }

                msg = CreateMessage($"*{text}*", hue, font, unicode, type);

                parent.AddMessage(msg);

                break;

            case MessageType.Command:

            case MessageType.Encoded:
            case MessageType.System:
            case MessageType.Party:
            case MessageType.Guild:
            case MessageType.Alliance:

                break;

            default:
                if (parent == null)
                {
                    break;
                }

                msg = CreateMessage(text, hue, font, unicode, type);

                parent.AddMessage(msg);

                break;
            }

            MessageReceived.Raise(new UOMessageEventArgs(parent, text, name, hue, type, font, unicode, lang), parent);
        }
Exemple #43
0
 public void TriggerMessageReceived(MessageEventArgs args)
 {
     MessageReceived?.Invoke(this, args);
 }
 /// <summary>
 /// Raises MessageReceived event.
 /// </summary>
 /// <param name="message">Received message</param>
 /// <param name="receivedTimestamp">Message reception timestamp</param>
 protected virtual void OnMessageReceived(IScsMessage message, DateTime receivedTimestamp) => MessageReceived?.Invoke(this, new MessageEventArgs(message, receivedTimestamp));
Exemple #45
0
        private async Task OnPacketReceived(Packet msg)
        {
            try
            {
                switch (msg.PacketType)
                {
                case PacketType.CONNACK:
                    Log($"[{_instaApi.GetLoggedUser().UserName}] " + "Received CONNACK");
                    ConnectionData.UpdateAuth(((FbnsConnAckPacket)msg).Authentication);
                    await RegisterMqttClient();

                    break;

                case PacketType.PUBLISH:
                    Log($"[{_instaApi.GetLoggedUser().UserName}] " + "Received PUBLISH");
                    var publishPacket = (PublishPacket)msg;
                    if (publishPacket.Payload == null)
                    {
                        throw new Exception($"{nameof(PushClient)}: Publish packet received but payload is null");
                    }
                    if (publishPacket.QualityOfService == QualityOfService.AtLeastOnce)
                    {
                        await FbnsPacketEncoder.EncodePacket(PubAckPacket.InResponseTo(publishPacket), _outboundWriter);
                    }

                    var payload = DecompressPayload(publishPacket.Payload);
                    var json    = Encoding.UTF8.GetString(payload);
                    Log($"[{_instaApi.GetLoggedUser().UserName}] " + $"MQTT json: {json}");
                    switch (Enum.Parse(typeof(TopicIds), publishPacket.TopicName))
                    {
                    case TopicIds.Message:
                        var message = JsonConvert.DeserializeObject <PushReceivedEventArgs>(json);
                        message.Json     = json;
                        message.InstaApi = _instaApi;
                        MessageReceived?.Invoke(this, message);
                        break;

                    case TopicIds.RegResp:
                        await OnRegisterResponse(json);

                        StartKeepAliveLoop();
                        break;

                    default:
                        Log($"[{_instaApi.GetLoggedUser().UserName}] " + $"Unknown topic received: {publishPacket.TopicName}");
                        break;
                    }

                    break;

                case PacketType.PUBACK:
                    Log($"[{_instaApi.GetLoggedUser().UserName}] " + "Received PUBACK");
                    _waitingForPubAck = false;
                    break;

                // todo: PingResp never arrives even though data was received. Decoder problem?
                case PacketType.PINGRESP:
                    Log($"[{_instaApi.GetLoggedUser().UserName}] " + "Received PINGRESP");
                    break;

                default: return;
                    //throw new NotSupportedException($"Packet type {msg.PacketType} is not supported.");
                }
            }
            catch (Exception ex)
            {
                PrintException("SendPing", ex);
                Shutdown();
            }
        }
            private NetworkStream stream = null; // Network stream for sending and receiving data

            #endregion Fields

            #region Constructors

            // Constructor
            public TCPConnection(TcpClient client, MessageReceived OnMessageReceived, bool isHost)
            {
                this.isHost = isHost;
                this.OnMessageReceived += OnMessageReceived;

                this.client = client;
                this.stream = this.client.GetStream();

                this.receiverThread = new Thread(this.Receive);
                this.receiverThread.Start();
            }
        public override InputHandlerResult handleInput(UserSession user_session, MessageReceived message_recieved)
        {
            string input = extractReply(message_recieved);
            Console.WriteLine("User with ID: " + user_session.user_profile.id + " Entered: " + input);
            //get reply
            string curr_user_page = user_session.current_menu_loc;
            InputHandlerResult output = handleDisplayMessageLinks(
                user_session,
                input,
                "Your input was invalid. You message has been sent already but please click Back/Main to continue");

            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            output = handleStdNavLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            /*output = handleStdPageLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;*/

            MenuManager mm = MenuManager.getInstance();
            //for now we assume this. must correct this later
            VerseMenuPage vmp = (VerseMenuPage)mm.menu_def.getMenuPage(curr_user_page);
            List<MenuOptionItem> options = vmp.options;
            foreach (MenuOptionItem option in options)
            {
                if (option.link_val.Equals(input))
                    return new InputHandlerResult(
                         InputHandlerResult.NEW_MENU_ACTION,
                         option.select_action,
                         InputHandlerResult.DEFAULT_PAGE_ID);
            }

            if (input.Count() > MAX_MESSAGE_LENGTH)
            {
                return new InputHandlerResult(
                   "Your message is too long, please keep it less than " + MAX_MESSAGE_LENGTH + " characters.\r\n"); //invalid choice
            }
            else if (input.Trim().Equals(""))
            {
                return new InputHandlerResult(
                   "You entered a blank message. please try again.\r\n"); //blank input
            }
            else if (input.Trim().ToUpper().Equals(MessageThreadHandler.REPLY))
            {
                return new InputHandlerResult(
                    InputHandlerResult.DO_NOTHING_ACTION,
                    InputHandlerResult.DEFAULT_MENU_ID,
                    InputHandlerResult.DEFAULT_MENU_ID); //blank input
            }
            else
            {
                try
                {
                    long thread_id = long.Parse(user_session.getVariable(MessageInboxHandler.CURRENTLY_VIEWING_TRHEAD));
                    VerseMessageThread vmt = VerseThreadManager.getInstance().getVerseMessageThread(thread_id);
                    if (vmt != null)
                    {
                        //check the current state of the friendship before along the user to send the message.
                        if (user_session.friend_manager.getFriendStatus(vmt.user_created_id) == FriendRelation.FRIEND_BLOCKED_BY_YOU)
                        {
                            return new InputHandlerResult(
                                InputHandlerResult.DISPLAY_MESSAGE,
                                InputHandlerResult.DEFAULT_MENU_ID,
                                "You blocked the original sender of this message. As a result you cant send them a message until you re-add you as a friend. You have to use their buddy code and send a friend request to them again. Because you blocked them they can't add you.");
                        }
                        else if (user_session.friend_manager.getFriendStatus(vmt.user_created_id) == FriendRelation.FRIEND_BLOCKED_YOU)
                        {
                            return new InputHandlerResult(
                                   InputHandlerResult.DISPLAY_MESSAGE,
                                   InputHandlerResult.DEFAULT_MENU_ID,
                                   "The original sender of this message blocked you as a buddy. This means that you cant send them any messages. The only way to be unblocked is for them to resend a friend request to you.");
                        }
                        user_session.verse_messaging_manager.addMessageToThread(vmt, input);
                    }
                    //if vmt is null there is something wrong. need to handle this because we might delete the thread while someone is viewing it.
                    return new InputHandlerResult(
                            InputHandlerResult.BACK_WITHOUT_INIT_MENU_ACTION,
                            InputHandlerResult.DEFAULT_MENU_ID,
                            InputHandlerResult.DEFAULT_PAGE_ID);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                    return new InputHandlerResult(
                   "Something went wrong when trying to send your message, please try again later. "); //invalid choice
                }
            }
        }
Exemple #48
0
        public override InputHandlerResult handleInput(UserSession user_session, MessageReceived message_recieved)
        {
            string input = extractReply(message_recieved);
            //Console.WriteLine("in input handler: " + input);
            Console.WriteLine("User with ID: " + user_session.user_profile.id + " Entered: " + input);
            //get reply
            string curr_user_page = user_session.current_menu_loc;

            InputHandlerResult output = handleStdNavLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            MenuManager mm = MenuManager.getInstance();
            //for now we assume this. must correct this later
            VerseMenuPage vmp = (VerseMenuPage)mm.menu_def.getMenuPage(curr_user_page);
            List<MenuOptionItem> options = vmp.options;
            foreach (MenuOptionItem option in options)
            {
                if (option.link_val.Equals(input))
                    return new InputHandlerResult(
                         InputHandlerResult.NEW_MENU_ACTION,
                         option.select_action,
                         InputHandlerResult.DEFAULT_PAGE_ID);
            }

            //now handle input
            input = input.Trim();
            if (input.Equals(""))
            {
                return new InputHandlerResult(
            "Invalid entry...Please enter a valid input (e.g. 'John 3:16' or '1 John 1:9' or read the help section for more information"); //invalid choice
            }
            input = input.Replace('.', ':');
            Verse start_verse = null;
            Verse end_verse = null;
            if (input.Contains('-'))
            {
                String[] start_end = input.Split('-');

                start_verse = getStartingVerse(user_session.user_profile.getDefaultTranslationId(), start_end[0]);
                if (start_verse == null)
                {
                    return new InputHandlerResult(
                                "Invalid entry...Please enter a valid input (e.g. 'John 3:16' or '1 John 1:9'"); //invalid choice
                }
                if (start_end.Count() >= 2)
                {
                    end_verse = getEndingVerse(user_session.user_profile.getDefaultTranslationId(), start_verse, start_end[1]);
                }
            }
            else
            {
                start_verse = getStartingVerse(user_session.user_profile.getDefaultTranslationId(), input);
            }
            user_session.deleteVariable("Browse.verse_section");

            try
            {
                if (end_verse == null)
                    end_verse = start_verse;
                VerseSection vs = new VerseSection(start_verse, end_verse);
                user_session.setVariable("Browse.verse_section", vs);
                //now this is one big hack
                user_session.setVariable("Browse.directSelect", true);
            }
            catch (XInvalidVerseSection e)
            {
                return new InputHandlerResult(e.Message); //invalid choice
            }

            return new InputHandlerResult(
                     InputHandlerResult.NEW_MENU_ACTION,
                     vmp.input_item.target_page,
                     InputHandlerResult.DEFAULT_PAGE_ID);
        }
Exemple #49
0
 public void OnMessageReceived(MessageReceived callback)
 {
     messageReceived = callback;
 }
        public override InputHandlerResult handleInput(UserSession user_session, MessageReceived message_recieved)
        {
            string input = extractReply(message_recieved);
            Console.WriteLine("User with ID: " + user_session.user_profile.id + " Entered: " + input);
            //get reply
            string curr_user_page = user_session.current_menu_loc;

            MenuManager mm = MenuManager.getInstance();
            MenuPage mp = mm.menu_def.getMenuPage(curr_user_page);
            //for now we assume this. must correct this later
            DynMenuPage dmp = (DynMenuPage)mm.menu_def.getMenuPage(curr_user_page);

            //handle extra commands
            InputHandlerResult output = dmp.dynamic_set.handleExtraCommandInput(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            output = handleStdNavLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            output = handleStdPageLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            output = handleRefreshLink(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            output = handleVerseTagLikeLinks(user_session, input);
            if (output.action != (InputHandlerResult.UNDEFINED_MENU_ACTION))
                return output;

            List<MenuOptionItem> options = mp.getOptionList(user_session);
            string output_var = dmp.output_var;
            //this is a waste, if we do change input then its found so we can already return.
            input = dmp.dynamic_set.parseInput(input, user_session);
            foreach (MenuOptionItem option in options)
            {
                if (option.is_valid && (option.link_val.Equals(input) || option.menu_option_id.Equals(input)))
                {

                    user_session.setVariable(output_var, input);
                    user_session.setVariable(TAGGED_VERSE_CURRENT_PAGE, (user_session.current_menu_page));
                    return new InputHandlerResult(
                        InputHandlerResult.NEW_MENU_ACTION,
                        option.select_action,
                        InputHandlerResult.DEFAULT_PAGE_ID);
                }
            }

            /*else if (mp.GetType().Name == "MxitTestApp.OptionMenuPage")
            {
                OptionMenuPage omp = (OptionMenuPage)mm.menu_def.getMenuPage(curr_user_page);
                List<MenuOptionItem> options = omp.options;
                foreach (MenuOptionItem option in options)
                {
                    if (option.link_val.Equals(input))
                    {
                        user_session.setVariable("SELECTED_BOOK_ID", input);
                        return new InputHandlerResult(
                            InputHandlerResult.NEW_MENU_ACTION,
                            option.select_action,
                            InputHandlerResult.DEFAULT_PAGE_ID);
                    }
                }
            }*/

            //handle back or home here.

            return new InputHandlerResult(
                    "Invalid entry...Please enter a valid input"); //invalid choice
        }
Exemple #51
0
 protected override void NewMessage(string tagId,NdefLibrary.Ndef.NdefMessage message)
 {
     var nfcMessage = new MessageReceived(tagId, message, this);
     _messenger.Publish(nfcMessage);
 }
Exemple #52
0
 public void LogMessage(string message)
 {
     MessageReceived?.Invoke(message);
 }
        private async Task ReceiveMessageTaskAsync(MessageReceived messageReceivedHandler) {
            Task<BrokeredMessage> t = Task<BrokeredMessage>.Factory.FromAsync(this.subClient.BeginReceive, subClient.EndReceive, null);
            BrokeredMessage brokeredMessage = await t;
            string message;
            if (brokeredMessage != null) {
                try {
                    message = brokeredMessage.GetBody<string>();

                    // Remove message from subscription
                    brokeredMessage.Complete();

                    messageReceivedHandler(message);
                } catch (Exception) {
                    // Indicate a problem, unlock message in subscription
                    brokeredMessage.Abandon();
                }
            }
        }
Exemple #54
0
 protected void OnMessageReceived(IpcMessage message) => MessageReceived?.Invoke(message);
Exemple #55
0
        void EventReceivedCallback(object sender, EventReceivedEventArgs e)
        {
            switch (e.Event.MessageType)
            {
            case MessageType.UserControlMessage:
                var m = (UserControlMessage)e.Event;
                if (m.EventType == UserControlMessageType.PingRequest)
                {
                    WriteProtocolControlMessage(new UserControlMessage(UserControlMessageType.PingResponse, m.Values));
                }
                break;

            case MessageType.DataAmf3:
#if DEBUG
                // have no idea what the contents of these packets are.
                // study these packets if we receive them.
                System.Diagnostics.Debugger.Break();
#endif
                break;

            case MessageType.CommandAmf3:
            case MessageType.DataAmf0:
            case MessageType.CommandAmf0:
                var command = (Command)e.Event;
                var call    = command.MethodCall;

                var param = call.Parameters.Length == 1 ? call.Parameters[0] : call.Parameters;
                switch (call.Name)
                {
                case "_result":
                    // unwrap Flex class, if present
                    var ack = param as AcknowledgeMessage;
                    callbackManager.SetResult(command.InvokeId, ack != null ? ack.Body : param);
                    break;

                case "_error":
                    // unwrap Flex class, if present
                    var error = param as ErrorMessage;
                    callbackManager.SetException(command.InvokeId, error != null ? new InvocationException(error) : new InvocationException());
                    break;

                case "receive":
                    var message = param as AsyncMessage;
                    if (message == null)
                    {
                        break;
                    }

                    object subtopicObject;
                    message.Headers.TryGetValue(AsyncMessageHeaders.Subtopic, out subtopicObject);

                    var dsSubtopic = subtopicObject as string;
                    var clientId   = message.ClientId;
                    var body       = message.Body;

                    WrapCallback(() => MessageReceived?.Invoke(this, new MessageReceivedEventArgs(clientId, dsSubtopic, body)));
                    break;

                case "onstatus":
                    System.Diagnostics.Debug.Print("received status");
                    break;

                default:
#if DEBUG
                    System.Diagnostics.Debug.Print($"unknown rtmp command: {call.Name}");
                    System.Diagnostics.Debugger.Break();
#endif
                    break;
                }

                break;
            }
        }
Exemple #56
0
		/// <summary>
		/// Retrieves a set of mail messages by their unique identifier message attributes.
		/// </summary>
		/// <param name="uids">An array of unique identifiers of the mail messages to
		/// retrieve</param>
		/// <param name="seen">Set this to true to set the \Seen flag for the fetched
		/// messages on the server.</param>
		/// <param name="mailbox">The mailbox the messages will be retrieved from. If this
		/// parameter is omitted, the value of the DefaultMailbox property is used to
		/// determine the mailbox to operate on.</param>
		/// <exception cref="NotAuthenticatedException">Thrown if the method was called
		/// in a non-authenticated state, i.e. before logging into the server with
		/// valid credentials.</exception>
		/// <exception cref="BadServerResponseException">Thrown if the mail messages could
		/// not be fetched. The message property of the exception contains the error message
		/// returned by the server.</exception>
		/// <returns>An array of initialized instances of the MailMessage class representing
		/// the fetched mail messages</returns>
		/// <remarks>A unique identifier (UID) is a 32-bit value assigned to each
		/// message which uniquely identifies the message within a mailbox. No two
		/// messages in a mailbox share the the same UID.</remarks>
		/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="GetMessages-1"]/*'/>
		public List<MessageInfo> GetMessages(long[] uids, bool seen = true, MessageReceived callback = null) {
			return GetMessages(uids, FetchOptions.Normal, seen, callback);
		}
            private TcpListener listener = null; // Listener to listen for connection requests

            #endregion Fields

            #region Constructors

            // Constructor
            public TCPConnector(MessageReceived OnMessageReceived, bool isHost)
            {
                this.isHost = isHost;
                this.OnMessageReceived += OnMessageReceived;

                listener = new TcpListener(IPAddress.Any, NetworkComponents.gamePort);

                if (this.isHost)
                    this.listener.Start();
            }
Exemple #58
0
 private void HandleReceiveMessage(string username, string message)
 {
     MessageReceived?.Invoke(this, new MessageReceivedEventArgs(username, message));
 }
		void ReportConsumerTime(DateTime startTime, TimeSpan receiveDuration, TimeSpan consumeDuration,
		                        IReceiveContext context)
		{
			var message = new MessageReceived
				{
					Context = context,
					ReceivedAt = startTime,
					ReceiveDuration = receiveDuration,
					ConsumeDuration = consumeDuration,
				};

			_eventChannel.Send(message);
		}
Exemple #60
0
 public void Invoke(WindowMessageEventArgs args) => MessageReceived?.Invoke(this, args);