protected void btnEnviar_Click(object sender, EventArgs e)
        {
            String account = "swap";

            String code = "zJmLTF7JvU";

            int contador = 0;
            try
            {
                if (Session["ListaSMS"] != null)
                {
                    List<SMS> listaSms = (List<SMS>)Session["ListaSMS"];
                    contador = ObterUltimoID() + 1;
                    foreach (var item in listaSms)
                    {
                        SimpleSending sms = new SimpleSending(account, code);

                        SimpleMessage message = new SimpleMessage();

                        message.To = item.Msisdn;
                        message.Message = item.Mensagem;
                        contador++;
                        message.Id = contador.ToString("0000");
                        List<String> response = sms.send(message);
                    }
                    lblResultado.Text = "Lote de SMS enviado com sucesso!";
                    SalvarUltimoID(contador);
                }
            }
            catch (Exception exx)
            {
                lblResultado.Text = "Ocorreu um erro no envio: " + exx.Message;
            }
        }
        private void SendMessages()
        {
            int i = 0;

            while (i < Program.SendMessagesBatchSize && Gmail.outgoingQueue.Count > 0)
            {
                SimpleMessage outgoing = new SimpleMessage();
                if (Gmail.outgoingQueue.TryDequeue(out outgoing))
                {
                    log.Info("Sending message " + outgoing.Subject + " to " + outgoing.To);
                    log.Debug("Body: " + outgoing.Body);
                    if (Gmail.SendMessage(outgoing.To, outgoing.Subject, outgoing.Body) == null)
                    {
                        outgoing.SendAttempts++;
                        if (outgoing.SendAttempts <= Program.MaxSendAttempts)
                        {
                            log.Warn("Failed to send message " + outgoing.Subject + " to " + outgoing.To + " retrying. Attempt " + outgoing.SendAttempts + ".");
                            log.Debug("Body: " + outgoing.Body);
                            Gmail.outgoingQueue.Enqueue(outgoing);
                        }
                        else
                        {
                            log.Error("Failed to send message " + outgoing.Subject + " to " + outgoing.To + " body " + outgoing.Body + "too many times.  WILL NOT RETRY.");
                        }
                    }
                }
                else
                {
                    log.Warn("Attempt to dequeue message failed.");
                }

                i++;
            }
        }
        protected void btnEnviar_Click(object sender, EventArgs e)
        {
            String account = "swap";

            String code = "zJmLTF7JvU";

            int contador = 0;
            try
            {
                contador = ObterUltimoID() + 1;

                SimpleSending sms = new SimpleSending(account, code);

                SimpleMessage message = new SimpleMessage();

                message.To = string.Format("55{0}{1}", txbDDD.Text, txbTelefone.Text);
                message.Message = RemoverAcentos(txbMensagem.Text);
                contador++;
                message.Id = contador.ToString("0000");
                List<String> response = sms.send(message);

                lblMsg.Text = "SMS enviado com sucesso!";
                SalvarUltimoID(contador);
                btnEnviar.Enabled = false;
            }
            catch (Exception exx)
            {
                lblMsg.Text = "Ocorreu um erro no envio: " + exx.Message;
            }
        }
Exemple #4
0
	protected void receive(SimpleMessage[] sma){
		show = true;
		//check if the last message is from me
		if(allMessages[allMessages.Count-1].sender != senderName)
			rt = Time.time;
		sp.y = Mathf.Infinity; //set the scroll
		pending = new List<string>(); //reset the pending message array
	}
    private void HandleOtherPlayerLeft(SimpleMessage message)
    {
        Debug.Log("Opponent player left, you won the game");
        opcb();
        NetworkStream stream = client.GetStream();

        stream.Close();
        client.Close();
    }
Exemple #6
0
 private void OnMessageReceived(SimpleMessage msg)
 {
     switch (msg.Data)
     {
     case BrowserQueryBuilderViewModel.MessageDone:
         CurrentModel = _browserQueryViewerViewModel;
         break;
     }
 }
 private void ConsumeMessage(SimpleMessage message)
 {
     switch (message.Type)
     {
     case SimpleMessage.MessageType.SettingsUpdated:
         HideConfig();
         break;
     }
 }
    // *** FOR SENDING MESSAGES (LOCAL PLAYER) *** //

    public SimpleMessage GetSpawnMessage()
    {
        SimpleMessage message  = new SimpleMessage(MessageType.Spawn);
        Vector3       pos      = this.character.transform.position;
        Quaternion    rotation = this.character.transform.rotation;

        message.SetFloats(pos.x, pos.y, pos.z, rotation.x, rotation.y, rotation.z, rotation.w);
        return(message);
    }
    static async Task Main()
    {
        Console.Title = "NServiceBusEndpoint";
        var endpointConfiguration = new EndpointConfiguration("NServiceBusEndpoint");

        endpointConfiguration.UseTransport <MsmqTransport>();
        endpointConfiguration.UseSerialization <NewtonsoftSerializer>();
        endpointConfiguration.EnableInstallers();
        endpointConfiguration.UsePersistence <InMemoryPersistence>();
        endpointConfiguration.SendFailedMessagesTo("error");

        #region DisableRetries

        var recoverability = endpointConfiguration.Recoverability();

        recoverability.Delayed(
            customizations: retriesSettings =>
        {
            retriesSettings.NumberOfRetries(0);
        });
        recoverability.Immediate(
            customizations: retriesSettings =>
        {
            retriesSettings.NumberOfRetries(0);
        });

        #endregion

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

        Console.WriteLine("Press 'Enter' to send a new message. Press any other key to finish.");
        while (true)
        {
            var key = Console.ReadKey();

            if (key.Key != ConsoleKey.Enter)
            {
                break;
            }

            var guid = Guid.NewGuid();

            var simpleMessage = new SimpleMessage
            {
                Id = guid
            };
            await endpointInstance.Send("NServiceBusEndpoint", simpleMessage)
            .ConfigureAwait(false);

            Console.WriteLine($"Sent a new message with Id = {guid}.");

            Console.WriteLine("Press 'Enter' to send a new message. Press any other key to finish.");
        }
        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }
        private void ChatHubProxyOnMessageReceived(SimpleMessage receivedMessage)
        {
            receivedMessage.IsLocalMessage = false;

            Application.Current.Dispatcher.Invoke(() =>
            {
                MessageReceivedHandler?.Invoke(new MessageReceivedEventArgs(CipherHelper.DecryptMessage(receivedMessage)));
            });
        }
        private async Task AndAMessageIsPublished()
        {
            _message = new SimpleMessage {
                Id = Guid.NewGuid()
            };
            await _publisher.PublishAsync(_message);

            await Task.Delay(TimeSpan.FromSeconds(1));
        }
Exemple #12
0
        void SendPollMessage(byte address)
        {
            var msg = new SimpleMessage(eControl.LP_Polling)
            {
                TypeDest = eDevice.LedPanel, Address = address
            };

            this.Presentation.SendData(msg);
        }
Exemple #13
0
        public async Task HandleMessageFromQueueLogs_ShouldHaveContext(bool handlerShouldSucceed, LogLevel level, string status, string exceptionMessage)
        {
            var handler = new InspectableHandler <SimpleMessage>()
            {
                ShouldSucceed = handlerShouldSucceed,
            };

            if (exceptionMessage != null)
            {
                handler.OnHandle = msg => throw new Exception(exceptionMessage);
            }

            var services = GivenJustSaying(levelOverride: LogLevel.Information)
                           .ConfigureJustSaying(
                (builder) => builder.WithLoopbackQueue <SimpleMessage>(UniqueName)
                .Subscriptions(sub => sub.WithDefaults(sgb =>
                                                       sgb.WithDefaultConcurrencyLimit(10))))
                           .AddSingleton <IHandlerAsync <SimpleMessage> >(handler);

            var sp = services.BuildServiceProvider();

            var cts = new CancellationTokenSource();

            var publisher = sp.GetRequiredService <IMessagePublisher>();
            await publisher.StartAsync(cts.Token);

            await sp.GetRequiredService <IMessagingBus>().StartAsync(cts.Token);

            var message = new SimpleMessage();
            await publisher.PublishAsync(message, cts.Token);

            await Patiently.AssertThatAsync(() => handler.ReceivedMessages
                                            .ShouldHaveSingleItem()
                                            .Id.ShouldBe(message.Id));

            var testLogger = sp.GetRequiredService <ITestLoggerSink>();

            await Patiently.AssertThatAsync(() =>
            {
                var handleMessage = testLogger.LogEntries
                                    .SingleOrDefault(le => le.OriginalFormat == "{Status} handling message with Id '{MessageId}' of type {MessageType} in {TimeToHandle}ms.");

                handleMessage.ShouldNotBeNull();

                handleMessage.LogLevel.ShouldBe(level);
                handleMessage.Exception?.Message.ShouldBe(exceptionMessage);

                var propertyMap = new Dictionary <string, object>(handleMessage.Properties);
                propertyMap.ShouldContainKeyAndValue("Status", status);
                propertyMap.ShouldContainKeyAndValue("MessageId", message.Id);
                propertyMap.ShouldContainKeyAndValue("MessageType", message.GetType().FullName);
                propertyMap.ShouldContainKey("TimeToHandle");
            });

            cts.Cancel();
        }
        void Awake()
        {
            ExecuteOnMainThread       = new Queue <Action>();
            _creatureHelper           = GameObject.Find("GameManager").GetComponent <CreatureHelper>();
            _player                   = Networking.Network.Instance.ClientPlayer;
            _creatureHelper.Creatures = new List <AbstractCreature>();

            MustAttack = false;
            _canMove   = false;

            GameFlow.Instance.Channel = new NetworkMessageChannel(_player);
            GameFlow.Instance.Channel.MoveCallback        += DrawPath;
            GameFlow.Instance.Channel.TurnCallback        += ChangeTurn;
            GameFlow.Instance.Channel.SyncHeroesCallback  += SyncHero;
            GameFlow.Instance.Channel.Attack              += Attack;
            GameFlow.Instance.Channel.GameIsReadyCallback += GameIsReady;
            GameFlow.Instance.Channel.DieCallback         += Die;
            GameFlow.Instance.Channel.FinishGame          += FinishGame;

            Messenger <TileBehaviour> .AddListener("Tile selected", MoveCreatureToSelectedTile);

            Messenger <CreatureComponent> .AddListener("Action finish", FinishAction);

            Messenger <CreatureComponent> .AddListener("CreatureComponent Selected", MouseOverCreature);

            Messenger <CreatureComponent> .AddListener("CreatureComponent Exit", MouseExitCreature);

            Messenger <CreatureComponent> .AddListener("CreatureComponent Attack", MouseClickCreature);

            _hero1Obj = Instantiate(Hero1Prefab) as GameObject;
            _hero2Obj = Instantiate(Hero2Prefab) as GameObject;

            _prefabCollector = PrefabDatabase.GetComponent <PrefabCollector>();

            _creaturePrefabDictionary.Add("Marksman", "GoblinHex");
            _creaturePrefabDictionary.Add("Troglodyte", "OrcHex");

            _creatureHelper.PlayerLeft.text  = GameFlow.Instance.PlayerLeftName;
            _creatureHelper.PlayerRight.text = GameFlow.Instance.PlayerRightName;

            _imageDictionary = new Dictionary <NetworkTypes.CreatureType, Sprite>()
            {
                { NetworkTypes.CreatureType.Range, _prefabCollector.CreatureImages.SingleOrDefault(x => x.Name == "Range").Image },
                { NetworkTypes.CreatureType.Melee, _prefabCollector.CreatureImages.SingleOrDefault(x => x.Name == "Melee").Image }
            };

            var roomName = new SimpleMessage {
                Message = GameFlow.Instance.RoomName
            };
            var parameters = new List <SerializableType> {
                roomName
            };
            var remoteInvokeMethod = new RemoteInvokeMethod("", Command.InitializeBoard, parameters);

            Client.BeginSendPackage(remoteInvokeMethod);
        }
        public void SendMessage(string message, bool compress = false, bool encrypt = false, bool close = false)
        {
            var messageBuilder = new SimpleMessage(MessageType.Message, this, Debug)
                                 .CompressMessage(compress)
                                 .EncryptMessage(encrypt)
                                 .SetMessage(message);

            messageBuilder.Build();
            SendToSocket(messageBuilder.PayLoad, close, false);
        }
Exemple #16
0
        public void Serialize(SimpleMessage <TMessageKey> item, Stream target)
        {
            Guard.IsNull(() => item);
            keySerializer.Serialize(item.Key, target);
            var data        = item.Data ?? new byte[0];
            var writeBuffer = BinarySerializerService.SingletonBitConverter.GetBytes(data.Length);

            target.Write(writeBuffer, 0, writeBuffer.Length);
            target.Write(data, 0, data.Length);
        }
    private void handleSimpleMessage(LobbyClient pClient, SimpleMessage _simpleMessage)
    {
        _simpleMessage.id = pClient.id;

        Console.WriteLine("client " + pClient.id + " said " + _simpleMessage.text);
        foreach (LobbyClient client in _clients)
        {
            sendObject(client.TcpClient, _simpleMessage);
        }
    }
 /// <summary>
 /// Handles SimpleMessage from child nodes
 /// </summary>
 /// <param name="request"></param>
 /// <param name="context"></param>
 /// <returns></returns>
 public override Task <SimpleMessageReply> SendSimpleMessage(SimpleMessage request, ServerCallContext context)
 {
     // TODO:
     _logger.LogInformation($"got a SimpleMessage from {request.ClientAddr}");
     _connectionManager.RemoveChildNode(request.ClientAddr);
     return(Task.FromResult(new SimpleMessageReply
     {
         Message = "Goodbye " + request.ClientAddr
     }));
 }
Exemple #19
0
        public void Should_use_converter_for_deserialization()
        {
            var obj = new SimpleMessage {
                ValueB = "Joe"
            };

            SimpleMessage result = SerializeAndReturn(obj);

            result.ValueB.ShouldEqual("Monster");
        }
Exemple #20
0
 public static SimpleMessage[] parseChatText(string s)
 {
     string[]        lines = s.Split(SimChatNetwork.splt, System.StringSplitOptions.RemoveEmptyEntries);
     SimpleMessage[] o     = new SimpleMessage[lines.Length];
     for (int l = 0; l < lines.Length; l++)
     {
         o[l] = new SimpleMessage(lines[l]);
     }
     return(o);
 }
		private static IMsg CreateMessage(string sender, string msg)
		{
			IMsg simpleMessage = new SimpleMessage()
			{
				Id = new Guid(),
				Body = msg
			};
			simpleMessage.Header.Sender = sender;
			return simpleMessage;
		}
        public void SendBytes(byte[] data, bool compress = false, bool encrypt = false, bool close = false)
        {
            var builder = new SimpleMessage(MessageType.Bytes, this, Debug)
                          .CompressMessage(compress)
                          .EncryptMessage(encrypt)
                          .SetBytes(data);

            builder.Build();
            SendToSocket(builder.PayLoad, close, false);
        }
        public async Task <Unit> Handle(SimpleMessageRequest simpleMessageRequest, CancellationToken cancellationToken)
        {
            var simpleMessage = new SimpleMessage
            {
                Message = simpleMessageRequest.Message
            };
            await publishEndpoint.Publish(simpleMessage, cancellationToken);

            return(Unit.Value);
        }
Exemple #24
0
        public void Should_use_converter_for_serialization()
        {
            var obj = new SimpleMessage {
                ValueA = "Joe"
            };

            var result = SerializeAndReturn(obj);

            result.ValueA.ShouldBe("Monster");
        }
Exemple #25
0
        public void SendTemperatureToDB(int deviceId, DateTime timestamp, double temperature, double humidity)
        {
            if (bSBViaHttp && messagingClient != null)
            {
                try
                {
                    this.TraceLog("Sending Temperature data to SB via HTTP");
                    SimpleMessage message = new SimpleMessage()
                    {
                        BrokerProperties = { { "SessionId", deviceId }, { "Label", "Temperature" } },
                        Properties       =
                        {
                            { AmqpSendReceiveBase.strPropertyDeviceGatewayDeviceId, deviceId    },
                            { AmqpSendReceiveBase.strPropertyEventTimestamp,        timestamp   },

                            { "DeviceTemperature",                                  temperature },
                            { "DeviceRelativeHumidity",                             humidity    },
                        },
                    };
                    this.messagingClient.Send(message);
                    this.TraceLog("Sent Temperature data to SB via HTTP");
                }
                catch (Exception e)
                {
                    this.TraceLog("Failure sending Temperature to SB via HTTP: " + e.Message);
                }
            }
            if (bSBViaAmqp && this.SBSender != null)
            {
                try
                {
                    this.TraceLog("Sending Temperature to SB via AMQP");

                    Message message = new Message();

                    message.Properties         = new Amqp.Framing.Properties();
                    message.Properties.Subject = "Temperature";
                    message.Properties.GroupId = deviceId.ToString();

                    message.ApplicationProperties = new Amqp.Framing.ApplicationProperties();
                    message.ApplicationProperties[AmqpSendReceiveBase.strPropertyDeviceGatewayDeviceId] = deviceId;
                    message.ApplicationProperties[AmqpSendReceiveBase.strPropertyEventTimestamp]        = timestamp;
                    message.ApplicationProperties[AmqpSendReceiveBase.strPropertySendTimestamp]         = DateTime.UtcNow;

                    message.ApplicationProperties["DeviceTemperature"]      = temperature;
                    message.ApplicationProperties["DeviceRelativeHumidity"] = humidity;

                    this.SBSender.SendOrEnqueueMessage(message);
                }
                catch (Exception e)
                {
                    this.TraceLog("Failure sending Temperature to SB via AMQP: " + e.Message);
                }
            }
        }
Exemple #26
0
        public static async Task <OperationResult> AdjustUserRoleLevel(string adminId, string uid, int rid, int del)
        {
            OperationResult OpResult = new OperationResult();
            var             maxp     = await MemberAdminContext.GetMaxPriority(adminId);

            var cntx = Cntx;
            UserServiceProxy usvc = new UserServiceProxy();
            var u = usvc.LoadEntityByKey(cntx, uid);

            if (u == null)
            {
                OpResult.Result = new { ok = false, msg = string.Format(ResourceUtils.GetString("b66098049404e4de1356242e8aa6444a", "User \"{0}\" is not found."), uid) };
                return(OpResult);
            }
            UsersInRoleServiceProxy uirsvc = new UsersInRoleServiceProxy();
            var uir = await uirsvc.LoadEntityByKeyAsync(cntx, rid, u.ID);

            if (uir == null)
            {
                OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("78257cace857db766d54e6568d7f912b", "The user is not in this role.") };
                return(OpResult);
            }
            uir.RoleRef = await uirsvc.MaterializeRoleRefAsync(cntx, uir);

            if (maxp.Major < uir.RoleRef.RolePriority || maxp.Major == uir.RoleRef.RolePriority && uir.SubPriority + del > maxp.Major)
            {
                OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("5986d63fe301793ee7f5b2134a8f8787", "Modifying more priviledged role is not authorized.") };
                return(OpResult);
            }
            var oldPrio = uir.SubPriority;

            uir.SubPriority += del;
            uir.LastModified = DateTime.UtcNow;
            uir.AdminID      = adminId;
            await uirsvc.AddOrUpdateEntitiesAsync(cntx, new UsersInRoleSet(), new UsersInRole[] { uir });

            uir.UserID = u.ID;
            uir.RoleID = rid;
            await AddUserRoleHistory(uir, UserRoleOperations.Modified);

            UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();
            var memb = await mbsvc.LoadEntityByKeyAsync(cntx, AppId, uid);

            var notice = new SimpleMessage
            {
                TypeId = 1,
                Title  = string.Format(ResourceUtils.GetString("54da39696e8014b5ded7a0eaeac1dfc4", "The relative priority of your role: [{0}] is changed from {1} to {2}.", memb.AcceptLanguages),
                                       uir.RoleRef.DistinctString, oldPrio, uir.SubPriority),
                Data = "{ id=\"" + rid + "\", type=\"role\", name=\"" + uir.RoleRef.DistinctString + "\" }"
            };

            OpResult.Result  = new { ok = true, msg = "" };
            OpResult.notices = new SimpleMessage[] { notice };
            return(OpResult);
        }
Exemple #27
0
    // Update is called once per frame
    void Update()
    {
        if (TextInputEnabled)
        {
            foreach (char c in Input.inputString)
            {
                if (c == '\b') //backspace / delete lmao
                {
                    if (TextBoxSend.text.Length != 0)
                    {
                        TextBoxSend.text = TextBoxSend.text.Substring(0, TextBoxSend.text.Length - 1);
                    }
                }
                else if (c == '\n' || c == '\r') //enter / return
                {
                    SimpleMessage simpleMessage = new SimpleMessage();
                    simpleMessage.Message  = TextBoxSend.text;
                    simpleMessage.Username = Username;
                    List_MessageCollection.Add(simpleMessage);
                    string JsonEncoded = JsonUtility.ToJson(simpleMessage);

                    SendMessageRabbitMQ(JsonEncoded);
                    TextBoxSend.text = "";
                }
                else
                {
                    if (TextBoxSend.text == "Type a message!")
                    {
                        TextBoxSend.text = "";
                    }
                    TextBoxSend.text += c;
                }
            }
            if (List_MessageCollection.Count > 25)
            {
                List_MessageCollection.RemoveAt(0);
            }
            if (List_TilingMessages_Collision.Count > 6)
            {
                List_TilingMessages_Collision.RemoveAt(0);
            }
            if (List_TilingMessages_PositionUpdates.Count > 6)
            {
                List_TilingMessages_PositionUpdates.RemoveAt(0);
            }
            if (List_StocksMessaging_MarketPrice.Count > 6)
            {
                List_StocksMessaging_MarketPrice.RemoveAt(0);
            }
            if (List_StocksMessaging_Sell_n_BuyRequests.Count > 6)
            {
                List_StocksMessaging_Sell_n_BuyRequests.RemoveAt(0);
            }
        }
    }
Exemple #28
0
        public FakeSerializationRegister()
        {
            var defaultMessage = new SimpleMessage
            {
                RaisingComponent = "Component",
                Id = Guid.NewGuid()
            };

            DefaultDeserializedMessage      = () => defaultMessage;
            ReceivedDeserializationRequests = new List <string>();
        }
 public void ShowAbout(bool force)
 {
     if (force || Config.ShowAbout)
     {
         SimpleMessage.ShowAbout("This FREE tool is provided \"AS IS\" with no warranties,\r\nand confers no rights.\r\n" +
                                 "Use it at your own risk.\r\n\r\n" +
                                 "Credits:\r\n.Net Reflector\r\nBe.HexEditor\r\nde4dot\r\nILMerge\r\nILSpy\r\nMicrosoft (gacutil, ilasm, ildasm, peverify, sn, CLR Profiler, ...)\r\nMono Cecil\r\n......"
                                 );
         Config.ShowAbout = false;
     }
 }
        public virtual void PostMsgText(IMsgChannel userChannel)
        {
            IMsg msg = new SimpleMessage()
            {
                Id   = new Guid(),
                Body = MessageText
            };

            msg.Header.Sender = SenderName;
            userChannel.PostMessage(msg);
        }
Exemple #31
0
        public IActionResult Greetings()
        {
            var message = new SimpleMessage()
            {
                By       = "System",
                Message  = "Welcome",
                DateTime = DateTime.Now
            };

            return(Ok(message));
        }
        private void SendSimpleMessage(int senderId, int index)
        {
            SimpleMessage message = new SimpleMessage
            {
                Id   = index,
                Text = "This is simple message from " + senderId
            };

            SendMessage(message);
            Console.WriteLine("Sent simple message #{0} from sender {1}", index, senderId);
        }
Exemple #33
0
 public int ObterQuantidadeDeMensagemPorUser(SimpleMessage mensagem)
 {
     try
     {
         return(_messageCollection.Find(x => x.Id_Usuario == mensagem.Id_Usuario).ToList().Count());
     }
     catch (Exception)
     {
         return(0);
     }
 }
 //Send message to single client
 private void SendMessage(TcpClient client, SimpleMessage msg)
 {
     try
     {
         NetworkProtocol.Send(client, msg);
     }
     catch (Exception e)
     {
         this.clientsToRemove.Add(client);
     }
 }
        /// <summary>
        /// </summary>
        /// <param name="notifyMessage"></param>
        public void Send(SimpleMessage notifyMessage)
        {
            Content content = notifyMessage.Content;
            var mailMessage =
                new MailMessage(new MailAddress(SupportEmail),
                                new MailAddress(notifyMessage.User.Contact.Email))
                    {
                        Body = content.Value,
                        Subject = content.Subject,
                        IsBodyHtml = true
                    };

            _smtpClient.Send(mailMessage);
        }
        public void ParseMessage(SimpleMessage message)
        {
            int id = ProcessSubject(message);

            if (id == -1)
            {
                ProcessActions(message, null);
            }
            else if (id >= 0)
            {
                Game game = GameSystem.Instance.GetGameById(id);
                if (game == null)
                {
                    HandleBadMessage(message, "You referenced an invalid game id: " + id);
                }
                else ProcessActions(message, game);
            }
        }
Exemple #37
0
        public void SimpleActorTestTestTell()
        {
            const string signalName = "SimpleActor.Test";
            var signal = new EventWaitHandle(false, EventResetMode.AutoReset, signalName);

            var system = new ActorSystem("test");

            var actorRef = system.ActorOf<SimpleActor>();

            var message = new SimpleMessage("hello", signalName);

            actorRef.Tell(message);

            if (!signal.WaitOne(TimeSpan.FromSeconds(5)))
            {
                Assert.Fail("timed out waiting for actor to process message");
            }
        }
        protected void btnEnviar_Click(object sender, EventArgs e)
        {
            String account = "swap";

            String code = "zJmLTF7JvU";

            int contador = 0;
            try
            {
                contador = HumanHelper.ObterUltimoID();

                SimpleSending sms = new SimpleSending(account, code);

                SimpleMessage message = new SimpleMessage();

                message.To = string.Format("55{0}{1}", txbDDD.Text, txbCelular.Text);
                string msg = txbMensagem.Text+" ";
                EncurtadorURL encurtador = new EncurtadorURL();
                string url = ConfigurationManager.AppSettings["URLBOLETO"].ToString() + "?banco="+ddlBanco.SelectedValue+"&sacado=" + txbNome.Text + "&endereco=" + txbEndereco.Text + "&cpf=" + txbCPF.Text + "&cidade=" + txbCidade.Text + "&uf=" + txbUF.Text + "&bairro=" + txbBairro.Text + "&cep=" + txbCEP.Text+"&valor="+txbValor.Text.Replace('.',',');
                string urlReduzida = encurtador.LengthenUrl(url);
                msg += urlReduzida;
                message.Message = HumanHelper.RemoverAcentos(msg);
                contador++;
                message.Id = contador.ToString("0000");
                lblMsgEnviada.Text = message.Message;
                hlLink.NavigateUrl = url;
                hlLink.Text = url;

                hlLinkReduzida.NavigateUrl = urlReduzida;
                hlLinkReduzida.Text = urlReduzida;
                List<String> response = sms.send(message);

                lblResultado.Text = "SMS com boleto enviado com sucesso!";
                btnEnviar.Enabled = false;
                btnLimpar.Enabled = true;
            }
            catch (Exception exx)
            {
                lblResultado.Text = "Ocorreu um erro no envio: " + exx.Message;
            }

            //EncurtadorURL encurtador = new EncurtadorURL();
            //string urlReduzida = encurtador.LengthenUrl(ConfigurationManager.AppSettings["URLBOLETO"].ToString()+"?sacado="+txbNome.Text+"&endereco="+txbEndereco.Text+"&cpf="+txbCPF.Text+"&cidade="+txbCidade.Text+"&uf="+txbUF.Text+"&bairro="+txbBairro.Text+"&cep="+txbCEP.Text);// "http://localhost:1057/BoletoBB.aspx");
        }
        public void Simple()
        {
            var unity = new UnityContainer();
            var tracker = new Tracker();
            unity.RegisterInstance(tracker);

            var registrator = new HandlerRegistrator(unity);
            registrator.RegisterAssemblies(new[] { Assembly.GetExecutingAssembly() });

            var dispatcher = new Dispatcher(unity, registrator);

            var message = new SimpleMessage();
            dispatcher.Dispatch(message);

            var message2 = new SimpleMessage2();
            dispatcher.Dispatch(message2);

            Assert.AreEqual(2, tracker.Handlers.Count);
            Assert.AreEqual(typeof(SimpleMessage), tracker.Handlers[0]);
            Assert.AreEqual(typeof(SimpleMessage2), tracker.Handlers[1]);
        }
Exemple #40
0
	//functions to call when a new message is received
	void receiveMessage1(SimpleMessage[] sm){
		rt1 = Time.time;
		Debug.Log (sm.Length);
		
		foreach(SimpleMessage smIn in sm){
			
			GameObject clone;
			//check if the sender had the same name as me, and change the color
			if(smIn.sender == sender){ //yo
				clone = Instantiate(chatYo, chatYo.transform.position, chatYo.transform.rotation) as GameObject;
				clone.transform.SetParent(chatYo.transform.parent);
				clone.transform.Find("PanelC/Panel/PerfilMask/ImagePerfil").GetComponent<Image> ().sprite = userImage;
				
			}else{
				clone = Instantiate(chatEl, chatEl.transform.position, chatEl.transform.rotation) as GameObject;
				clone.transform.SetParent(chatEl.transform.parent);
				clone.transform.Find("PanelC/Panel/PerfilMask/ImagePerfil").GetComponent<Image> ().sprite = amigoImage;
				
			}
			
			
			//get date:
			System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
			dateTime = dateTime.AddSeconds( Double.Parse(smIn.time.ToString()) );
			string printDate = dateTime.ToShortDateString() +" "+ dateTime.ToLongTimeString();
			
			//sumScroll += clone.transform.GetComponent<Text> ().preferredHeight;
			//Debug.Log("preferredHeight: " +clone.transform.GetComponent<Text> ().preferredHeight);
			//yChatCount -= 0.5f;
			
			//clone.GetComponent<RectTransform>().pivot = new Vector2(GameObject.Find("PanelContent").GetComponent<RectTransform>().pivot.y, 0);
			clone.transform.localScale = new Vector3(1, 1, 1);
			clone.SetActive(true);
			//Debug.Log(smIn.message);
			clone.transform.Find("PanelC/PanelP/TextMgs").GetComponent<Text> ().text = smIn.message.Replace("&#10;"," ");
			clone.transform.Find("PanelC/PanelP/TextTime").GetComponent<Text> ().text = smIn.sender + " " + printDate;
			
			
			Debug.Log("dice q fecha: " + printDate);
			
			
			//ScrollObj.GetComponent<ScrollRect>().verticalNormalizedPosition = -1;
			//normalizedPosition
			//ScrollObj.GetComponent<RectTransform>().sizeDelta = new Vector2(ScrollObj.GetComponent<RectTransform>().rect.width, sumScroll); 
		}
		
		
		
		//string _nID = ScheduleLocalNotification (CreateNotification (1, eNotificationRepeatInterval.NONE));
		
		StartCoroutine (scrollDown ());
	}
        public void Should_handle_a_missing_nullable_value()
        {
            var obj = new SimpleMessage("");

            SimpleMessage result = SerializeAndReturn(obj);

            result.Body.ShouldBe(obj.Body);
        }
 private static void TextMessageHandler(string side, SimpleMessage<int> message, int size)
 {
     Console.WriteLine(@"{0}: Received Message (Size: {3} Bytes), Type {1}, Contents: {2}", side, message.Key,
         Encoding.ASCII.GetString(message.Data), size);
 }
 private void SendAction(Game game, Player p, Player candidate, string actionText)
 {
     SimpleMessage msg = new SimpleMessage();
     msg.From = p.Address;
     msg.Subject = "New Game";
     if(game != null) msg.Subject = game.FullTitle;
     msg.Body = actionText + " " + candidate.Name.ToLowerInvariant();
     MessageParser.Instance.ParseMessage(msg);
 }
        private List<Action> ParseActions(SimpleMessage message, Player player, Game game)
        {
            List<Action> actions = new List<Action>();

            foreach (string line in message.BodyAsLines())
            {
                Action action = null;
                if (player != null && game != null && game.IsInProgress)
                {
                    action = ParseGameAction(line, player, game);
                }
                if (action == null)
                {
                    action = ParseSystemAction(line);
                }
                if (action != null) actions.Add(action);
            }

            return actions;
        }
Exemple #45
0
	//functions to call when a new message is received
	void receiveMessage1(SimpleMessage[] sm){
		rt1 = Time.time;
		//agregar notificacion de chat recibido
		string _nID = ScheduleLocalNotification(CreateNotification(1, eNotificationRepeatInterval.NONE));
	}
 private void HandleBadMessage(SimpleMessage message, string error)
 {
     log.Warn("Malformed request: " + message.Subject + " from " + message.From);
     log.Debug("Body: " + message.Body);
     Gmail.MessagePerson(message.From, message.Subject, error);
 }
 public void NewGame(SimpleMessage message, List<Action> actions)
 {
     string address = message.From;
     string name = "";
     Action joinAction = null;
     foreach (Action action in actions)
     {
         if (action.Type == ActionEnum.JoinAs) joinAction = action;
     }
     name = joinAction.Text;
     Player player = new Player(name, address);
     if (String.IsNullOrEmpty(name))
     {
         HandleBadAction(null, player, joinAction, "You didn't specify the name you wished to join the game as. To do this send a new email with \"Join as <i>name</i>\" where <i>name</i> is your name.");
         return;
     }
     Game game = GetGameByPlayer(player);
     if (game != null)
     {
         HandleBadAction(null, player, joinAction, "You are already playing in " + game + " , you may only play one game at a time.");
         return;
     }
     game = new Game(GetNextGameId(), player);
     Games.Add(game);
     Gmail.MessagePlayer(player, game, game.Title + " has been started, you are the <b>Overlord</b>."
         + "<br /><br />Have your friends join by sending a message with the subject \"" + game.Title + "\" and body \"Join as <i>name</i>\" where <i>name</i> is their name.<br />"
         + game.Help(player)
         + "<br /><hr><br />" + Program.License.Replace('\n'.ToString(), "<br />")
         + "<br /><br />Download this program on " + Program.GitHub);
     gameLog.Info("Started new game: " + game);
 }
        /// <summary>
        /// Processes all actions in the message, calls <see cref="ParseActions(SimpleMessage)"/> to get a list of valid actions.
        /// Passes each action to <see cref="GameSystem.PerformAction(Game, Player, Action)"/>.
        /// </summary>
        /// <param name="message">The message to process</param>
        /// <param name="game">The game the player is playing in</param>
        /// <seealso cref="ParseActions(SimpleMessage)"/>
        private void ProcessActions(SimpleMessage message, Game game)
        {
            GameSystem gameSystem = GameSystem.Instance;
            string address = message.From;
            Player player = null;
            if (game != null) player = game.GetPlayer("", address);
            List<Action> actions = ParseActions(message, player, game);

            if (game == null) gameSystem.NewGame(message, actions);
            else if (player == null) gameSystem.ValidateJoinAction(address, actions, game);
            else
            {
                foreach (Action action in actions)
                {
                    gameSystem.PerformAction(game, player, action);
                }
            }
        }
 private void HandleBadMessage(SimpleMessage message, string error, Exception e)
 {
     log.Warn("Exception thrown when parsing message: " + e.Message);
     HandleBadMessage(message, error);
 }
 /// <summary>
 /// Process the message subject, returning the id of the game referenced, or -1 if referencing a new game request.  Otherwise -2 for malformed requests.
 /// </summary>
 /// <param name="message"></param>
 /// <returns></returns>
 private int ProcessSubject(SimpleMessage message)
 {
     try
     {
         string subject = message.Subject.Trim().ToLowerInvariant();
         if (subject.StartsWith("new game")) return -1;
         string strId = subject.GetTextAfter("game");
         if (strId.Contains(" ")) strId = strId.GetTextBefore(" ");
         if (String.IsNullOrEmpty(strId)) throw new Exception("No game Id found.");
         int id = Int32.Parse(strId);
         return id;
     }
     catch (Exception e)
     {
         HandleBadMessage(message, "Invalid syntax in your subject, should be \"Game #\" where # is your game id.", e);
         return -2;
     }
 }
 public void Send(SimpleMessage notifyMessage)
 {
     DaoFactory.SimpleMessageDao.SaveOrUpdate(notifyMessage);
 }
Exemple #52
0
 //functions to call when a new message is received
 void receiveMessage1(SimpleMessage[] sm)
 {
     rt1 = Time.time;
 }
        public void Should_use_converter_for_serialization()
        {
            var obj = new SimpleMessage {ValueA = "Joe"};

            SimpleMessage result = SerializeAndReturn(obj);

            result.ValueA.ShouldBe("Monster");
        }
Exemple #54
0
 void receiveMessage2(SimpleMessage[] sm)
 {
     rt2 = Time.time;
 }