Exemple #1
0
        public async Task ReturnMessageToSourceQueue()
        {
            var state = new State();
            IEndpointInstance endpoint = null;

            try
            {
                endpoint = await StartEndpoint(state).ConfigureAwait(false);

                var messageToSend = new MessageToSend();
                await endpoint.SendLocal(messageToSend).ConfigureAwait(false);

                var messageId = await GetMessageId().ConfigureAwait(false);

                state.ShouldHandlerThrow = false;

                await ErrorQueue.ReturnMessageToSourceQueue(
                    errorQueueName : errorQueueName,
                    messageId : messageId)
                .ConfigureAwait(false);

                Assert.IsTrue(await state.Signal.Task.ConfigureAwait(false));
            }
            finally
            {
                if (endpoint != null)
                {
                    await endpoint.Stop().ConfigureAwait(false);
                }
            }
        }
        public async Task Write()
        {
            var endpointConfiguration = new EndpointConfiguration(endpointName);
            var encryptionService     = new RijndaelEncryptionService(
                encryptionKeyIdentifier: "2015-10",
                key: Convert.FromBase64String("gdDbqRpqdRbTs3mhdZh9qCaDaxJXl+e6"));

            endpointConfiguration.EnableMessagePropertyEncryption(
                encryptionService: encryptionService,
                encryptedPropertyConvention: propertyInfo =>
            {
                return(propertyInfo.Name.EndsWith("EncryptedProperty"));
            }
                );

            var conventions = endpointConfiguration.Conventions();
            var typesToScan = TypeScanner.NestedTypes <HeaderWriterEncryption>();

            endpointConfiguration.SetTypesToScan(typesToScan);
            endpointConfiguration.UseTransport(new LearningTransport());
            endpointConfiguration.RegisterMessageMutator(new Mutator());

            var endpointInstance = await Endpoint.Start(endpointConfiguration)
                                   .ConfigureAwait(false);

            var messageToSend = new MessageToSend
            {
                EncryptedProperty1 = "String 1",
                EncryptedProperty2 = "String 2"
            };
            await endpointInstance.SendLocal(messageToSend)
            .ConfigureAwait(false);

            ManualResetEvent.WaitOne();
        }
Exemple #3
0
        public async Task Write()
        {
            var endpointConfiguration = new EndpointConfiguration(endpointName);

            endpointConfiguration.RijndaelEncryptionService("2015-10", Encoding.ASCII.GetBytes("gdDbqRpqdRbTs3mhdZh9qCaDaxJXl+e6"));
            var conventions = endpointConfiguration.Conventions();

            conventions.DefiningEncryptedPropertiesAs(info => info.Name.StartsWith("EncryptedProperty"));
            var typesToScan = TypeScanner.NestedTypes <HeaderWriterEncryption>();

            endpointConfiguration.SetTypesToScan(typesToScan);
            endpointConfiguration.SendFailedMessagesTo("error");
            endpointConfiguration.EnableInstallers();
            endpointConfiguration.UsePersistence <InMemoryPersistence>();
            endpointConfiguration.RegisterComponents(
                registration: components =>
            {
                components.ConfigureComponent <Mutator>(DependencyLifecycle.InstancePerCall);
            });
            var endpointInstance = await Endpoint.Start(endpointConfiguration)
                                   .ConfigureAwait(false);

            var messageToSend = new MessageToSend
            {
                EncryptedProperty1 = "String 1",
                EncryptedProperty2 = "String 2"
            };
            await endpointInstance.SendLocal(messageToSend)
            .ConfigureAwait(false);

            ManualResetEvent.WaitOne();
        }
    public void AddNewMessage(InputField message)
    {
        MessageToSend messageToSend = new MessageToSend
        {
            ChannelId = _fixedChannel,
            Message   = message.text,
            SocketId  = _pusher.SocketID,
            UserId    = _fixedUser
        };

        TheDispatcher.RunOnMainThread(async() =>
        {
            var result = await _api.SendMessage(messageToSend);
            if (result.IsSuccessStatusCode)
            {
                Debug.Log("Message sent to server successfully");
            }
            else
            {
                Debug.Log($"Error: { result.StatusCode } - { await result.Content.ReadAsStringAsync() } ");
            }
        });

        message.text = string.Empty;
    }
        public override void addLinksToMessageFromList(
            UserSession us,
            List<MenuOptionItem> list,
            MessageToSend ms)
        {
            int count = (us.current_menu_page * MenuDefinition.PAGE_ITEM_COUNT) + 1;

            int starting_index = us.current_menu_page * MenuDefinition.PAGE_ITEM_COUNT;
            FriendRelationMenuOptionItem an_option;
            FriendRelation fr;
            for (int i = starting_index;
                i < list.Count && i < starting_index + MenuDefinition.PAGE_ITEM_COUNT;
                i++)
            {
                an_option = (FriendRelationMenuOptionItem)list.ElementAt(i);
                fr = an_option.fr;
                ms.Append("* " + UserNameManager.getInstance().getUserName(long.Parse(an_option.display_text)));
                ms.Append(" ");
                ms.Append(createMessageLink(MENU_LINK_NAME, "[REMOVE]", "DELETE_" + an_option.display_text));
                ms.Append(" ");
                ms.Append(createMessageLink(MENU_LINK_NAME, "[BLOCK]", "BLOCK_" + an_option.display_text));
                ms.Append(" ");
                ms.Append("\r\n");
                count++;
            }
        }
        public override MessageToSend getOutputScreenMessage(
            UserSession us,
            MenuPage mp,
            MessageToSend ms,
            InputHandlerResult ihr)
        {
            ms.Append(MessageBuilder.Elements.CreateClearScreen());
            if (!mp.GetType().FullName.Equals("MxitTestApp.OptionMenuPage"))//TODO: Should be constant
                throw new Exception("Invalid menu page passed into getScreen method ");

            OptionMenuPage omp = (OptionMenuPage)mp;
            ms.Append(omp.title + "\r\n", TextMarkup.Bold);
            if (ihr.action == InputHandlerResult.INVALID_MENU_ACTION
                && ihr.error != null)
            {
                ms.Append((string)ihr.error + "\r\n");
            }
            else
            {
                ms.Append(parseMessage(us, omp.message) + "\r\n");
            }
            List<MenuOptionItem> options = omp.options;
            int count =1 ;
            foreach (MenuOptionItem option in options)
            {
                ms.Append(createMessageLink(MENU_LINK_NAME, count + ") ", option.link_val));
                ms.Append(option.display_text + "\r\n");
                count++;
            }
            appendBackMainLinks(us,  ms);
            appendMessageConfig(true, ms);
            return ms;
            //return output;
        }
        public void addQuickFilterLinksToMessageFromList(
            UserSession us,
            MessageToSend ms)
        {
            List<char> starting_chars = us.friend_manager.getStartingCharacters();
            //.. starting_chars
            starting_chars.Sort();
            if (starting_chars.Count() > 1)
            {
                int i = 0;

                foreach (var a_char in starting_chars)
                {
                    if (i == 0)
                    {
                        i++;
                        ms.Append("\r\nFilter - ");
                        ms.Append(createMessageLink(MENU_LINK_NAME, "[ALL]", FriendHandler.FILTER_LIST + "ALL"));
                        ms.Append(" ");
                    }
                    ms.Append(createMessageLink(MENU_LINK_NAME, "[" + a_char.ToString().ToUpper() + "]", FriendHandler.FILTER_LIST + a_char));
                    ms.Append(" ");
                }
                ms.Append("\r\n\r\n");
            }
        }
Exemple #8
0
        public async Task Write()
        {
            var endpointConfiguration = new EndpointConfiguration(endpointName);
            var dataBus = endpointConfiguration.UseDataBus <FileShareDataBus>();

            dataBus.BasePath(@"..\..\..\storage");
            var typesToScan = TypeScanner.NestedTypes <HeaderWriterDataBusConvention>();

            endpointConfiguration.SetTypesToScan(typesToScan);
            endpointConfiguration.UsePersistence <LearningPersistence>();
            endpointConfiguration.UseTransport <LearningTransport>();
            var conventions = endpointConfiguration.Conventions();

            conventions.DefiningDataBusPropertiesAs(property =>
            {
                return(property.Name.StartsWith("LargeProperty"));
            });
            endpointConfiguration.RegisterMessageMutator(new Mutator());

            var endpointInstance = await Endpoint.Start(endpointConfiguration)
                                   .ConfigureAwait(false);

            var messageToSend = new MessageToSend
            {
                LargeProperty1 = new byte[10],
                LargeProperty2 = new byte[10]
            };
            await endpointInstance.SendLocal(messageToSend)
            .ConfigureAwait(false);

            ManualResetEvent.WaitOne();
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
        public override void addLinksToMessageFromList(
            UserSession us,
            List<MenuOptionItem> list,
            MessageToSend ms)
        {
            ms.AppendLine();
            int count = (us.current_menu_page * MenuDefinition.PAGE_ITEM_COUNT) + 1;

            int starting_index = us.current_menu_page * MenuDefinition.PAGE_ITEM_COUNT;
            FriendRelationMenuOptionItem an_option;
            FriendRelation fr;

            List<long> recipient_list = null;
            if (us.hasVariable(ChooseFriendHandler.RECIPIENT_LIST))
            {
                recipient_list = (List<long>)us.getVariableObject(ChooseFriendHandler.RECIPIENT_LIST);
            }
            for (int i = starting_index;
                i < list.Count && i < starting_index + MenuDefinition.PAGE_ITEM_COUNT;
                i++)
            {
                an_option = (FriendRelationMenuOptionItem)list.ElementAt(i);
                fr = an_option.fr;
                if (recipient_list == null || (recipient_list != null && !recipient_list.Contains(long.Parse(an_option.display_text))))
                {

                    ms.Append(" " + UserNameManager.getInstance().getUserName(long.Parse(an_option.display_text)) + " ");
                    ms.Append(createMessageLink(MENU_LINK_NAME, "[+]", "ADD_" + an_option.display_text));
                    /*ms.Append(" ");
                    ms.Append(createMessageLink(MENU_LINK_NAME, "[-]", "REMOVE_" + an_option.display_text));*/
                    ms.Append("\r\n");
                }
                count++;
            }
        }
        public override void addLinksToMessageFromList(
            UserSession us,
            List<MenuOptionItem> list,
            MessageToSend ms)
        {
            int count = (us.current_menu_page * MenuDefinition.PAGE_ITEM_COUNT) + 1;

            int starting_index = us.current_menu_page * MenuDefinition.PAGE_ITEM_COUNT;
            MenuOptionItem an_option;
            String summary = "";
            for (int i = starting_index;
                i < list.Count && i < starting_index + MenuDefinition.PAGE_ITEM_COUNT;
                i++)
            {
              /*  an_option = (MenuOptionItem)list.ElementAt(i);
                ms.Append(createMessageLink(MENU_LINK_NAME, count + ") ", an_option.link_val));
                ms.Append(an_option.display_text);
                String start_verse = "";//an_option.fvr.start_verse;
                Verse verse_summ = Verse_Handler.getStartingVerse(us.user_profile.getDefaultTranslationId(), an_option.fvr.start_verse);
                //NetBible method should not be used because this is not always a NET Bible
                if (an_option.is_valid && verse_summ != null)
                {
                    summary = BibleContainer.getSummaryOfVerse(verse_summ, SUMMARY_WORD_COUNT);
                    ms.Append(" - " + summary + "...");
                }
                else
                {
                    ms.Append(" - The verse is not available in this translation", TextMarkup.Bold);
                }
                //ms.Append(createMessageLink(MENU_LINK_NAME, "[x]", "del:"+ count));
                ms.Append("\r\n");
                count++;*/
            }
        }
        public void addThreadLinks(
            UserSession us,
            MessageToSend ms)
        {
            int current_page = Int32.Parse(us.getVariable(MessageInboxHandler.CURRENT_MESSAGE_THREAD));
            int count = (current_page * THREAD_COUNT_PER_PAGE) + 1;
            VerseMessageThread vmt;
            int starting_index = current_page * THREAD_COUNT_PER_PAGE;
            List<VerseMessageThread> threads = us.verse_messaging_manager.getParticipatingThreads();
            if (threads.Count() == 0)
            {
                ms.Append("Your inbox is empty");
                return;
            }

            for (int i = starting_index;
                i < threads.Count && i < starting_index + THREAD_COUNT_PER_PAGE;
                i++)
            {
                vmt = threads.ElementAt(i);
                if (vmt == null)
                    continue;
                appendMessageThread(us, ms, vmt);
            }
            appendPaginateLinks(us,  ms, threads.Count, THREAD_COUNT_PER_PAGE);
        }
Exemple #12
0
        public void Write()
        {
            var busConfiguration = new BusConfiguration();

            busConfiguration.EndpointName(endpointName);
            var typesToScan = TypeScanner.NestedTypes <HeaderWriterError>(typeof(ConfigErrorQueue));

            busConfiguration.TypesToScan(typesToScan);
            busConfiguration.EnableInstallers();
            busConfiguration.UsePersistence <InMemoryPersistence>();
            busConfiguration.RegisterComponents(c => c.ConfigureComponent <Mutator>(DependencyLifecycle.InstancePerCall));
            using (var bus = (UnicastBus)Bus.Create(busConfiguration).Start())
            {
                bus.Builder.Build <BusNotifications>()
                .Errors
                .MessageSentToErrorQueue
                .Subscribe(e =>
                {
                    var headerText = HeaderWriter.ToFriendlyString <HeaderWriterError>(e.Headers);
                    headerText     = BehaviorCleaner.CleanStackTrace(headerText);
                    headerText     = StackTraceCleaner.CleanStackTrace(headerText);
                    SnippetLogger.Write(text: headerText, suffix: "Error", version: "5");
                    ManualResetEvent.Set();
                });
                var messageToSend = new MessageToSend();
                bus.SendLocal(messageToSend);
                ManualResetEvent.WaitOne();
            }
        }
Exemple #13
0
        public void ReturnMessageToSourceQueuePS()
        {
            var state = new State();

            using (var bus = StartBus(state))
            {
                var messageToSend = new MessageToSend();
                bus.SendLocal(messageToSend);
                var msmqMessageId = GetMsmqMessageId();
                state.ShouldHandlerThrow = false;
                var currentDirectory = Path.GetDirectoryName(GetType().Assembly.CodeBase.Remove(0, 8));
                var scriptPath       = Path.Combine(currentDirectory, "msmq/ErrorQueue.ps1");
                using (var powerShell = PowerShell.Create())
                {
                    powerShell.AddScript(File.ReadAllText(scriptPath));
                    powerShell.Invoke();
                    var command = powerShell.AddCommand("ReturnMessageToSourceQueue");
                    command.AddParameter("ErrorQueueMachine", Environment.MachineName);
                    command.AddParameter("ErrorQueueName", errorQueueName);
                    command.AddParameter("MessageId", msmqMessageId);
                    command.Invoke();
                }
                state.ResetEvent.WaitOne();
            }
        }
Exemple #14
0
        public void Write()
        {
            var busConfiguration = new BusConfiguration();

            busConfiguration.EndpointName(endpointName);
            var dataBus = busConfiguration.UseDataBus <FileShareDataBus>();

            dataBus.BasePath(@"..\..\..\storage");
            var typesToScan = TypeScanner.NestedTypes <HeaderWriterDataBusProperty>(typeof(ConfigErrorQueue));

            busConfiguration.TypesToScan(typesToScan);
            busConfiguration.EnableInstallers();
            busConfiguration.UsePersistence <InMemoryPersistence>();
            busConfiguration.RegisterComponents(
                registration: components =>
            {
                components.ConfigureComponent <Mutator>(DependencyLifecycle.InstancePerCall);
            });
            using (var bus = Bus.Create(busConfiguration).Start())
            {
                var messageToSend = new MessageToSend
                {
                    LargeProperty1 = new DataBusProperty <byte[]>(new byte[10]),
                    LargeProperty2 = new DataBusProperty <byte[]>(new byte[10])
                };
                bus.SendLocal(messageToSend);
                ManualResetEvent.WaitOne();
            }
        }
Exemple #15
0
        public async Task <IActionResult> PostMessage(int userId, MessageToSend message)
        {
            var loggedUser = await _repo.GetUser(userId);

            var loggedUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (loggedUserId != loggedUser.Id)
            {
                return(Unauthorized());
            }

            var recipient = await _repo.GetUser(message.RecipientId);

            if (recipient == null)
            {
                return(BadRequest("couldn't find the recipient"));
            }

            message.SenderId = userId;

            var messageToSave = _mapper.Map <Message>(message);

            _repo.Add(messageToSave);

            if (!await _repo.SaveAll())
            {
                throw new Exception("sending message failed on save");
            }

            var messageToReturn = _mapper.Map <MessageToReturnDto>(messageToSave);

            // return CreatedAtRoute("GetMessage", new { messageId = messageToSave.Id }, messageToReturn);
            return(CreatedAtAction("GetMessage", new { userId, messageId = messageToSave.Id }, messageToReturn));
        }
        public void Initialize(Algorithm algo)
        {
            int count = 0;
            // Process Values

            Process pp1 = new Process();

            pp1.ProcessId    = 1;
            pp1.InitialValue = p1;
            pp1.Balance      = p1;
            pp1.ColorCode    = ConsoleColor.White;

            Process pp2 = new Process();

            pp2.ProcessId    = 2;
            pp2.InitialValue = p2;
            pp2.Balance      = p2;
            pp2.ColorCode    = ConsoleColor.White;

            algo.Processes.Add(pp1);
            algo.Processes.Add(pp2);


            algo.totalTimeSlots       = totaltime;
            algo.RedInitiatorPId      = redprocessid;
            algo.RedInitiatorTimeSlot = redtime;

            algo.InitializeChannels(MessageToSend.ToList <Message>());
        }
Exemple #17
0
        public async Task Write()
        {
            var endpointConfiguration = new EndpointConfiguration(endpointName);
            var dataBus = endpointConfiguration.UseDataBus <FileShareDataBus>();

            dataBus.BasePath(@"..\..\..\storage");
            var typesToScan = TypeScanner.NestedTypes <HeaderWriterDataBusConvention>();

            endpointConfiguration.SetTypesToScan(typesToScan);
            endpointConfiguration.SendFailedMessagesTo("error");
            endpointConfiguration.EnableInstallers();
            endpointConfiguration.Conventions().DefiningDataBusPropertiesAs(x => x.Name.StartsWith("LargeProperty"));
            endpointConfiguration.UsePersistence <InMemoryPersistence>();
            endpointConfiguration.RegisterComponents(c => c.ConfigureComponent <Mutator>(DependencyLifecycle.InstancePerCall));

            var endpointInstance = await Endpoint.Start(endpointConfiguration)
                                   .ConfigureAwait(false);

            var messageToSend = new MessageToSend
            {
                LargeProperty1 = new byte[10],
                LargeProperty2 = new byte[10]
            };
            await endpointInstance.SendLocal(messageToSend)
            .ConfigureAwait(false);

            ManualResetEvent.WaitOne();
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
Exemple #18
0
        public async Task Write()
        {
            var endpointConfiguration = new EndpointConfiguration(endpointName);
            var dataBus = endpointConfiguration.UseDataBus <FileShareDataBus>();

            dataBus.BasePath(@"..\..\..\storage");
            var typesToScan = TypeScanner.NestedTypes <HeaderWriterDataBusProperty>();

            endpointConfiguration.SetTypesToScan(typesToScan);
            endpointConfiguration.UsePersistence <LearningPersistence>();
            endpointConfiguration.UseTransport <LearningTransport>();
            endpointConfiguration.RegisterComponents(
                registration: components =>
            {
                components.ConfigureComponent <Mutator>(DependencyLifecycle.InstancePerCall);
            });

            var endpointInstance = await Endpoint.Start(endpointConfiguration)
                                   .ConfigureAwait(false);

            var messageToSend = new MessageToSend
            {
                LargeProperty1 = new DataBusProperty <byte[]>(new byte[10]),
                LargeProperty2 = new DataBusProperty <byte[]>(new byte[10])
            };
            await endpointInstance.SendLocal(messageToSend)
            .ConfigureAwait(false);

            ManualResetEvent.WaitOne();
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
        public override void ShowGUI(List <ActionParameter> parameters)
        {
            parameterID = Action.ChooseParameterGUI("Object to affect:", parameters, parameterID, ParameterType.GameObject);
            if (parameterID >= 0)
            {
                constantID   = 0;
                linkedObject = null;
            }
            else
            {
                linkedObject = (GameObject)EditorGUILayout.ObjectField("Object to affect:", linkedObject, typeof(GameObject), true);

                constantID   = FieldToID(linkedObject, constantID);
                linkedObject = IDToField(linkedObject, constantID, false);
            }

            messageToSend = (MessageToSend)EditorGUILayout.EnumPopup("Message to send:", messageToSend);
            if (messageToSend == MessageToSend.Custom)
            {
                customMessage = EditorGUILayout.TextField("Method name:", customMessage);

                sendValue = EditorGUILayout.Toggle("Pass integer to method?", sendValue);
                if (sendValue)
                {
                    customValue = EditorGUILayout.IntField("Integer to send:", customValue);
                }
            }

            affectChildren     = EditorGUILayout.Toggle("Send to children too?", affectChildren);
            ignoreWhenSkipping = EditorGUILayout.Toggle("Ignore when skipping?", ignoreWhenSkipping);

            AfterRunningOption();
        }
        public async Task Write()
        {
            var endpointConfiguration = new EndpointConfiguration(endpointName);
            var dataBus = endpointConfiguration.UseDataBus <FileShareDataBus>();

            dataBus.BasePath(@"..\..\..\storage");
            var typesToScan = TypeScanner.NestedTypes <HeaderWriterDataBusProperty>();

            endpointConfiguration.SetTypesToScan(typesToScan);
            endpointConfiguration.UseTransport(new LearningTransport());
            endpointConfiguration.RegisterMessageMutator(new Mutator());

            var endpointInstance = await Endpoint.Start(endpointConfiguration)
                                   .ConfigureAwait(false);

            var messageToSend = new MessageToSend
            {
                LargeProperty1 = new DataBusProperty <byte[]>(new byte[10]),
                LargeProperty2 = new DataBusProperty <byte[]>(new byte[10])
            };
            await endpointInstance.SendLocal(messageToSend)
            .ConfigureAwait(false);

            ManualResetEvent.WaitOne();
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
Exemple #21
0
        private async Task <string> GetChannelId(MessageToSend message)
        {
            if (!string.IsNullOrEmpty(message.ChannelId))
            {
                return(message.ChannelId);
            }
            if (!string.IsNullOrEmpty(message.ChannelName))
            {
                //could open channel if not available, but thats outside the scope of this bot for now, so we'll let it fail
                var channel = Client.Channels.Single(c => c.name == message.ChannelName);
                if (channel != null)
                {
                    return(channel.id);
                }
            }
            ;
            var dmchannel = Client.DirectMessages.SingleOrDefault(dm => dm.user == message.UserId);

            if (dmchannel != null)
            {
                return(dmchannel.id);
            }

            var res = await OpenUserConversation(message.UserId);

            //skulle gjerne ha oppdatert  dm-cache her, men har ikke enkel tilgang på objektet
            return(res.id);
        }
        public async Task <IActionResult> Send([FromBody] MessageToSend message)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            int messageId = await SaveMessage(message.Subject, message.Body);

            IEnumerable <Recipient> recipients = await SaveRecipients(message.Recipients);

            foreach (Recipient recipient in recipients)
            {
                Correspondence correspondence =
                    await SendMessage(
                        new EmailAddress(_emailSender.Address, _emailSender.Name),
                        new EmailAddress(recipient.Email),
                        message.Subject,
                        message.Body);

                correspondence.MessageId   = messageId;
                correspondence.RecipientId = recipient.Id;

                _correspondenceRepository.Add(correspondence);
            }

            await _correspondenceRepository.UnitOfWork.SaveChangesAsync();

            return(CreatedAtAction(nameof(Show), new { messageId }, await GetSentMessageById(messageId)));
        }
Exemple #23
0
        public void Write()
        {
            var busConfiguration = new BusConfiguration();

            busConfiguration.EndpointName(endpointName);
            busConfiguration.RijndaelEncryptionService("key1", Encoding.ASCII.GetBytes("gdDbqRpqdRbTs3mhdZh9qCaDaxJXl+e6"));
            var conventions = busConfiguration.Conventions();

            conventions.DefiningEncryptedPropertiesAs(info => info.Name.StartsWith("EncryptedProperty"));
            var typesToScan = TypeScanner.NestedTypes <HeaderWriterEncryption>(typeof(ConfigErrorQueue));

            busConfiguration.TypesToScan(typesToScan);
            busConfiguration.EnableInstallers();
            busConfiguration.UsePersistence <InMemoryPersistence>();
            busConfiguration.RegisterComponents(
                registration: components =>
            {
                components.ConfigureComponent <Mutator>(DependencyLifecycle.InstancePerCall);
            });
            using (var bus = Bus.Create(busConfiguration).Start())
            {
                var messageToSend = new MessageToSend
                {
                    EncryptedProperty1 = "String 1",
                    EncryptedProperty2 = "String 2"
                };
                bus.SendLocal(messageToSend);
                ManualResetEvent.WaitOne();
            }
        }
Exemple #24
0
        public async Task Write()
        {
            var endpointConfiguration = new EndpointConfiguration(endpointName);

#pragma warning disable 618
            endpointConfiguration.RijndaelEncryptionService("2015-10", Convert.FromBase64String("gdDbqRpqdRbTs3mhdZh9qCaDaxJXl+e6"));
#pragma warning restore 618
            var conventions = endpointConfiguration.Conventions();
#pragma warning disable 618
            conventions.DefiningEncryptedPropertiesAs(info => info.Name.StartsWith("EncryptedProperty"));
#pragma warning restore 618
            var typesToScan = TypeScanner.NestedTypes <HeaderWriterEncryption>();
            endpointConfiguration.SetTypesToScan(typesToScan);
            endpointConfiguration.UsePersistence <LearningPersistence>();
            endpointConfiguration.UseTransport <LearningTransport>();
            endpointConfiguration.RegisterComponents(
                registration: components =>
            {
                components.ConfigureComponent <Mutator>(DependencyLifecycle.InstancePerCall);
            });
            var endpointInstance = await Endpoint.Start(endpointConfiguration)
                                   .ConfigureAwait(false);

            var messageToSend = new MessageToSend
            {
                EncryptedProperty1 = "String 1",
                EncryptedProperty2 = "String 2"
            };
            await endpointInstance.SendLocal(messageToSend)
            .ConfigureAwait(false);

            ManualResetEvent.WaitOne();
        }
        public async Task CreateQueues()
        {
            var state = new State();
            IEndpointInstance endpoint = null;

            try
            {
                await CreateEndpointQueues.CreateQueuesForEndpoint(endpointName, includeRetries : true)
                .ConfigureAwait(false);

                await QueueCreationUtils.CreateQueue(
                    queueName : errorQueueName)
                .ConfigureAwait(false);

                await QueueCreationUtils.CreateQueue(
                    queueName : auditQueueName)
                .ConfigureAwait(false);

                endpoint = await StartEndpoint(state).ConfigureAwait(false);

                var messageToSend = new MessageToSend();
                await endpoint.SendLocal(messageToSend).ConfigureAwait(false);

                Assert.IsTrue(await state.Signal.Task.ConfigureAwait(false));
            }
            finally
            {
                if (endpoint != null)
                {
                    await endpoint.Stop().ConfigureAwait(false);
                }
            }
        }
Exemple #26
0
        public IEnumerable <object> HandleAndSpawnMany(MessageToSend message)
        {
            yield return(new RespondToSender(new Response()));

            yield return(new NotResponding());

            yield return(new DelayedResponse(new NotResponding(), TimeSpan.FromMinutes(1)));
        }
        protected void SendMessage(SignallingMessage message)
        {
            message.SourceAddress             = LocalAddress;
            message.SourceControlPlaneElement = ControlPlaneElementType;

            OnUpdateState("[OUT] " + message);
            MessageToSend?.Invoke(this, message);
        }
 public IActionResult Send([FromForm] MessageToSend message)
 {
     service.SendMessage(message);
     return(RedirectToAction("Index", new RequestMessages()
     {
         ChannelId = message.ChannelId, ChannelSecret = message.ChannelSecret
     }));
 }
        /// <summary>
        /// Sends a MessageToSend to a chatID or user.
        /// </summary>
        public async Task <MessageResponse> SendMessageAsync(MessageToSend message)
        {
            await InitAsync();

            var result = await DoRequest <MessageResponse>("sendMessage", message);

            return(result);
        }
Exemple #30
0
        public ActionResult SendMessage(MessageToSend msg)
        {
            var twilio       = new TwilioRestClient(AccountSid, AuthToken);
            var messageModel = twilio.SendMessage(destinatario, msg.to, msg.body);

            ViewBag.temp = messageModel;
            return(View("Index"));
        }
Exemple #31
0
        private async Task SendComicsAsync(Subscription subscriptionType)
        {
            using (var db = new BotDBContext())
            {
                var clients = (from c in db.Clients
                               join sub in db.Subscriptions on c.Subscription equals sub.Id
                               where sub.SubsctiptionType == (int)subscriptionType
                               select c.ChatId
                               ).Distinct();

                MessageToSend message = (subscriptionType == Subscription.Oglaf) ? GetOglafPicture() : GetXKCDPicture();

                foreach (var client in clients)
                {
                    var lastPostedKey = (from cli in db.Clients
                                         join sub in db.Subscriptions on cli.Subscription equals sub.Id
                                         where cli.ChatId == client && sub.SubsctiptionType == (int)subscriptionType
                                         orderby sub.Id descending
                                         select new
                    {
                        LTK = sub.LastPostedKey,
                        SUBID = sub.Id
                    }
                                         ).First();

                    if (message.Title.Equals(lastPostedKey.LTK))
                    {
                        continue;
                    }

                    DatabaseInteractions.Subscription subToUpdate = db.Subscriptions.Where(x => x.Id == lastPostedKey.SUBID).First();
                    string newHash = message.Title;
                    subToUpdate.LastPostedKey = newHash;
                    db.Update(subToUpdate);
                    //db.Subscriptions.Where(x => x.Id == lastPostedKey.SUBID).First().LastPostedKey = message.Title.GetHashCode().ToString();

                    try
                    {
                        await _bot.SendTextMessageAsync(client, message.Title.ToUpper());

                        await _bot.SendTextMessageAsync(client, message.SubTitle);

                        await _bot.SendPhotoAsync(client, new InputOnlineFile(message.Image));
                    }
                    catch (ChatNotFoundException e)
                    {
                        TraceError.Info(e.Message);
                        var clientsRecords = db.Clients.Where(c => c.ChatId == client).ToList();
                        TraceError.Info("Client Recs to remove: " + string.Join(",", clientsRecords.Select(c => c.ChatId)));
                        var subscriptionsToRemove = db.Subscriptions.Where(x => clientsRecords.Select(o => o.Subscription).Contains(x.Id));
                        TraceError.Info("Subscription Recs to remove: " + string.Join(",", subscriptionsToRemove.Select(s => s.SubsctiptionType.ToString())));
                        db.Subscriptions.RemoveRange(subscriptionsToRemove);
                        db.Clients.RemoveRange(clientsRecords);
                    }
                }
                await db.SaveChangesAsync();
            }
        }
 public void appendExtraCommandLinks(String extra_commands, MessageToSend ms)
 {
     if (!(extra_commands == ""))
     {
         //TODO Complete this to split on | and add different commands
         ms.Append(createMessageLink(MENU_LINK_NAME, extra_commands, extra_commands.ToUpper()));
         ms.Append("\r\n");
     }
 }
 public async Task <HttpResponseMessage> SendMessage(MessageToSend message)
 {
     return(await _restService.MakeRequest(new Request
     {
         Data = message,
         Path = Routes.Chat.SendMessage,
         Method = HttpMethod.Post
     }));
 }
        //in here we should rather call a this method and from here call the implemented output screen
        //message method so that we can do common things in here. anyway too late now.
        public override MessageToSend getOutputScreenMessage(
            UserSession us,
            MenuPage mp,
            MessageToSend ms,
            InputHandlerResult ihr)
        {
            ms.Append(MessageBuilder.Elements.CreateClearScreen());
            if (!mp.GetType().FullName.Equals("MxitTestApp.DynMenuPage"))//TODO: Should be constant
                throw new Exception("Invalid menu page passed into getScreen method ");

            DynMenuPage dmp = (DynMenuPage)mp;
            ms.Append(dmp.title + "\r\n", TextMarkup.Bold);
            if (ihr.action == InputHandlerResult.CONF_PAGE_ACTION
                 && ihr.message != null)
            {
                ms.Append(ihr.message + "\r\n");
                ms.Append(createMessageLink(MENU_LINK_NAME, "Y", "Yes"));
                ms.Append(" | ");
                ms.Append(createMessageLink(MENU_LINK_NAME, "N", "No"));
            }
            else
            {
                if (ihr.action == InputHandlerResult.INVALID_MENU_ACTION
                && ihr.error != null)
                {
                    ms.Append((string)ihr.error + "\r\n");
                }
                else
                {
                    ms.Append(parseMessage(us, dmp.message) + "\r\n");
                }
                /*List<MenuOptionItem> options = dmp.options;
                int count =1 ;
                foreach (MenuOptionItem option in options)
                {
                    ms.Append(createMessageLink(MENU_LINK_NAME, count + ") ", option.link_val));
                    ms.Append(option.display_text + "\r\n");
                    count++;
                }*/
                List<MenuOptionItem> dyn_options = dmp.dynamic_set.getOptionList(us);
                if (dyn_options.Count() == 0)
                {
                    String empty_msg = dmp.dynamic_set.getListEmptyMessage();
                    if (empty_msg != null && empty_msg != "")
                        ms.Append(dmp.dynamic_set.getListEmptyMessage() + "\r\n");
                }
                addLinksToMessageFromList(us, dyn_options,  ms);

                appendPaginateLinks(us, ms, dyn_options.Count);
                appendExtraCommandLinks(dmp.dynamic_set.getExtraCommandString(), ms);
                appendBackMainLinks(us, ms);
                appendMessageConfig(true,  ms);
            }
            return ms;
            //return output;
        }
Exemple #35
0
        public async Task CreateQueues_Powershell(string delayedDeliveryMethod)
        {
            var randomName     = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
            var endpointName   = $"createqueues-powershell-{randomName}";
            var errorQueueName = $"createqueueserror-powershell-{randomName}";
            var auditQueueName = $"createqueuesaudit-powershell-{randomName}";

            var state = new State();
            IEndpointInstance endpoint = null;

            try
            {
                var scriptPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "QueueCreation/QueueCreation.ps1");
                using (var powerShell = PowerShell.Create())
                {
                    powerShell.AddScript(File.ReadAllText(scriptPath));
                    powerShell.Invoke();
                    var command = powerShell.AddCommand("CreateQueuesForEndpoint");
                    command.AddParameter("EndpointName", endpointName);
                    command.AddParameter("IncludeRetries");
                    command.AddParameter("DelayedDeliveryMethod", delayedDeliveryMethod);
                    command.Invoke();

                    command = powerShell.AddCommand("CreateQueue");
                    command.AddParameter("QueueName", errorQueueName);
                    command.Invoke();

                    command = powerShell.AddCommand("CreateQueue");
                    command.AddParameter("QueueName", auditQueueName);
                    command.Invoke();
                }

                endpoint = await StartEndpoint(state, endpointName, errorQueueName, auditQueueName, delayedDeliveryMethod).ConfigureAwait(false);

                var messageToSend = new MessageToSend();
                await endpoint.SendLocal(messageToSend).ConfigureAwait(false);

                Assert.IsTrue(await state.Signal.Task.ConfigureAwait(false));
            }
            finally
            {
                if (endpoint != null)
                {
                    await endpoint.Stop().ConfigureAwait(false);
                }

                await DeleteEndpointQueues.DeleteQueuesForEndpoint(endpointName, includeRetries : true, delayedDeliveryMethod : delayedDeliveryMethod)
                .ConfigureAwait(false);

                await QueueDeletionUtils.DeleteQueue(errorQueueName)
                .ConfigureAwait(false);

                await QueueDeletionUtils.DeleteQueue(auditQueueName)
                .ConfigureAwait(false);
            }
        }
        public override void ShowGUI(List <ActionParameter> parameters)
        {
            isPlayer = EditorGUILayout.Toggle("Send to Player?", isPlayer);
            if (isPlayer)
            {
                if (KickStarter.settingsManager != null && KickStarter.settingsManager.playerSwitching == PlayerSwitching.Allow)
                {
                    playerParameterID = ChooseParameterGUI("Player ID:", parameters, playerParameterID, ParameterType.Integer);
                    if (playerParameterID < 0)
                    {
                        playerID = ChoosePlayerGUI(playerID, true);
                    }
                }
            }
            else
            {
                parameterID = Action.ChooseParameterGUI("Object to affect:", parameters, parameterID, ParameterType.GameObject);
                if (parameterID >= 0)
                {
                    constantID   = 0;
                    linkedObject = null;
                }
                else
                {
                    linkedObject = (GameObject)EditorGUILayout.ObjectField("Object to affect:", linkedObject, typeof(GameObject), true);

                    constantID   = FieldToID(linkedObject, constantID);
                    linkedObject = IDToField(linkedObject, constantID, false);
                }
            }

            messageToSend = (MessageToSend)EditorGUILayout.EnumPopup("Message to send:", messageToSend);
            if (messageToSend == MessageToSend.Custom)
            {
                customMessageParameterID = Action.ChooseParameterGUI("Method name:", parameters, customMessageParameterID, ParameterType.String);
                if (customMessageParameterID < 0)
                {
                    customMessage = EditorGUILayout.TextField("Method name:", customMessage);
                }

                sendValue = EditorGUILayout.Toggle("Pass integer to method?", sendValue);
                if (sendValue)
                {
                    customValueParameterID = Action.ChooseParameterGUI("Integer to send:", parameters, customValueParameterID, ParameterType.Integer);
                    if (customValueParameterID < 0)
                    {
                        customValue = EditorGUILayout.IntField("Integer to send:", customValue);
                    }
                }
            }

            affectChildren     = EditorGUILayout.Toggle("Send to children too?", affectChildren);
            ignoreWhenSkipping = EditorGUILayout.Toggle("Ignore when skipping?", ignoreWhenSkipping);

            AfterRunningOption();
        }
Exemple #37
0
        public async Task SendMessage(MessageToSend message)
        {
            if (_isDisconnecting)
            {
                _logger.Warning("Trying to send message while disconnecting.");
            }
            var channelId = await GetChannelId(message);

            var res = await Client.PostMessageAsync(channelId, message.Text, "Automa Luce Della Pizza (PizzaLight Bot)");
        }
        public bool appendShinkaBannerAd(ref MessageToSend messageToSend, MXit.User.UserInfo userInfo)
        {
            bool gotShinkaAd = false;

            try
            {
                if (AdvertConfig.isShowShinkaBannerAd)
                {
                    String MxitUserID = userInfo.UserId;
                    MXit.User.GenderType userGenderType = userInfo.Gender;
                    int displayWidth = userInfo.DeviceInfo.DisplayWidth;
                    int displayHeight = userInfo.DeviceInfo.DisplayHeight;
                    int userAge = AgeInYears(userInfo.DateOfBirth);

                    BannerAd adTodisplay;
                    gotShinkaAd = AdvertHelper.Instance.getBannerAd(MxitUserID, userGenderType, displayWidth, displayHeight, userAge, out adTodisplay);

                    if (gotShinkaAd)
                    {
                        if (adTodisplay.creativeType == "image")
                        {
                            IMessageElement inlineImage = MessageBuilder.Elements.CreateInlineImage(adTodisplay.adImage, ImageAlignment.Center, TextFlow.AloneOnLine, 100);
                            messageToSend.Append(inlineImage);
                        }

                        messageToSend.Append("Go to ", CSS.Ins.clr["light"], CSS.Ins.mrk["d"]);
                        messageToSend.AppendLine(MessageBuilder.Elements.CreateLink(adTodisplay.altText, ".clickad~" + adTodisplay.clickURL));
                        messageToSend.AppendLine();

                        //register impression for the bannerad display
                        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(adTodisplay.impressionURL);

                        req.UserAgent = "Mozilla Compatible mxit_client";
                        req.Headers.Add("HTTP_X_DEVICE_USER_AGENT", "Mozilla Compatible mxit_client");
                        req.Headers.Add("HTTP_X_FORWARDED_FOR", MxitUserID);
                        req.Headers.Add("HTTP_REFERER", AdvertConfig.appID);

                        req.Timeout = AdvertConfig.bannerAdTimeout;
                        req.Proxy = null;
                        req.KeepAlive = false;
                        req.ServicePoint.ConnectionLeaseTimeout = 1000;
                        req.ServicePoint.MaxIdleTime = 1000;

                        QueueHelper_HTTP.Instance.QueueItem(req);
                    }
                }
                //zama end
            }
            catch (Exception ex)
            {
                logger.Error("[" + MethodBase.GetCurrentMethod().Name + " - Error getting or showing Shinka ad: " + ex.ToString());
            }

            return gotShinkaAd; //so that the calling function knows if an ad was displayed
        }
Exemple #39
0
        /// <summary>
        ///		Comprueba si se puede ejecutar una acción
        /// </summary>
        protected override bool CanExecuteAction(string action, object parameter)
        {
            switch (action)
            {
            case nameof(SendMessageCommand):
                return(!MessageToSend.IsEmpty());

            default:
                return(false);
            }
        }
Exemple #40
0
 public MessageToSend getScreenMessage(
     UserSession us,
     MessageToSend ms,
     InputHandlerResult ihr)
 {
     string page_id = us.current_menu_loc;
     return ScreenOutputAdapterFactory.getScreenOutputAdapter(page_id).getOutputScreenMessage(
         us,
         menu_def.getMenuPage(page_id),
         ms,
         ihr);
 }
        public void addQuickFilterLinksToMessageFromList(
            UserSession us,
            MessageToSend ms)
        {
            List<char> starting_chars = us.friend_manager.getStartingCharacters();
            //.. starting_chars
            starting_chars.Sort();
            String filter = "";
            if (us.hasVariable(ChooseFriendHandler.FRIEND_LIST_FILTER))
            {
                filter = us.getVariable(ChooseFriendHandler.FRIEND_LIST_FILTER);

            }
            if (starting_chars.Count() > 1)
            {
                int i = 0;

                foreach (var a_char in starting_chars)
                {
                    if (i == 0)
                    {
                        i++;
                        ms.Append("\r\nFilter - ");
                        if (filter.Equals("") || filter.Equals("ALL"))
                        {
                            ms.Append("[ALL]");
                        }
                        else
                        {
                            ms.Append(createMessageLink(MENU_LINK_NAME, "[ALL]", FriendHandler.FILTER_LIST + "ALL"));
                        }
                        ms.Append(" ");
                    }
                    if (filter.Equals(a_char.ToString().ToUpper()))
                    {
                        ms.Append("[" + a_char.ToString().ToUpper() + "]");
                    }
                    else
                    {
                        ms.Append(createMessageLink(MENU_LINK_NAME, "[" + a_char.ToString().ToUpper() + "]", FriendHandler.FILTER_LIST + a_char));
                    }
                    ms.Append(" ");
                }
                ms.Append("\r\n\r\n");
            }
        }
        public virtual void addLinksToMessageFromList(
            UserSession us,
            List<MenuOptionItem> list,
            MessageToSend ms)
        {
            int count = (us.current_menu_page * MenuDefinition.PAGE_ITEM_COUNT) + 1;

            int starting_index = us.current_menu_page * MenuDefinition.PAGE_ITEM_COUNT;
            MenuOptionItem an_option;
            for (int i = starting_index;
                i < list.Count && i < starting_index + MenuDefinition.PAGE_ITEM_COUNT;
                i++)
            {
                an_option = list.ElementAt(i);
                ms.Append(createMessageLink(MENU_LINK_NAME, count + ") ", an_option.link_val));
                ms.Append(an_option.display_text + "\r\n");
                count++;
            }
        }
        public static void appendInitialMessageConfig(UserProfile up, MessageToSend message)
        {
            IMessageElement chatScreenConfig;
            IClientColors clientColors = MessageBuilder.Elements.CreateClientColors(); //Create the colour scheme you want to
            UserColourTheme uct = UserColourTheme.getColourTheme(up.user_profile_custom.colour_theme);
            if (uct != null)
            {
                clientColors[ClientColorType.Background] = uct.getBackGroundColour();
                clientColors[ClientColorType.Text] = uct.getForeGroundColour();
                clientColors[ClientColorType.Link] = uct.getLinkColour();
                chatScreenConfig = MessageBuilder.Elements.CreateChatScreenConfig(
                    ChatScreenBehaviourType.ShowProgress |
                    ChatScreenBehaviourType.NoPrefix,
                    clientColors);
            }
            else
            {

                //clientColors[ClientColorType.Background] = Color.Empty; //System.Drawing.ColorTranslator.FromHtml("#??????");
                //clientColors[ClientColorType.Text] = Color.Empty; //System.Drawing.ColorTranslator.FromHtml("#??????");
                //clientColors[ClientColorType.Link] = Color.Empty; //System.Drawing.ColorTranslator.FromHtml("#??????");
                chatScreenConfig = MessageBuilder.Elements.CreateChatScreenConfig(
                    ChatScreenBehaviourType.ShowProgress |
                    ChatScreenBehaviourType.NoPrefix);

            }

            message.Append(chatScreenConfig);
            /*else
            {
                chatScreenConfig = MessageBuilder.Elements.CreateChatScreenConfig(
                    ChatScreenBehaviourType.ShowProgress |
                    ChatScreenBehaviourType.NoPrefix);
            }
            ms.Append(chatScreenConfig);*/
        }
 public bool SendMessage(MessageToSend messageToSend)
 {
     MXitConnectionModule.RESTMessageToSend RESTMessageToSend = new RESTMessageToSend(messageToSend);
     return this.SendMessage(RESTMessageToSend);
 }
        public bool appendShinkaBannerAd(ref MessageToSend messageToSend, MXit.User.UserInfo userInfo, String preselectedAdUnitID)
        {
            bool gotShinkaAd = false;

            try
            {
                if (AdvertConfig.isShowShinkaBannerAd)
                {
                    String MxitUserID = userInfo.UserId;
                    MXit.User.GenderType userGenderType = userInfo.Gender;
                    int displayWidth = userInfo.DeviceInfo.DisplayWidth;
                    int displayHeight = userInfo.DeviceInfo.DisplayHeight;
                    int userAge = AgeInYears(userInfo.DateOfBirth);

                    BannerAd adTodisplay;
                    gotShinkaAd = AdvertHelper.Instance.getBannerAd(MxitUserID, userGenderType, displayWidth, displayHeight, userAge, preselectedAdUnitID, out adTodisplay);

                    if (gotShinkaAd)
                    {
                        if (adTodisplay.creativeType == "image" && userInfo.DeviceInfo.DisplayWidth >= 320)
                        {
                            //an extra check to see that the image was retrieved
                            //Eric changed: if (adTodisplay.adImage == null)
                            if (adTodisplay.adImage == null)
                            {
                                return false;
                            }
                            else
                            {
                                appendBannerImage(ref messageToSend, userInfo, adTodisplay);
                            }

                        }

                        //If the Alt text is empty then don't display the link below the image:
                        if (!String.IsNullOrEmpty(adTodisplay.altText))
                        {
                            messageToSend.Append("Go to ", CSS.Ins.clr["light"], CSS.Ins.mrk["d"]);
                            String displayText = System.Net.WebUtility.HtmlDecode(adTodisplay.altText);
                            messageToSend.AppendLine(MessageBuilder.Elements.CreateBrowserLink(displayText, adTodisplay.clickURL));
                            messageToSend.AppendLine();
                        }
                        else //Don't display Alt text link:
                        {
                            messageToSend.AppendLine();
                        }

                        //register impression for the bannerad display
                        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(adTodisplay.impressionURL);

                        req.UserAgent = "Mozilla Compatible";

                        Random random = new Random(DateTime.Now.Second);
                        int randomUpTo254 = random.Next(1, 254);
                        String tempIP = "196.11.239." + randomUpTo254;
                        req.Headers.Add("X-Forwarded-For", tempIP);

                        req.Referer = AdvertConfig.appID;

                        req.Timeout = AdvertConfig.bannerAdTimeout;
                        req.Proxy = null;
                        req.KeepAlive = false;
                        req.ServicePoint.ConnectionLeaseTimeout = 10000;
                        req.ServicePoint.MaxIdleTime = 10000;

                        QueueHelper_HTTP.Instance.QueueItem(req);
                    }
                }
                //zama end
            }
            catch (Exception ex)
            {
                logger.Error("[" + MethodBase.GetCurrentMethod().Name + " - Error getting or showing Shinka ad: " + ex.ToString());
            }

            return gotShinkaAd; //so that the calling function knows if an ad was displayed
        }
        public override MessageToSend getOutputScreenMessage(
            UserSession us,
            MenuPage mp,
            MessageToSend ms,
            InputHandlerResult ihr)
        {
            ms.Append(MessageBuilder.Elements.CreateClearScreen());
            if (!mp.GetType().FullName.Equals("MxitTestApp.OptionMenuPage"))//TODO: Should be constant
                throw new Exception("Invalid menu page passed into getScreen method ");

            OptionMenuPage omp = (OptionMenuPage)mp;
            ms.Append(omp.title + "\r\n", TextMarkup.Bold);
            if (ihr.action == InputHandlerResult.INVALID_MENU_ACTION
                && ihr.error != null)
            {
                ms.Append((string)ihr.error + "\r\n");
            }
            else
            {
                ms.Append(parseMessage(us, omp.message) + "\r\n");
            }

            ms.AppendLine("Refer a friend to the BibleApp on MXit by using the link below. ");
            ms.AppendLine(createMessageLink(MENU_LINK_NAME, "Spread The Word", MainMenuHandler.REFER_A_FRIEND));

            ms.AppendLine();

            if (us.user_profile.is_suspended)
            {
                ms.Append("\r\n");
                ms.Append("You have been suspended from this application. Please email us at [email protected].");
                ms.Append("\r\n");
                ms.Append("\r\n");
                return ms;
            }

            if (us.hasVariable(UserSession.GUEST_USER_NAME_ASSIGNED))
            {
                ms.Append("\r\n");
                ms.Append("You have been assigned a guest user name. To remove this message please change your user name in the profile option below.");
                ms.Append("\r\n");
                ms.Append("\r\n");
            }

            if (us.bookmark_manager.bookmark_verse != null)
            {
                ms.Append("To continue reading where you left off ");
                ms.Append(createMessageLink(MENU_LINK_NAME, "Click Here", "BOOKMARK"));
                ms.Append("\r\n");
                ms.Append("\r\n");
                ms.Append("Or choose an option below...\r\n");
            }
            else
            {
                ms.Append("Choose an option below...\r\n");
            }

            List<MenuOptionItem> options = omp.options;
            int count =1 ;
            foreach (MenuOptionItem option in options)
            {
                ms.Append(createMessageLink(MENU_LINK_NAME, count + ") ", option.link_val));
                if (option.menu_option_id == MY_PROFILE_OPTION_ID)
                {
                    if (us.hasNewEvent())
                    {
                        ms.Append(option.display_text + " (!)\r\n", TextMarkup.Bold);
                    }
                    else
                    {
                        ms.Append(option.display_text + "\r\n");
                    }
                }
                else
                {
                    ms.Append(option.display_text + "\r\n");
                }

                count++;
            }
            appendBackMainLinks(us,  ms);
            appendMessageConfig(true, ms);

            ms.AppendLine("");

            ms.AppendLine("");
            ms.AppendLine("Shortcuts...", TextMarkup.Bold);
            ms.Append(createMessageLink(MENU_LINK_NAME, "Inbox", MainMenuHandler.MESSAGE_INBOX));
            if (us.hasNewMessageEvent())
            {
                ms.Append(" (NEW)", TextMarkup.Bold);
            }

            if (us.hasNewFriendRequest())
            {
                ms.Append(" | ");
                ms.Append(createMessageLink(MENU_LINK_NAME, "Buddy Requests", MainMenuHandler.BUDDY_REQUESTS));
                ms.Append(" (NEW)", TextMarkup.Bold);
            }

            ms.Append(" | ");
            ms.Append(createMessageLink(MENU_LINK_NAME, "Help", MainMenuHandler.HELP));

            ms.Append(" | ");
            ms.Append(createMessageLink(MENU_LINK_NAME, "About Us", MainMenuHandler.ABOUT));

            ms.Append(" | ");
            ms.Append(createMessageLink(MENU_LINK_NAME, "Change Colours", MainMenuHandler.COLOUR_CHANGE));

            ms.AppendLine();
            ms.AppendLine();
            UserColourTheme uct = UserColourTheme.getColourTheme(us.user_profile.user_profile_custom.colour_theme);
            if (uct != null)
            {
                Color color = uct.getTipTextColour();
                ms.AppendLine("Tip: Check out the profile section and if your friends use the BibleApp add them as buddies so that you can send them verses. For a start add us, our code is CBTJXP. ",color);
            }
            else
            {
                ms.AppendLine("Tip: Check out the profile section and if your friends use the BibleApp add them as buddies so that you can send them verses. For a start add us, our code is CBTJXP. ");
            }
            ms.AppendLine();
            ms.AppendLine();
            //ADMIN AREA
            if (us.user_profile.is_admin)
            {
                ms.AppendLine("ADMIN AREA");
                ms.AppendLine("");
                ms.Append(createMessageLink(MENU_LINK_NAME, "Send Notification", MainMenuHandler.SEND_NOTIFICATION));
                //ms.AppendLine("");
                //ms.Append(createMessageLink(MENU_LINK_NAME, "Send Notification", MainMenuHandler.SEND_NOTIFICATION));
            }

            return ms;
            //return output;
        }
        public bool appendShinkaBannerAd(ref MessageToSend messageToSend, MXit.User.UserInfo userInfo)
        {
            //Default to no preselected ad unit id:
            String preselectedAdUnitID = "";

            return appendShinkaBannerAd(ref messageToSend, userInfo, preselectedAdUnitID);
        }
		public override void ShowGUI (List<ActionParameter> parameters)
		{
			parameterID = Action.ChooseParameterGUI ("Object to affect:", parameters, parameterID, ParameterType.GameObject);
			if (parameterID >= 0)
			{
				constantID = 0;
				linkedObject = null;
			}
			else
			{
				linkedObject = (GameObject) EditorGUILayout.ObjectField ("Object to affect:", linkedObject, typeof(GameObject), true);
				
				constantID = FieldToID (linkedObject, constantID);
				linkedObject = IDToField  (linkedObject, constantID, false);
			}
			
			messageToSend = (MessageToSend) EditorGUILayout.EnumPopup ("Message to send:", messageToSend);
			if (messageToSend == MessageToSend.Custom)
			{
				customMessage = EditorGUILayout.TextField ("Method name:", customMessage);
				
				sendValue = EditorGUILayout.Toggle ("Pass integer to method?", sendValue);
				if (sendValue)
				{
					customValue = EditorGUILayout.IntField ("Integer to send:", customValue);
				}
			}
			
			affectChildren = EditorGUILayout.Toggle ("Send to children too?", affectChildren);
			ignoreWhenSkipping = EditorGUILayout.Toggle ("Ignore when skipping?", ignoreWhenSkipping);
			
			AfterRunningOption ();
		}
 public IEnumerable<object> HandleAndSpawnMany(MessageToSend message)
 {
     yield return new RespondToSender(new Response());
     yield return new NotResponding();
     yield return new DelayedResponse(new NotResponding(), TimeSpan.FromMinutes(1));
 }
        public override MessageToSend getOutputScreenMessage(
            UserSession us,
            MenuPage mp,
            MessageToSend ms,
            InputHandlerResult ihr)
        {
            ms.Append(MessageBuilder.Elements.CreateClearScreen());
            if (!mp.GetType().FullName.Equals("MxitTestApp.VerseMenuPage"))//TODO: Should be constant
                throw new Exception("Invalid menu page passed into getScreen method ");

            VerseMenuPage omp = (VerseMenuPage)mp;
            ms.Append(omp.title + "\r\n", TextMarkup.Bold);
            ms.Append("\r\n");
            ms.Append("\r\n");
            if (ihr.error != null && ihr.action == InputHandlerResult.INVALID_MENU_ACTION)
            {
                ms.Append((string)ihr.error + "\r\n");
            }

            Boolean should_display_conf_message = displayMessage(us, ms, ihr);
            if (should_display_conf_message)
            {
                return ms;
            }
            ms.Append(parseMessage(us, omp.message) + "\r\n");

            /*else if (us.getVariable(FriendHandler.DELETED_FRIEND_NAME) != null)
            {
                friend_name = (String)us.removeVariable(FriendHandler.DELETED_FRIEND_NAME);
                ms.Append("You have removed " + friend_name + " from you buddy list.");
                ms.Append("\r\n");
                ms.Append("\r\n");
            }*/

                Boolean recip_is_set = false;
                //check if recipient is set already
                if (us.hasVariable(RECIPIENT_ID))
                {
                    String friend_id = us.getVariable(RECIPIENT_ID);
                    long l_friend_id = long.Parse(friend_id);
                    String user_name = UserNameManager.getInstance().getUserName(l_friend_id);
                    ms.Append("To: ");
                    ms.Append(user_name, TextMarkup.Bold);
                    ms.Append(" ");
                    ms.Append(createMessageLink(MENU_LINK_NAME, "[ edit ]", NotifMessageSendHandler.CHOOSE_FRIEND_ID));
                    recip_is_set = true;
                }
                else
                {
                    ms.Append("To: ");
                    ms.Append(createMessageLink(MENU_LINK_NAME, "[ edit ]", NotifMessageSendHandler.CHOOSE_FRIEND_ID));
                    ms.Append(" *");
                }

                ms.Append("\r\n");
                ms.Append("\r\n");

                if (us.hasVariable(MESSAGE_SUBJECT))
                {
                    String subject = us.getVariable(MESSAGE_SUBJECT);
                    ms.Append("Subject: ");
                    ms.Append(subject);
                    ms.Append(" ");
                }
                else
                {
                    ms.Append("Subject: ");
                }
                ms.Append(createMessageLink(MENU_LINK_NAME, "[ edit ]", NotifMessageSendHandler.ENTER_MESSAGE_SUBJECT));
                ms.Append("\r\n");
                ms.Append("\r\n");

                if (us.hasVariable(MESSAGE_TEXT))
                {
                    String message = us.getVariable(MESSAGE_TEXT);
                    ms.Append("Message: ");
                    ms.Append(message);
                    ms.Append(" ");
                }
                else
                {
                    ms.Append("Message: ");
                }
                ms.Append(createMessageLink(MENU_LINK_NAME, "[ edit ]", NotifMessageSendHandler.ENTER_MESSAGE));
                ms.Append("\r\n");
                ms.Append("\r\n");

                if (!recip_is_set)
                    ms.AppendLine("Fields marked with * has to be set before you can send the message");
                else
                    ms.AppendLine(createMessageLink(MENU_LINK_NAME, "Send Message", NotifMessageSendHandler.SEND_MESSAGE));

            ms.AppendLine("");
            appendBackMainLinks(us, ms);
            appendMessageConfig(true,  ms);
            return ms;
            //return output;
        }
 public Response HandleWithReplyOrPublish(MessageToSend message)
 {
     //Will reply to original sender if sender used bus.Request<Response>(message)
     //Will also send message through routing rules in your TransportRegistry
     return new Response();
 }
 public bool EnqueueMessageToSend(MessageToSend item)
 {
     return QueueHelper_OutgoingMessage.Instance.EnqueueItem(item);
 }
Exemple #53
0
        public void BuildMenu(DBUtil.UData ud, MessageToSend mes)
        {
            IMessageElement link;
            switch (ud.state)
            {
                case -2: //first time user
                    {
                        mes.AppendLine("Final War", TextMarkup.Bold);
                        mes.AppendLine();
                        mes.AppendLine("Welcome to Final War, the war to end all wars! Join the struggle to control the cyber world through brute force.");
                        mes.AppendLine();
                        mes.Append("It is your first time here, to get started use the ");
                        mes.Append("nick", TextMarkup.Underline);
                        mes.Append(" command to change your nickname (currently: " + ud.uname + ", this is the only free name change available), then why dont you read the ");

                        link = MessageBuilder.Elements.CreateLink("tuthelp",          // Optional
                                                          "help",             // Compulsory
                                                          "help",  // Optional
                                                          "help");        // Optional
                        mes.Append(link);

                        mes.AppendLine(" otherwise, head to the main menu to jump in.");

                        link = MessageBuilder.Elements.CreateLink("tutmenu",          // Optional
                                                          "Back to the menu.",             // Compulsory
                                                          "menu",  // Optional
                                                          "menu");        // Optional
                        mes.Append(link);
                        return;
                    }
                case 0: //main menu
                    {
                        mes.AppendLine("Final War", TextMarkup.Bold);
                        mes.AppendLine();
                        mes.AppendLine("Welcome back " + ud.uname + " what would you like to do?");
                        mes.AppendLine();

                        link = MessageBuilder.Elements.CreateLink("menu1",          // Optional
                                  "1) My Hideout",             // Compulsory
                                  "1",  // Optional
                                  "1");        // Optional
                        mes.AppendLine(link);

                        link = MessageBuilder.Elements.CreateLink("menu2",          // Optional
                                  "2) Bank",             // Compulsory
                                  "2",  // Optional
                                  "2");        // Optional
                        mes.AppendLine(link);

                        link = MessageBuilder.Elements.CreateLink("menu3",          // Optional
                                  "3) Tech",             // Compulsory
                                  "3",  // Optional
                                  "3");        // Optional
                        mes.AppendLine(link);

                        link = MessageBuilder.Elements.CreateLink("menu4",          // Optional
                                  "4) Gang",             // Compulsory
                                  "4",  // Optional
                                  "4");        // Optional
                        mes.AppendLine(link);

                        link = MessageBuilder.Elements.CreateLink("menu5",          // Optional
                                  "5) The streets",             // Compulsory
                                  "5",  // Optional
                                  "5");        // Optional
                        mes.AppendLine(link);

                        link = MessageBuilder.Elements.CreateLink("menu9",          // Optional
                                  "9) Leaderboards",             // Compulsory
                                  "9",  // Optional
                                  "9");        // Optional
                        mes.AppendLine(link);

                        link = MessageBuilder.Elements.CreateLink("menuhelp",          // Optional
                                  "help) Help",             // Compulsory
                                  "help",  // Optional
                                  "help");        // Optional
                        mes.AppendLine(link);

                        mes.AppendLine();
                        mes.AppendLine("News: " + Program.config.Notice);

                        return;
                    }
                case 1: //help menu
                    {
                        mes.AppendLine("Help", TextMarkup.Bold);
                        mes.AppendLine();
                        mes.AppendLine("Do stuff, kill people, level up");
                        mes.AppendLine();

                        link = MessageBuilder.Elements.CreateLink("helpmenu",          // Optional
                                  "Back",             // Compulsory
                                  "menu",  // Optional
                                  "menu");        // Optional
                        mes.Append(link);

                        return;
                    }
                case 2: //hideout
                    {
                        mes.AppendLine("Your Hideout", TextMarkup.Bold);
                        mes.AppendLine();
                        mes.AppendLine("Your stats:");
                        mes.AppendLine("Level: " + ud.level.ToString() + "  Exp: " + ud.exp.ToString());
                        mes.AppendLine();

                        link = MessageBuilder.Elements.CreateLink("hidemenu",          // Optional
                                  "Back",             // Compulsory
                                  "menu",  // Optional
                                  "menu");        // Optional
                        mes.Append(link);
                        return;
                    }
                case 3: //bank
                    {
                        mes.AppendLine("Your Bank Account", TextMarkup.Bold);
                        mes.AppendLine();
                        mes.AppendLine("Your bank details:");
                        mes.AppendLine("Bank Balance: $" + ud.bank.ToString());
                        mes.AppendLine("Wallet Balance: $" + ud.wallet.ToString());
                        mes.AppendLine();
                        mes.Append("Use the ");
                        mes.Append("with", TextMarkup.Underline);
                        mes.AppendLine(" command to withdraw money");
                        mes.Append("Use the ");
                        mes.Append("dep", TextMarkup.Underline);
                        mes.AppendLine(" command to deposit it");

                        link = MessageBuilder.Elements.CreateLink("bankback",          // Optional
                                  "Back",             // Compulsory
                                  "menu",  // Optional
                                  "menu");        // Optional
                        mes.Append(link);

                        return;
                    }
                case 4: //tech
                    {
                        mes.AppendLine("Your Tech", TextMarkup.Bold);
                        mes.AppendLine();
                        mes.AppendLine("Equips and Stats:");
                        mes.AppendLine("Atk: " + ud.atk.ToString() + "  Def: " + ud.def.ToString());
                        mes.Append("Armour: ");
                        if (ud.armour == -1)
                        {
                            mes.AppendLine("None");
                        }
                        else
                        {
                            mes.AppendLine(ud.armour.ToString() + "(armour ID)");
                        }
                        mes.Append("Gloves: ");
                        if (ud.gloves == -1)
                        {
                            mes.AppendLine("None");
                        }
                        else
                        {
                            mes.AppendLine(ud.gloves.ToString() + "(gloves ID)");
                        }
                        mes.Append("Helmet: ");
                        if (ud.helmet == -1)
                        {
                            mes.AppendLine("None");
                        }
                        else
                        {
                            mes.AppendLine(ud.helmet.ToString() + "(helmet ID)");
                        }
                        mes.Append("Weapon: ");
                        if (ud.weapon == -1)
                        {
                            mes.AppendLine("None");
                        }
                        else
                        {
                            mes.AppendLine(ud.weapon.ToString() + "(weapon ID)");
                        }
                        mes.AppendLine();
                        link = MessageBuilder.Elements.CreateLink("techback",          // Optional
                                  "Back",             // Compulsory
                                  "menu",  // Optional
                                  "menu");        // Optional
                        mes.Append(link);

                        return;
                    }
                case 5: //gang
                    {
                        mes.AppendLine("Your Gang", TextMarkup.Bold);
                        mes.AppendLine();
                        mes.AppendLine("Members, Message, factories, tax, etc");
                        mes.AppendLine();
                        link = MessageBuilder.Elements.CreateLink("gangback",          // Optional
                                  "Back",             // Compulsory
                                  "menu",  // Optional
                                  "menu");        // Optional
                        mes.Append(link);

                        return;
                    }
                case 6: //streets
                    {
                        mes.AppendLine("The Streets", TextMarkup.Bold);
                        mes.AppendLine();
                        mes.AppendLine("Fight, Level, etc");
                        mes.AppendLine();
                        link = MessageBuilder.Elements.CreateLink("streetback",          // Optional
                                  "Back",             // Compulsory
                                  "menu",  // Optional
                                  "menu");        // Optional
                        mes.Append(link);

                        return;
                    }

            }
        }
        public bool appendShinkaBannerAd(ref MessageToSend messageToSend, MXit.User.UserInfo userInfo)
        {
            bool gotShinkaAd = false;

            try
            {
                if (AdvertConfig.isShowShinkaBannerAd)
                {
                    String MxitUserID = userInfo.UserId;
                    MXit.User.GenderType userGenderType = userInfo.Gender;
                    int displayWidth = userInfo.DeviceInfo.DisplayWidth;
                    int displayHeight = userInfo.DeviceInfo.DisplayHeight;
                    int userAge = AgeInYears(userInfo.DateOfBirth);

                    BannerAd adTodisplay;
                    gotShinkaAd = AdvertHelper.Instance.getBannerAd(MxitUserID, userGenderType, displayWidth, displayHeight, userAge, out adTodisplay);

                    if (gotShinkaAd)
                    {
                        if (adTodisplay.creativeType == "image")
                        {
                            int imageDisplayWidthPerc;

                            if (displayWidth <= 128)
                            {
                                imageDisplayWidthPerc = 99;
                            }
                            else
                            {
                                imageDisplayWidthPerc = 100;
                            }

                            IMessageElement inlineImage = MessageBuilder.Elements.CreateInlineImage(adTodisplay.adImage, ImageAlignment.Center, TextFlow.AloneOnLine, imageDisplayWidthPerc);
                            messageToSend.Append(inlineImage);
                        }

                        messageToSend.Append("Go to ", CSS.Ins.clr["light"], CSS.Ins.mrk["d"]);
                        String displayText = System.Net.WebUtility.HtmlDecode(adTodisplay.altText);
                        messageToSend.AppendLine(MessageBuilder.Elements.CreateBrowserLink(displayText, adTodisplay.clickURL));
                        messageToSend.AppendLine();

                        //register impression for the bannerad display
                        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(adTodisplay.impressionURL);

                        req.UserAgent = "Mozilla Compatible mxit_client";

                        Random random = new Random(DateTime.Now.Second);
                        int randomUpTo254 = random.Next(1, 254);
                        String tempIP = "196.11.239." + randomUpTo254;
                        req.Headers.Add("X-Forwarded-For", tempIP);

                        req.Referer = AdvertConfig.appID;

                        req.Timeout = AdvertConfig.bannerAdTimeout;
                        req.Proxy = null;
                        req.KeepAlive = false;
                        req.ServicePoint.ConnectionLeaseTimeout = 10000;
                        req.ServicePoint.MaxIdleTime = 10000;

                        QueueHelper_HTTP.Instance.QueueItem(req);
                    }
                }
                //zama end
            }
            catch (Exception ex)
            {
                logger.Error("[" + MethodBase.GetCurrentMethod().Name + " - Error getting or showing Shinka ad: " + ex.ToString());
            }

            return gotShinkaAd; //so that the calling function knows if an ad was displayed
        }
        public void ProcessOAuth2Token(MXit.OAuth2.TokenResponse tokenResponseReceived)
        {
            logger.Debug(MethodBase.GetCurrentMethod().Name + "() - START");

            bool isTokenResultSuccess = (tokenResponseReceived.Result == AsyncOperationResult.Success);

            if (isTokenResultSuccess) //We got a succesfull result:
            {
                bool isUserAllowed = (tokenResponseReceived.AuthorizationResult == AuthorizationResult.Allow);
                bool isUserAlwaysAllowed = (tokenResponseReceived.AuthorizationResult == AuthorizationResult.AlwaysAllow);

                if (isUserAllowed || isUserAlwaysAllowed) //We got permission:
                {
                    if ((String)tokenResponseReceived.Context == ".p")
                    {
                        MxitModel.FullProfile userProfile;

                        //Do something with the tokenReceived.AccessToken
                        this.GetUserMxitProfile(tokenResponseReceived.AccessToken, tokenResponseReceived.UserId, out userProfile);
                    }
                    else if ((String)tokenResponseReceived.Context == ".sf")
                    {
                        MxitModel.ContactList userContactList;

                        //Do something with the tokenReceived.AccessToken
                        this.GetContactList(tokenResponseReceived.AccessToken, tokenResponseReceived.UserId, out userContactList);

                        for (int i=0; i < userContactList.Contacts.Length; i++)
                        {
                            Console.WriteLine(userContactList.Contacts[i].DisplayName);
                        }
                    }
                    else if ((String)tokenResponseReceived.Context == ".f")
                    {
                        System.Net.HttpStatusCode responseCode;
                        //MXitConnectionModule.RESTConnectionHelper.Instance.SendMessageFromFriendToFriend(tokenResponseReceived.AccessToken, tokenResponseReceived.UserId, "m42992584002", "Merry Christmas! It's morning, and we've got nowhere to go. So wake me up in about an hour or so. It's Christmas day, and since we've got nowhere to be, stoke that braai and throw on another boerewors for me. It's Christmas night, and there's nothing I'd rather do than chill by the light of the Christmas tree with you.", out responseCode);

                        MessageToSend messageToSendToFriend = new MessageToSend(tokenResponseReceived.UserId, "m42992584002", DeviceInfo.DefaultDevice);
                        messageToSendToFriend.AppendLine("Light text", System.Drawing.Color.Black);
                        messageToSendToFriend.AppendLine("Bold text", System.Drawing.Color.Purple, new TextMarkup[] { TextMarkup.Bold });
                        messageToSendToFriend.AppendLine(MessageBuilder.Elements.CreateLink("Tip Link", ".tip"));

                        MXitConnectionModule.RESTConnectionHelper.Instance.SendMessageFromUserAToUserB(tokenResponseReceived.AccessToken, messageToSendToFriend);
                    }
                }
                else
                {
                    //Call a hook that will display a message to the user asking him to allow access to proceed.
                }
            }
            else
            {
                //Some error occured.
                if (logger.IsDebugEnabled) Console.WriteLine(DateTime.Now.ToString() + " Token request was not succesfull: " + tokenResponseReceived.Result);
                logger.Error(MethodBase.GetCurrentMethod().Name + " Token request was not succesfull: " + tokenResponseReceived.Result);
            }

            logger.Debug(MethodBase.GetCurrentMethod().Name + "() - END");
        }
 public DelayedResponse HandleWithDelayedResponse(MessageToSend message)
 {
     //Route the message, but don't process it for 15 minutes
     return new DelayedResponse(new Response(), TimeSpan.FromMinutes(15));
 }
 public bool SendMessageFromUserAToUserB(String token, MessageToSend messageToSend)
 {
     MXitConnectionModule.RESTMessageToSend RESTMessageToSend = new RESTMessageToSend(messageToSend);
     return this.SendMessageFromUserAToUserB(token, RESTMessageToSend);
 }
        public override MessageToSend getOutputScreenMessage(
            UserSession us,
            MenuPage mp,
            MessageToSend ms,
            InputHandlerResult ihr)
        {
            ms.Append(MessageBuilder.Elements.CreateClearScreen());
            if (!mp.GetType().FullName.Equals("MxitTestApp.VerseMenuPage"))//TODO: Should be constant
                throw new Exception("Invalid menu page passed into getScreen method ");

            VerseMenuPage omp = (VerseMenuPage)mp;
            ms.Append(omp.title + "\r\n", TextMarkup.Bold);
            ms.Append("\r\n");
            ms.Append("\r\n");
            if (ihr.error != null && ihr.action == InputHandlerResult.INVALID_MENU_ACTION)
            {
                ms.Append((string)ihr.error + "\r\n");
            }

            Boolean should_display_conf_message = displayMessage(us, ms, ihr);
            if (should_display_conf_message)
            {
                return ms;
            }
            ms.Append(parseMessage(us, omp.message) + "\r\n");

            /*else if (us.getVariable(FriendHandler.DELETED_FRIEND_NAME) != null)
            {
                friend_name = (String)us.removeVariable(FriendHandler.DELETED_FRIEND_NAME);
                ms.Append("You have removed " + friend_name + " from you buddy list.");
                ms.Append("\r\n");
                ms.Append("\r\n");
            }*/

            if (us.friend_manager.getFriends().Count <= 0)
            {
                ms.Append("You dont have any buddies added, you need to first invite buddies in order to send Verses to them.");
                ms.Append("\r\n");
                ms.Append("\r\n");
            }
            else
            {
                Boolean recip_is_set = false;
                //check if recipient is set already

                if (us.hasVariable(ChooseFriendHandler.RECIPIENT_LIST) && ((List<long>)us.getVariableObject(ChooseFriendHandler.RECIPIENT_LIST)).Count > 0)
                {
                    String friend_list = getCurrentSendList(us);
                    ms.Append("To: ");
                    ms.Append(friend_list);
                    ms.Append(" ");
                    ms.Append(createMessageLink(MENU_LINK_NAME, "[ edit ]", VerseMessageSendHandler.CHOOSE_FRIEND_ID));
                    recip_is_set = true;
                }
                else
                {
                    ms.Append("To: ");
                    ms.Append(createMessageLink(MENU_LINK_NAME, "[ edit ]", VerseMessageSendHandler.CHOOSE_FRIEND_ID));
                    ms.Append(" *");
                }

                ms.Append("\r\n");
                ms.Append("\r\n");

                VerseSection vs = (VerseSection)us.getVariableObject("Browse.verse_section");
                if (vs == null)
                {
                    Console.WriteLine("Expected Browse.verse_section present, but not found");
                }
                else
                {
                    Verse start_verse = vs.start_verse;
                    Verse end_verse = vs.end_verse;
                    if (end_verse == null)
                    {
                        end_verse = BrowseBibleScreenOutputAdapter.getDefaultEndVerse(start_verse);
                    }

                    ms.Append("Verse: ");
                    ms.Append(BibleHelper.getVerseSectionReference(start_verse, end_verse), TextMarkup.Bold);
                    ms.Append("\r\n");
                    ms.Append("\r\n");
                }

                if (us.hasVariable(MESSAGE_SUBJECT))
                {
                    String subject = us.getVariable(MESSAGE_SUBJECT);
                    ms.Append("Subject: ");
                    ms.Append(subject);
                    ms.Append(" ");
                }
                else
                {
                    ms.Append("Subject: ");
                }
                ms.Append(createMessageLink(MENU_LINK_NAME, "[ edit ]", VerseMessageSendHandler.ENTER_MESSAGE_SUBJECT));
                ms.Append("\r\n");
                ms.Append("\r\n");

                if (us.hasVariable(MESSAGE_TEXT))
                {
                    String message = us.getVariable(MESSAGE_TEXT);
                    ms.Append("Message: ");
                    ms.Append(message);
                    ms.Append(" ");
                }
                else
                {
                    ms.Append("Message: ");
                }
                ms.Append(createMessageLink(MENU_LINK_NAME, "[ edit ]", VerseMessageSendHandler.ENTER_MESSAGE));
                ms.Append("\r\n");
                ms.Append("\r\n");

                if (!recip_is_set)
                    ms.AppendLine("Fields marked with * has to be set before you can send the message");
                else
                    ms.AppendLine(createMessageLink(MENU_LINK_NAME, "Send Message", VerseMessageSendHandler.SEND_MESSAGE));
            }
            ms.AppendLine("");
            appendBackMainLinks(us, ms);
            appendMessageConfig(true,  ms);
            return ms;
            //return output;
        }
        private void appendBannerImage(ref MessageToSend messageToSend, MXit.User.UserInfo userInfo, BannerAd adTodisplay)
        {
            if ((AdvertConfig.bannerCacheSize > 0) && (messageToSend.ToDevice.HasFeature(DeviceFeatures.Gaming)))
            {
                //use ImageStrips to allow caching of images on users device
                string bannerHash = GetImageHash(adTodisplay.adImage);
                int cachePosition;
                if (!bannerHashMap.ContainsKey(bannerHash))
                {
                    cachePosition = lastCachePosition;
                    //we create a dictionary of ImageStrips with the required sizes
                    AdvertStripCollection bannerStrips = new AdvertStripCollection(bannerHash, adTodisplay.adImage);

                    bannerStripCache[cachePosition] = bannerStrips;
                    //remove any other hashes that are using this position
                    foreach (string key in bannerHashMap.Keys)
                    {
                        if (bannerHashMap[key] == cachePosition)
                            bannerHashMap.Remove(key);
                        break;
                    }
                    //and assign this position to the hash
                    bannerHashMap[bannerHash] = cachePosition;

                    //advance the pointer of the last added imagestrip.
                    lastCachePosition++;
                    if (lastCachePosition == AdvertConfig.bannerCacheSize)
                    {
                        lastCachePosition = 0;
                    }
                }
                else
                {
                    cachePosition = bannerHashMap[bannerHash];
                }

                string userSize = GetUserSize(userInfo);
                //this doesn't allow client-side auto resizing of images, may want to consider server side resizing
                ITable boardAd = MessageBuilder.Elements.CreateTable(messageToSend, "ad-" + bannerHash + "-" + userSize, 1, 1);
                boardAd.SelectionMode = SelectionRectType.Outline;
                boardAd.Style.Align = (AlignmentType)((int)AlignmentType.VerticalCenter + (int)AlignmentType.HorizontalCenter);
                boardAd.Mode = TableSendModeType.Update;
                //Mxit SDK 1.4.6 shows Frames.Set as obsolete, to be replaced with Frames.Add, but will break compatibility with older SDK's
                boardAd[0, 0].Frames.Set(bannerStripCache[cachePosition].GetStrip(userSize), 0);
                messageToSend.Append(boardAd);
            }

            else
            {
                int displayWidth = userInfo.DeviceInfo.DisplayWidth;
                int imageDisplayWidthPerc;

                if (displayWidth <= 128)
                {
                    imageDisplayWidthPerc = 99;
                }
                else
                {
                    imageDisplayWidthPerc = 100;
                }

                IMessageElement inlineImage = MessageBuilder.Elements.CreateInlineImage(adTodisplay.adImage, ImageAlignment.Center, TextFlow.AloneOnLine, imageDisplayWidthPerc);
                //IMessageElement inlineImage = MessageBuilder.Elements.CreateInlineImage(adTodisplay.adImageURL, ImageAlignment.Center, TextFlow.AloneOnLine);
                messageToSend.AppendLine(inlineImage);
            }
        }
Exemple #60
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
        }