public WebSocketConnection(Socket socket, WebSocketWrapper websocket, SubProtocolModelFactoryWrapper modelfactory)
 {
     Sender = new Sender(socket, websocket);
     Receiver = new Receiver(socket, websocket, modelfactory);
     Sender.Connection = this;
     Receiver.Connection = this;
 }
Example #2
0
 public RegularLogger(string category, Sender sender, int level)
 {
     this.category = category;
     senders[0] = NullSend;
     senders[1] = sender ?? NullSend;
     SetLevel(level);
 }
Example #3
0
 public MyNickInfo(string ServerName)
 {
     _servername = ServerName;
     _Identify = false;
     _Vhost = false;
     sSender = sIrcBase.Networks[ServerName].sSender;
 }
 public WebSocketConnection(Socket socket, WebSocketWrapper websocket)
 {
     Sender = new Sender(socket, websocket);
     Receiver = new Receiver(socket, websocket);
     Sender.Connection = this;
     Receiver.Connection = this;
 }
 public ResetPasswordTests(ITestOutputHelper output) {
     _output = output;
     _server = new TestServer(new WebHostBuilder()
         .UseStartup<Startup>());
     _client = _server.CreateClient();
     _sender = _server.Host.Services.GetService<ISmsSender>() as Sender;
 }
Example #6
0
        static void Main(string[] args)
        {
            Description desc = new Description("C# Dummy", "dummy");
            desc.addDataSeries("val1", new DataSeriesInfo(Value.Type.STRING, 0, ""));
            desc.addDataSeries("val2", new DataSeriesInfo(Value.Type.DOUBLE, (int)DataSeriesInfo.Property.INTERPOLATABLE, ""));
            desc.addDataSeries("val3", new DataSeriesInfo(Value.Type.DOUBLE, (int)(DataSeriesInfo.Property.INTERPOLATABLE | DataSeriesInfo.Property.HAS_MINMAX), "", 0.0, 1.0));

            int cnt = 0;

            using (Sender sender = new Sender(desc, new StringMap()))
            {
                DataMessage msg = sender.createDataMessage();

                long start = DateTime.Now.Ticks;
                while (DateTime.Now.Ticks < start + 5 * TimeSpan.TicksPerSecond)
                {
                    msg.setString("val1", "hello");
                    msg.setDouble("val2", 42.0);
                    msg.setDouble("val3", 0.5);
                    sender.sendMessage(msg);
                    cnt++;
                }
            }

            System.Console.Out.WriteLine(cnt);
            System.Console.ReadLine();
        }
        public ConnectionUDP(Route route, string dstHost, int dstPort,
                             int mode, int connectId, ClientControl clientControl)
        {
            MyClientControl = clientControl;
            MyRoute = route;
            DstHost = dstHost;
            DstPort = dstPort;
            Mode = mode;
            ConnectId = connectId;

            try
            {
                MySender = new Sender(this);
                MyRecevier = new Receiver(this);
                Uos = new UDPOutputStream(this);
                Uis = new UDPInputStream(this);
                /*
                if (mode == 2)
                {
                    route.CreateTunnelProcessor().Process(this);
                }
                */
            }
            catch (Exception e)
            {
                _connected = false;
                route.ConnTable.Remove(connectId);

                lock (this)
                {
                    Monitor.PulseAll(this);
                }
                throw (e);
            }
        }
 public WebSocketConnection()
 {
     Sender = new Sender();
     Receiver = new Receiver();
     Sender.Connection = this;
     Receiver.Connection = this;
 }
Example #9
0
 private static void TweetThis(TwitterClient twitterClient, Tweet tweet, Sender<TweetStatus> sender) {
     var response = twitterClient.Tweet(tweet.Message, tweet.Token);
     var tweetStatus = new TweetStatus {
         CorrelationId = tweet.CorrelationId,
         Status = response
     };
     sender.Send(tweetStatus);
 }
 public Receiver(ConnectionUDP conn)
 {
     Conn = conn;
     Uis = new UDPInputStream(conn);
     MySender = conn.MySender;
     DstHost = conn.DstHost;
     DstPort = conn.DstPort;
 }
        protected override void DoSetUp()
        {
            sender = new Sender();
            receiver = new Receiver();
            transport = new EncryptionAndCompressionTransportDecorator(sender, receiver);

            Console.WriteLine(RijndaelHelper.GenerateNewKey());
        }
Example #12
0
        public void SendShouldCallBasicPublishWithSuppliedArguments()
        {
            SetupRabbitMqFactoryDefault();
            var sender = new Sender(QueueEndpointProvider, RabbitMqFactory, ChannelConfigurator);
            sender.Send("testendpoint", MessageData, MessageProperties);

            Model.AssertWasCalled(x => x.BasicPublish(GetExchangeName(), QueueEndpoint.RoutingKey, Properties, MessageData));
        }
Example #13
0
        public void SendMessageToSubscriber()
        {
            var sender = new Sender();
            var s = new Subscriber();
            sender.Send(180);

            Assert.That(s.Value, Is.EqualTo(180));
        }
Example #14
0
        public void SendShouldSetCorrelationIdOnProperties()
        {
            MessageProperties.CorrelationId = "asdfklöj";
            SetupRabbitMqFactoryDefault();
            var sender = new Sender(QueueEndpointProvider, RabbitMqFactory, ChannelConfigurator);
            sender.Send("testendpoint", MessageData, MessageProperties);

            Assert.AreEqual(MessageProperties.CorrelationId, Properties.CorrelationId);
        }
Example #15
0
        public void SendShouldCallExchangeDeclareIfExchangeIsEmpty()
        {
            var exchange = string.Empty;
            SetupRabbitMqFactoryWithExchange(exchange);
            var sender = new Sender(QueueEndpointProvider, RabbitMqFactory, ChannelConfigurator);
            sender.Send("testendpoint", MessageData, MessageProperties);

            Model.AssertWasNotCalled(x => x.ExchangeDeclare(exchange, "fanout"));
        }
Example #16
0
        public void SendShouldCallExchangeDeclare()
        {
            const string exchange = "abc";
            SetupRabbitMqFactoryWithExchange(exchange);
            var sender = new Sender(QueueEndpointProvider, RabbitMqFactory, ChannelConfigurator);
            sender.Send("testendpoint", MessageData, MessageProperties);

            Model.AssertWasCalled(x => x.ExchangeDeclare(exchange, "fanout", Exchange.Durable));
        }
 public WebSocketConnection(WebSocketWrapper websocket)
 {
     Sender = new Sender();
     Receiver = new Receiver();
     Sender.WebSocket = websocket;
     Receiver.WebSocket = websocket;
     Sender.Connection = this;
     Receiver.Connection = this;
 }
Example #18
0
 public Form1()
 {
     InitializeComponent();
     PortInit();
     InputEmpty = true;
     send = new Sender();
     send.DataBits = int.Parse(DataCom.Text);
     send.Baudrate = int.Parse(BauCom.Text);
     send.PortName = PortCom.Text;
 }
Example #19
0
        //private IDictionary<short, Fade> fades;

        /// <summary>
        /// Initializes a new instance of the <see cref="ArtNetFascade"/> class.
        /// </summary>
        /// <param name="universe">The universe.</param>
        /// <param name="hosts">The hosts.</param>
        public ArtNetFascade(short universe, ISet<string> hosts)
        {
            persistence = new Persistence();
            package = persistence.GetAsync(universe).Result;
            sender = new Sender(hosts);
            sendTimer = new Timer(10);
            sendTimer.Elapsed += sendTimer_Elapsed;
            sendTimer.Start();
            saveTimer = new Timer(2000);
            saveTimer.Elapsed += saveTimer_Elapsed;
            saveTimer.Start();
            //fades = new Dictionary<short, Fade>();
        }
        internal static void Read(XmlReader reader, Sender sender)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");
            if (sender == null)
                throw new ArgumentNullException("sender");

            if (reader.IsEmptyElement)
            {
                SerializationHelper.SkipNode(reader);
                return;
            }

            reader.ReadStartElement(SenderSerializer.Sender);
            reader.MoveToContent();

            while (!reader.EOF)
            {
                if (SerializationHelper.IsEndElement(reader, SenderSerializer.Sender))
                {
                    SerializationHelper.SkipNode(reader);
                    break;
                }

                if (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                        case SenderSerializer.Name:
                            sender.Name = reader.ReadElementContentAsString();
                            break;
                        case SenderSerializer.Email:
                            sender.Email = reader.ReadElementContentAsString();
                            break;
                        case PhoneSerializer.Phone:
                            Phone phone = new Phone();
                            PhoneSerializer.Read(reader, phone);
                            sender.Phone = phone;
                            break;
                        default:
                            SerializationHelper.SkipElement(reader);
                            break;
                    }
                }
                else
                {
                    SerializationHelper.SkipNode(reader);
                }
            }
        }
Example #21
0
	/// <summary>
	/// initializes the standard fields of this event type and
	/// signature
	/// </summary>
	protected override void InitFields()
	{

		m_Fields = new FieldInfo[]{this.GetType().GetField("Send")};

		StoreInvokerFieldNames();

		m_DefaultMethods = new MethodInfo[] { this.GetType().GetMethod("Empty") };

		m_DelegateTypes = new Type[] { typeof(vp_Message.Sender) };
		Prefixes = new Dictionary<string, int>() { { "OnMessage_", 0 } };

		Send = Empty;

	}
Example #22
0
        public void SendMessageToMultipleSubscribers()
        {
            var sender = new Sender();
            var s1 = new Subscriber();
            var s2 = new Subscriber();
            var s3 = new Subscriber();
            var s4 = new Subscriber();

            sender.Send(180);

            Assert.That(s1.Value, Is.EqualTo(180));
            Assert.That(s2.Value, Is.EqualTo(180));
            Assert.That(s3.Value, Is.EqualTo(180));
            Assert.That(s4.Value, Is.EqualTo(180));
        }
Example #23
0
        static void Main(string[] args)
        {
            Console.WriteLine("Press enter when the server is running.");
            Console.ReadKey();

            Listener listener = new Listener();
            listener.Open();

            Sender sender = new Sender();
            sender.Go();

            //sender.Dispose();
            //listener.Dispose();

            Console.WriteLine("Done, press enter to exit");
            Console.ReadKey();
        }
Example #24
0
        public static void Main(string[] args) {
            var receiver = new Receiver<Tweet>();
            var twitterClient = new TwitterClient();
            var sender = new Sender<TweetStatus>();

            receiver.Received += tweet => {
                TweetThis(twitterClient, tweet, sender);
            };
            //receiver.Received += tweet => Console.WriteLine($"{tweet.Message}");

            receiver.Receive();

            Console.WriteLine("Press any key to stop...");
            Console.ReadKey();

            receiver.Stop();
        }
Example #25
0
        public void UploadFile()
        {
            Sender sender = new Sender();
            string localFile = "eventsFile.txt";
            if (File.Exists(localFile) == true && FormTesting.allowBrowsing == true)
            {
                try
                {
                    StreamReader rdr = new StreamReader(localFile);

                    string inLine = rdr.ReadLine();
                    string[] words = inLine.Split(' ');
                    inLine = "";
                    foreach (string word in words)
                    {
                        inLine += word.Split('?')[0] + " ";
                    }

                    while (inLine != null)
                    {
                        sender.send(FormTesting.hash + '|' + FormTesting.zipCode + '|' + FormTesting.provider + '|' + inLine);
                        inLine = rdr.ReadLine();

                        if (inLine != null)
                        {
                            words = inLine.Split(' ');
                            inLine = "";
                            foreach (string word in words)
                            {
                                inLine += word.Split('?')[0] + " ";
                            }
                        }
                    }

                    rdr.Close();
                    File.Delete(localFile);
                }
                catch (Exception exc)
                {
                    Console.Out.WriteLine("Exception " + exc.ToString());
                }
            }

            sender.send(FormTesting.hash + '|' + FormTesting.zipCode + '|' + FormTesting.provider + '|' + reasonListView.Items[reasonListView.SelectedIndices[0]].Text + '|' + processListView.Items[processListView.SelectedIndices[0]].Text);
        }
        internal static void Write(XmlWriter writer, Sender sender)
        {
            if (writer == null)
                throw new ArgumentNullException("writer");
            if (sender == null)
                throw new ArgumentNullException("sender");

            writer.WriteStartElement(SenderSerializer.Sender);

            SerializationHelper.WriteElementStringNotNull(writer, SenderSerializer.Name, sender.Name);
            SerializationHelper.WriteElementStringNotNull(writer, SenderSerializer.Email, sender.Email);

            if (sender.Phone != null)
            {
                PhoneSerializer.Write(writer, sender.Phone);
            }
            writer.WriteEndElement();
        }
 public void Should_wrap_encrypted_message(Sender sender)
 {
     IMessageCodec messageCodec = GetMessageCodec();
     byte[] wrappedMessageBytes = messageCodec.EncodeEncryptedMessage(TestMessage, TestRig.AuthKey, 0x999UL, 0x777UL, sender);
     byte[] expectedMessageBytes;
     switch (sender)
     {
         case Sender.Client:
             expectedMessageBytes = TestEncryptedClientMessageBytes;
             break;
         case Sender.Server:
             expectedMessageBytes = TestEncryptedServerMessageBytes;
             break;
         default:
             throw new ArgumentOutOfRangeException("sender");
     }
     wrappedMessageBytes.ShouldBeEquivalentTo(expectedMessageBytes);
 }
Example #28
0
            public MemoryStream Reply(Sender.Writer w, int count)
            {
                var pos = w.Stream.Position;
                var buf = new Receiver.Writer();
                w.Stream.Position = 0;
                w.Stream.CopyTo(Reader.Stream);
                Reader.Stream.Position = 0;

                for (int i = 0; i < count; ++i)
                {
                    var header = Reader.ReadHeader();
                    Reader.Dispatch(header)(buf);
                }

                Assert.AreEqual(pos, buf.Stream.Position);
                Assert.AreEqual(pos, buf.Stream.Length);

                return buf.Stream;
            }
Example #29
0
        static void test(uint N)
        {
            Sender sender = new Sender();
            Reciever rcv = new Reciever();

            TimeSpan X1 = TimeSpan.Zero;
            TimeSpan X2 = TimeSpan.Zero;
            TimeSpan X3 = TimeSpan.Zero;

            for(int j=0; j<8; ++j)
	        {
		        DateTime c0 = DateTime.Now;

		        for(uint i = 0; i< N; ++i)
		        {
                    sender.testEvent += rcv.handleFloat;
		        }

		        DateTime c1 = DateTime.Now;

		        for(int k=0; k<100; ++k)
		        {
			        sender.fire(3.14f);
		        }

		        DateTime c2 = DateTime.Now;

		        for(uint i = 0; i< N; ++i)
		        {
                    sender.testEvent -= rcv.handleFloat;
		        }

		        DateTime c3 = DateTime.Now;

		        X1 = X1.Add(c1.Subtract(c0));
                X2 = X2.Add(c2.Subtract(c1));
		        X3 = X3.Add(c3.Subtract(c3));
	        }
	        System.Console.WriteLine("{0,8}\t{1}\t{2}\t{3}", N, X1.Milliseconds, X2.Milliseconds, X3.Milliseconds);
        }
Example #30
0
        public static void Main(string[] args)
        {
            var sender = new Sender ();
            var listener = new Listener ();
            listener.DiscoveredEndPoint += delegate(object obj, Listener.DiscoveredEndPointEventArgs e) {
                Console.WriteLine("DiscoveredEndPoint event was raised.  End Point is {0}", e.EndPoint.ToString());
            };

            Console.WriteLine ("Starting Listener");
            listener.Start ();

            Console.WriteLine ("Choose either 's' to send, or 'x' to exit");
            ConsoleKeyInfo cki;

            bool continueLoop = true;
            do
            {
                if (Console.KeyAvailable)
                {
                    cki = Console.ReadKey(true);
                    switch (cki.KeyChar)
                    {
                    case 's':
                        sender.Send();
                        break;
                    case 'x':
                        Console.WriteLine("Try exiting...");

                        listener.Stop();
                        continueLoop = false;
                        break;
                    }
                }

                Thread.Sleep(10);
            } while (continueLoop);

            Console.WriteLine ("Please press any key to exit...");
            Console.ReadKey (true);
        }
 public UserMessage SetSystem(SystemName sys) =>
 new UserMessage(Content, Sender.SetSystem(sys), ReplyTo.SetSystem(sys));
Example #32
0
        public LocalContext(Func <IActor> producer, ISupervisorStrategy supervisorStrategy, Receive receiveMiddleware, Sender senderMiddleware, PID parent)
        {
            _producer           = producer;
            _supervisorStrategy = supervisorStrategy;
            _receiveMiddleware  = receiveMiddleware;
            _senderMiddleware   = senderMiddleware;

            //Parents are implicitly watching the child
            //The parent is not part of the Watchers set
            Parent = parent;

            IncarnateActor();
        }
Example #33
0
        static Guid?CreateTransactionExample(Configuration configuration)
        {
            TransactionsApi api = new TransactionsApi(configuration);

            // Please check our documentation at https://docs.transferzero.com/docs/transaction-flow/
            // for details on how transactions work

            // When adding a sender to transaction, please use either an id or external_id. Providing both will result in a validation error.
            // Please see our documentation at https://docs.transferzero.com/docs/transaction-flow/#sender

            Sender sender = new Sender(id: Guid.Parse("058de445-ffff-ffff-ffff-da9c751d14bf"));

            // You can find the various payout options at https://docs.transferzero.com/docs/transaction-flow/#payout-details

            PayoutMethodDetails ngnBankDetails = new PayoutMethodDetails(
                bankAccount: "123456789",
                bankAccountType: PayoutMethodBankAccountTypeEnum._20,
                bankCode: "082",
                firstName: "First",
                lastName: "Last"
                );

            PayoutMethod payoutMethod = new PayoutMethod(
                type: "NGN::Bank",
                details: ngnBankDetails
                );

            // Please see https://docs.transferzero.com/docs/transaction-flow/#requested-amount-and-currency
            // on what the request amount and currencies do

            Recipient recipient = new Recipient(
                requestedAmount: 10000,
                requestedCurrency: "NGN",
                payoutMethod: payoutMethod
                );

            // Similarly you can check https://docs.transferzero.com/docs/transaction-flow/#requested-amount-and-currency
            // on details about the input currency parameter

            // Find more details on external IDs at https://docs.transferzero.com/docs/transaction-flow/#external-id

            Transaction transaction = new Transaction(
                inputCurrency: "USD",
                sender: sender,
                recipients: new List <Recipient>()
            {
                recipient
            },
                externalId: "TRANSACTION-00001"
                );

            try
            {
                TransactionRequest transactionRequest = new TransactionRequest(
                    transaction: transaction
                    );
                TransactionResponse transactionResponse = api.PostTransactions(transactionRequest);
                System.Console.WriteLine("Transaction created! ID" + transactionResponse.Object.Id);
                System.Console.WriteLine(transactionResponse.Object);
                return(transactionResponse.Object.Id);
            }
            catch (ApiException e)
            {
                if (e.IsValidationError)
                {
                    TransactionResponse transactionResponse = e.ParseObject <TransactionResponse>();
                    System.Console.WriteLine("Validation Error" + transactionResponse.Object.Errors);
                }
                else
                {
                    throw e;
                }
                return(null);
            }
        }
Example #34
0
        private static void TemporarilySendTest()
        {
            var network = Network.TestNet;

            #region SetupSafe

            string walletFilePath;
            if (network == Network.MainNet)
                walletFilePath = "MainNetHidden2.wallet";
            else
                walletFilePath = "TestNetHidden2.wallet";

            Safe safe;
            if (File.Exists(walletFilePath))
            {
                safe = Safe.Load("password", walletFilePath);
                if (safe.Network != network)
                    throw new Exception("Wrong network");
            }
            else
            {
                string mnemonic;
                safe = Safe.Create(out mnemonic, "password", walletFilePath, network);
            }

            WriteLine("Safe has been set up");

            #endregion

            #region InitializeHttpSafeMonitor

            var safeMonitor = new HttpSafeMonitor(safe, addressCount: 100);

            // Report initialization progress
            safeMonitor.InitializationStateChanged += delegate(object sender, EventArgs args)
            {
                var monitor = (HttpSafeMonitor) sender;
                WriteLine($"Initialization state: {monitor.InitializationState}");
            };
            safeMonitor.InitializationProgressPercentChanged += delegate(object sender, EventArgs args)
            {
                var monitor = (HttpSafeMonitor) sender;
                WriteLine($"Initializing: {monitor.InitializationProgressPercent}%");
            };

            // Let's wait until initialized
            while (safeMonitor.InitializationState != State.Ready)
                Thread.Sleep(100);

            WriteLine("SafeMonitor is ready to work with");

            #endregion

            #region FeedBack

            var bal = safeMonitor.SafeBalanceInfo;
            var his = safeMonitor.SafeHistory;

            WriteLine();
            WriteLine($"Balance: {bal.Balance}");
            WriteLine($"Confirmed balance: {bal.Confirmed}");
            WriteLine($"Unconfirmed balance: {bal.Unconfirmed}");
            WriteLine($"TotalReceived: {his.TotalReceived}");
            WriteLine($"TotalSpent: {his.TotalSpent}");
            WriteLine($"TotalReceived - TotalSpent: {his.TotalReceived - his.TotalSpent}");
            WriteLine($"TotalReceived - TotalSpent == Balance: {his.TotalReceived - his.TotalSpent == bal.Balance}");
            WriteLine();
            WriteLine("RECORDS:");

            foreach (var record in his.Records)
            {
                WriteLine();
                WriteLine($"DateTime: {record.DateTime}");
                WriteLine($"Amount: {record.Amount}");
                WriteLine($"Confirmed: {record.Confirmed}");
            }

            safeMonitor.BalanceChanged += delegate(object sender, EventArgs args)
            {
                var monitor = (HttpSafeMonitor) sender;

                WriteLine();
                WriteLine("Change happened");
                WriteLine($"Balance: {monitor.SafeBalanceInfo.Balance}");
                WriteLine($"Confirmed balance: {monitor.SafeBalanceInfo.Confirmed}");
                WriteLine($"Unconfirmed balance: {monitor.SafeBalanceInfo.Unconfirmed}");
                WriteLine($"TotalReceived: {monitor.SafeHistory.TotalReceived}");
                WriteLine($"TotalSpent: {monitor.SafeHistory.TotalSpent}");
                WriteLine(
                    $"TotalReceived - TotalSpent: {monitor.SafeHistory.TotalReceived - monitor.SafeHistory.TotalSpent}");
                WriteLine(
                    $"TotalReceived - TotalSpent == Balance: {monitor.SafeHistory.TotalReceived - monitor.SafeHistory.TotalSpent == monitor.SafeBalanceInfo.Balance}");
                WriteLine();
                WriteLine("Last record:");
                var record = monitor.SafeHistory.Records.First();
                WriteLine($"DateTime: {record.DateTime}");
                WriteLine($"Amount: {record.Amount}");
                WriteLine($"Confirmed: {record.Confirmed}");
            };
            WriteLine();
            WriteLine("Subscribed to changes");

            #endregion

            foreach (var addressBalanceInfo in safeMonitor.SafeBalanceInfo.AddressBalances)
            {
                if (addressBalanceInfo.Balance != 0 || addressBalanceInfo.Unconfirmed != 0)
                {
                    WriteLine($"{addressBalanceInfo.Address} : {addressBalanceInfo.Balance}");
                    WriteLine($"Confirmed: {addressBalanceInfo.Confirmed} Unconfirmed: {addressBalanceInfo.Unconfirmed}");
                }
            }

            var spender = new HttpSafeBuilder(safeMonitor.Safe);

            spender.TransactionBuildStateChanged += delegate(object sender, EventArgs args)
            {
                var currentSpender = sender as HttpSafeBuilder;
                WriteLine(currentSpender.TransactionBuildState);
            };

            WriteLine("Create transaction");
            var tx = spender.BuildTransaction(
                new List<AddressAmountPair>
                {
                    new AddressAmountPair
                    {
                        Address = "2NBY5BrXhnWESaLqxYvRWUZ8xzDF3aZqX7S",
                        Amount = 0.1m
                    },
                    new AddressAmountPair
                    {
                        Address = "2N66DDrmjDCMM3yMSYtAQyAqRtasSkFhbmX",
                        Amount = 0.1m
                    }
                },
                FeeType.Fastest,
                "keep the change you filthy animal"
                );
            WriteLine("Transaction created");
            Sender.Send(ConnectionType.RandomNode, tx);
            WriteLine("Transaction sent");

            ReadLine();
        }
 public LeaderSynchronizer()
 {
     Receive <string>(str => str.Equals("leader"), _ => Sender.Tell(Cluster.Get(Context.System).State.Leader));
 }
        public override IDeepCopyable CopyTo(IDeepCopyable other)
        {
            var dest = other as CommunicationRequest;

            if (dest != null)
            {
                base.CopyTo(dest);
                if (Identifier != null)
                {
                    dest.Identifier = new List <Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy());
                }
                if (Category != null)
                {
                    dest.Category = (Hl7.Fhir.Model.CodeableConcept)Category.DeepCopy();
                }
                if (Sender != null)
                {
                    dest.Sender = (Hl7.Fhir.Model.ResourceReference)Sender.DeepCopy();
                }
                if (Recipient != null)
                {
                    dest.Recipient = new List <Hl7.Fhir.Model.ResourceReference>(Recipient.DeepCopy());
                }
                if (Payload != null)
                {
                    dest.Payload = new List <Hl7.Fhir.Model.CommunicationRequest.PayloadComponent>(Payload.DeepCopy());
                }
                if (Medium != null)
                {
                    dest.Medium = new List <Hl7.Fhir.Model.CodeableConcept>(Medium.DeepCopy());
                }
                if (Requester != null)
                {
                    dest.Requester = (Hl7.Fhir.Model.ResourceReference)Requester.DeepCopy();
                }
                if (StatusElement != null)
                {
                    dest.StatusElement = (Code <Hl7.Fhir.Model.CommunicationRequest.CommunicationRequestStatus>)StatusElement.DeepCopy();
                }
                if (Encounter != null)
                {
                    dest.Encounter = (Hl7.Fhir.Model.ResourceReference)Encounter.DeepCopy();
                }
                if (Scheduled != null)
                {
                    dest.Scheduled = (Hl7.Fhir.Model.Element)Scheduled.DeepCopy();
                }
                if (Reason != null)
                {
                    dest.Reason = new List <Hl7.Fhir.Model.CodeableConcept>(Reason.DeepCopy());
                }
                if (RequestedOnElement != null)
                {
                    dest.RequestedOnElement = (Hl7.Fhir.Model.FhirDateTime)RequestedOnElement.DeepCopy();
                }
                if (Subject != null)
                {
                    dest.Subject = (Hl7.Fhir.Model.ResourceReference)Subject.DeepCopy();
                }
                if (Priority != null)
                {
                    dest.Priority = (Hl7.Fhir.Model.CodeableConcept)Priority.DeepCopy();
                }
                return(dest);
            }
            else
            {
                throw new ArgumentException("Can only copy to an object of the same type", "other");
            }
        }
Example #37
0
        /// <summary>
        /// TBD
        /// </summary>
        /// <param name="message">TBD</param>
        /// <returns>TBD</returns>
        protected override bool Receive(object message)
        {
            if (message is PublishSubscribe.Send ||
                message is PublishSubscribe.SendToAll ||
                message is PublishSubscribe.Publish)
            {
                var tunnel = ResponseTunnel(Sender);
                tunnel.Tell(Ping.Instance); // keep alive
                _pubSubMediator.Tell(message, tunnel);
            }
            else if (message is Heartbeat)
            {
                if (_cluster.Settings.VerboseHeartbeatLogging)
                {
                    _log.Debug("Heartbeat from client [{0}]", Sender.Path);
                }
                Sender.Tell(HeartbeatRsp.Instance);
                UpdateClientInteractions(Sender);
            }
            else if (message is GetContacts)
            {
                // Consistent hashing is used to ensure that the reply to GetContacts
                // is the same from all nodes (most of the time) and it also
                // load balances the client connections among the nodes in the cluster.
                if (_settings.NumberOfContacts >= _nodes.Count)
                {
                    var contacts = new Contacts(_nodes.Select(a => Self.Path.ToStringWithAddress(a)).ToImmutableList());
                    if (_log.IsDebugEnabled)
                    {
                        _log.Debug("Client [{0}] gets contactPoints [{1}] (all nodes)", Sender.Path, string.Join(", ", contacts));
                    }

                    Sender.Tell(contacts);
                }
                else
                {
                    // using ToStringWithAddress in case the client is local, normally it is not, and
                    // ToStringWithAddress will use the remote address of the client
                    var addr = _consistentHash.NodeFor(Sender.Path.ToStringWithAddress(_cluster.SelfAddress));

                    var first = _nodes.From(addr).Tail().Take(_settings.NumberOfContacts).ToArray();
                    var slice = first.Length == _settings.NumberOfContacts
                        ? first
                        : first.Union(_nodes.Take(_settings.NumberOfContacts - first.Length)).ToArray();
                    var contacts = new Contacts(slice.Select(a => Self.Path.ToStringWithAddress(a)).ToImmutableList());

                    if (_log.IsDebugEnabled)
                    {
                        _log.Debug("Client [{0}] gets ContactPoints [{1}]", Sender.Path, string.Join(", ", contacts.ContactPoints));
                    }

                    Sender.Tell(contacts);
                }
            }
            else if (message is ClusterEvent.CurrentClusterState state)
            {
                _nodes = ImmutableSortedSet <Address> .Empty.WithComparer(RingOrdering.Instance)
                         .Union(state.Members
                                .Where(m => m.Status != MemberStatus.Joining && IsMatchingRole(m))
                                .Select(m => m.Address));

                _consistentHash = ConsistentHash.Create(_nodes, _virtualNodesFactor);
            }
            else if (message is ClusterEvent.MemberUp up)
            {
                if (IsMatchingRole(up.Member))
                {
                    _nodes          = _nodes.Add(up.Member.Address);
                    _consistentHash = ConsistentHash.Create(_nodes, _virtualNodesFactor);
                }
            }
            else if (message is ClusterEvent.MemberRemoved removed)
            {
                if (removed.Member.Address.Equals(_cluster.SelfAddress))
                {
                    Context.Stop(Self);
                }
                else if (IsMatchingRole(removed.Member))
                {
                    _nodes          = _nodes.Remove(removed.Member.Address);
                    _consistentHash = ConsistentHash.Create(_nodes, _virtualNodesFactor);
                }
            }
            else if (message is ClusterEvent.IMemberEvent)
            {
                // not of interest
            }
            else if (message is SubscribeClusterClients)
            {
                var subscriber = Sender;
                subscriber.Tell(new ClusterClients(_clientInteractions.Keys.ToImmutableHashSet()));
                _subscribers = _subscribers.Add(subscriber);
                Context.Watch(subscriber);
            }
            else if (message is UnsubscribeClusterClients)
            {
                var subscriber = Sender;
                _subscribers = _subscribers.Where(c => !c.Equals(subscriber)).ToImmutableList();
            }
            else if (message is Terminated terminated)
            {
                Self.Tell(UnsubscribeClusterClients.Instance, terminated.ActorRef);
            }
            else if (message is GetClusterClients)
            {
                Sender.Tell(new ClusterClients(_clientInteractions.Keys.ToImmutableHashSet()));
            }
            else if (message is CheckDeadlines)
            {
                _clientInteractions = _clientInteractions.Where(c => c.Value.IsAvailable).ToImmutableDictionary();
                PublishClientsUnreachable();
            }
            else
            {
                return(false);
            }

            return(true);
        }
 public Inbox.Inbox GetInbox(Sender senderId)
 {
     return(new Inbox.Inbox(senderId, _requestHelper));
 }
 public static Task PostLolSuggestedPlayersV1VictoriousComrade([Parameter("resource", "body")] LolSuggestedPlayersSuggestedPlayersVictoriousComrade resource)
 => Sender.Request("post", $"/lol-suggested-players/v1/victorious-comrade", resource);
 public static Task <object> DeleteLolSuggestedPlayersV1SuggestedPlayersBySummonerId([Parameter("summonerId", "path")] long summonerId)
 => Sender.Request <object>("delete", $"/lol-suggested-players/v1/suggested-players/{summonerId}");
 public static Task <LolSuggestedPlayersSuggestedPlayersSuggestedPlayer[]> GetLolSuggestedPlayersV1SuggestedPlayers()
 => Sender.Request <LolSuggestedPlayersSuggestedPlayersSuggestedPlayer[]>("get", $"/lol-suggested-players/v1/suggested-players");
 public static Task PostLolSuggestedPlayersV1ReportedPlayer([Parameter("resource", "body")] LolSuggestedPlayersSuggestedPlayersReportedPlayer resource)
 => Sender.Request("post", $"/lol-suggested-players/v1/reported-player", resource);
Example #43
0
        private void HandleCoordinatorMessage(PersistentShardCoordinator.ICoordinatorMessage message)
        {
            switch (message)
            {
            case PersistentShardCoordinator.HostShard hs:
            {
                var shard = hs.Shard;
                Log.Debug("Host shard [{0}]", shard);
                RegionByShard = RegionByShard.SetItem(shard, Self);
                UpdateRegionShards(Self, shard);

                // Start the shard, if already started this does nothing
                GetShard(shard);

                Sender.Tell(new PersistentShardCoordinator.ShardStarted(shard));
            }
            break;

            case PersistentShardCoordinator.ShardHome home:
                Log.Debug("Shard [{0}] located at [{1}]", home.Shard, home.Ref);

                if (RegionByShard.TryGetValue(home.Shard, out var region))
                {
                    if (region.Equals(Self) && !home.Ref.Equals(Self))
                    {
                        // should not happen, inconsistency between ShardRegion and PersistentShardCoordinator
                        throw new IllegalStateException(string.Format("Unexpected change of shard [{0}] from self to [{1}]", home.Shard, home.Ref));
                    }
                }

                RegionByShard = RegionByShard.SetItem(home.Shard, home.Ref);
                UpdateRegionShards(home.Ref, home.Shard);

                if (!home.Ref.Equals(Self))
                {
                    Context.Watch(home.Ref);
                }

                if (home.Ref.Equals(Self))
                {
                    var shardRef = GetShard(home.Shard);
                    if (!Equals(shardRef, ActorRefs.Nobody))
                    {
                        DeliverBufferedMessage(home.Shard, shardRef);
                    }
                }
                else
                {
                    DeliverBufferedMessage(home.Shard, home.Ref);
                }
                break;

            case PersistentShardCoordinator.RegisterAck ra:
                _coordinator = ra.Coordinator;
                Context.Watch(_coordinator);
                RequestShardBufferHomes();
                break;

            case PersistentShardCoordinator.BeginHandOff bho:
            {
                var shard = bho.Shard;
                Log.Debug("Begin hand off shard [{0}]", shard);
                if (RegionByShard.TryGetValue(shard, out var regionRef))
                {
                    if (!Regions.TryGetValue(regionRef, out var updatedShards))
                    {
                        updatedShards = ImmutableHashSet <ShardId> .Empty;
                    }

                    updatedShards = updatedShards.Remove(shard);

                    Regions = updatedShards.Count == 0
                                ? Regions = Regions.Remove(regionRef)
                                : Regions.SetItem(regionRef, updatedShards);

                    RegionByShard = RegionByShard.Remove(shard);
                }

                Sender.Tell(new PersistentShardCoordinator.BeginHandOffAck(shard));
            }
            break;

            case PersistentShardCoordinator.HandOff ho:
            {
                var shard = ho.Shard;
                Log.Debug("Hand off shard [{0}]", shard);

                // must drop requests that came in between the BeginHandOff and now,
                // because they might be forwarded from other regions and there
                // is a risk or message re-ordering otherwise
                if (ShardBuffers.ContainsKey(shard))
                {
                    ShardBuffers             = ShardBuffers.Remove(shard);
                    _loggedFullBufferWarning = false;
                }

                if (Shards.TryGetValue(shard, out var actorRef))
                {
                    HandingOff = HandingOff.Add(actorRef);
                    actorRef.Forward(message);
                }
                else
                {
                    Sender.Tell(new PersistentShardCoordinator.ShardStopped(shard));
                }
            }
            break;

            default:
                Unhandled(message);
                break;
            }
        }
Example #44
0
 protected override void OnReceive(object message)
 {
     Sender.Tell(Self);
 }
Example #45
0
 public IRCMessanger(Sender sender, string channel)
 {
     this.sender  = sender;
     this.channel = channel;
 }
Example #46
0
 protected override bool Receive(object message)
 {
     Sender.Tell(_nested, Self);
     return(true);
 }
Example #47
0
        internal void PrepareHeaders(bool sendEnvelope, bool allowUnicode)
        {
            string headerName;

            if (_headersEncoding == null)
            {
                _headersEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
            }

            //ContentType is written directly to the stream so remove potential user duplicate
            Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.ContentType) !);

            Headers[MailHeaderInfo.GetString(MailHeaderID.MimeVersion)] = "1.0";

            // add sender to headers first so that it is written first to allow the IIS smtp svc to
            // send MAIL FROM with the sender if both sender and from are present
            headerName = MailHeaderInfo.GetString(MailHeaderID.Sender) !;
            if (Sender != null)
            {
                Headers.InternalAdd(headerName, Sender.Encode(headerName.Length, allowUnicode));
            }
            else
            {
                Headers.Remove(headerName);
            }

            headerName = MailHeaderInfo.GetString(MailHeaderID.From) !;
            Headers.InternalAdd(headerName, From !.Encode(headerName.Length, allowUnicode));

            headerName = MailHeaderInfo.GetString(MailHeaderID.To) !;
            if (To.Count > 0)
            {
                Headers.InternalAdd(headerName, To.Encode(headerName.Length, allowUnicode));
            }
            else
            {
                Headers.Remove(headerName);
            }

            headerName = MailHeaderInfo.GetString(MailHeaderID.Cc) !;
            if (CC.Count > 0)
            {
                Headers.InternalAdd(headerName, CC.Encode(headerName.Length, allowUnicode));
            }
            else
            {
                Headers.Remove(headerName);
            }

            headerName = MailHeaderInfo.GetString(MailHeaderID.ReplyTo) !;
            if (ReplyTo != null)
            {
                Headers.InternalAdd(headerName, ReplyTo.Encode(headerName.Length, allowUnicode));
            }
            else if (ReplyToList.Count > 0)
            {
                Headers.InternalAdd(headerName, ReplyToList.Encode(headerName.Length, allowUnicode));
            }
            else
            {
                Headers.Remove(headerName);
            }

            Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Bcc) !);

            if (_priority == MailPriority.High)
            {
                Headers[MailHeaderInfo.GetString(MailHeaderID.XPriority)]  = "1";
                Headers[MailHeaderInfo.GetString(MailHeaderID.Priority)]   = "urgent";
                Headers[MailHeaderInfo.GetString(MailHeaderID.Importance)] = "high";
            }
            else if (_priority == MailPriority.Low)
            {
                Headers[MailHeaderInfo.GetString(MailHeaderID.XPriority)]  = "5";
                Headers[MailHeaderInfo.GetString(MailHeaderID.Priority)]   = "non-urgent";
                Headers[MailHeaderInfo.GetString(MailHeaderID.Importance)] = "low";
            }
            //if the priority was never set, allow the app to set the headers directly.
            else if (((int)_priority) != -1)
            {
                Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.XPriority) !);
                Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Priority) !);
                Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Importance) !);
            }

            Headers.InternalAdd(MailHeaderInfo.GetString(MailHeaderID.Date) !,
                                MailBnfHelper.GetDateTimeString(DateTime.Now, null) !);

            headerName = MailHeaderInfo.GetString(MailHeaderID.Subject) !;
            if (!string.IsNullOrEmpty(_subject))
            {
                if (allowUnicode)
                {
                    Headers.InternalAdd(headerName, _subject);
                }
                else
                {
                    Headers.InternalAdd(headerName,
                                        MimeBasePart.EncodeHeaderValue(_subject, _subjectEncoding,
                                                                       MimeBasePart.ShouldUseBase64Encoding(_subjectEncoding),
                                                                       headerName.Length));
                }
            }
            else
            {
                Headers.Remove(headerName);
            }

            EncodeHeaders(_headers !, allowUnicode);
        }
Example #48
0
 public bool CanExecute(Sender session)
 {
     return(true);
 }
Example #49
0
 public YesNoMaybe(Sender sender, LobbyManager lobbyManager) : base(sender, lobbyManager)
 {
 }
Example #50
0
 protected override void OnReceive(object message)
 {
     Sender.Tell(Context.Props.Dispatcher);
 }
Example #51
0
 /// <summary>
 ///     Handles the identity.
 /// </summary>
 /// <param name="m">The m.</param>
 private void HandleIdentity(Identify m)
 {
     Sender.Tell(new ActorIdentity(m.MessageId, Self));
 }
Example #52
0
        private void OffLine()
        {
            Receive <Tcp.Received>(received =>
            {
                if (!Sender.Equals(_tcpActorRef))
                {
                    _log.Error($"link error close link!");
                    Sender.Tell(Tcp.Close.Instance);
                    return;
                }

                var aMsg     = ProtoTool.DeSerialize <AMsg>(received.Data.ToArray());
                var aMsgType = aMsg.type;
                if (aMsgType == AMsg.Type.RequestMsg)
                {
                    var aMsgRequestMsg = aMsg.requestMsg;
                    switch (aMsgRequestMsg.head)
                    {
                    case RequestMsg.Head.LoginRequest:
                        var aMsgLoginRequest = aMsgRequestMsg.loginRequest;
                        var accountId        = aMsgLoginRequest.accountId;
                        var password         = aMsgLoginRequest.Password;

                        if (!Tools.CheckAccountIdOk(accountId))
                        {
                            var loginResponse = new LoginResponse()
                            {
                                reason = LoginResponse.Reason.NoGoodAccount, Nickname = ""
                            };
                            var msg = new AMsg()
                            {
                                type        = AMsg.Type.ResponseMsg,
                                responseMsg = new ResponseMsg()
                                {
                                    head = ResponseMsg.Head.LoginResponse, loginResponse = loginResponse
                                }
                            };
                            Sender.Tell(GenTcpWrite(msg));
                        }
                        else if (!Tools.CheckPasswordOk(password))
                        {
                            var loginResponse = new LoginResponse()
                            {
                                reason = LoginResponse.Reason.NoGoodPassword, Nickname = ""
                            };
                            var msg = new AMsg()
                            {
                                type        = AMsg.Type.ResponseMsg,
                                responseMsg = new ResponseMsg()
                                {
                                    head = ResponseMsg.Head.LoginResponse, loginResponse = loginResponse
                                }
                            };
                            Sender.Tell(GenTcpWrite(msg));
                        }
                        else
                        {
                            _accountId = accountId;
                            FamousActors.MongodbAccountActor.Tell(aMsgLoginRequest);
                        }

                        Become(LoginDoing);
                        break;

                    case RequestMsg.Head.FixAccountPasswordRequest:
                        var aMsgFixAccountPasswordRequest = aMsgRequestMsg.fixAccountPasswordRequest;

                        if (!Tools.CheckAccountIdOk(aMsgFixAccountPasswordRequest.accountId))
                        {
                            var loginResponse = new FixAccountPasswordResponse
                            {
                                reason = FixAccountPasswordResponse.Reason.NoGoodAccountId
                            };
                            var msg = new AMsg()
                            {
                                type        = AMsg.Type.ResponseMsg,
                                responseMsg = new ResponseMsg()
                                {
                                    head = ResponseMsg.Head.FixAccountPasswordResponse,
                                    fixAccountPasswordResponse = loginResponse
                                }
                            };
                            Sender.Tell(GenTcpWrite(msg));
                        }
                        else if (!Tools.CheckPasswordOk(aMsgFixAccountPasswordRequest.newPassword) ||
                                 !Tools.CheckPasswordOk(aMsgFixAccountPasswordRequest.oldPassword))
                        {
                            var loginResponse = new FixAccountPasswordResponse
                            {
                                reason = FixAccountPasswordResponse.Reason.NoGoodPassword
                            };
                            var msg = new AMsg()
                            {
                                type        = AMsg.Type.ResponseMsg,
                                responseMsg = new ResponseMsg()
                                {
                                    head = ResponseMsg.Head.FixAccountPasswordResponse,
                                    fixAccountPasswordResponse = loginResponse
                                }
                            };
                            Sender.Tell(GenTcpWrite(msg));
                        }
                        else
                        {
                            FamousActors.MongodbAccountActor.Tell(aMsgFixAccountPasswordRequest);
                        }

                        break;

                    default:
                        _tcpActorRef.Tell(Tcp.Close.Instance);
                        throw new ArgumentOutOfRangeException();
                    }
                }
            });


            Receive <FixAccountPasswordResponse>(response =>
            {
                var genTcpWrite = GenTcpWrite(new AMsg()
                {
                    type = AMsg.Type.ResponseMsg, responseMsg =
                        new ResponseMsg
                    {
                        head = ResponseMsg.Head.FixAccountPasswordResponse,
                        fixAccountPasswordResponse = response
                    }
                }
                                              );
                _tcpActorRef.Tell(genTcpWrite);
            });

            NormalAccident();
        }
Example #53
0
 public Subject()
 {
     ReceiveAny(_ => Sender.Tell(_));
 }
Example #54
0
 public Echo()
 {
     ReceiveAny(m => Sender.Tell(m));
 }
Example #55
0
 public void OnDestroy()
 {
     Sender.Send("Unload.");
     Sender.Destroy();
     Receiver.Destroy();
 }
Example #56
0
 public void Respond(object message)
 {
     Sender.Tell(message);
 }
Example #57
0
 private Receive HandleWriteMessages(ConnectionInfo info)
 {
     return(message =>
     {
         if (message is SelectionHandler.ChannelWritable)
         {
             if (WritePending())
             {
                 DoWrite(info);
                 if (!WritePending() && _interestedInResume != null)
                 {
                     _interestedInResume.Tell(IO.Tcp.WritingResumed.Instance);
                     _interestedInResume = null;
                 }
             }
             return true;
         }
         var write = message as Tcp.WriteCommand;
         if (write != null)
         {
             if (_writingSuspended)
             {
                 if (_tcp.Settings.TraceLogging)
                 {
                     _log.Debug("Dropping write because writing is suspended");
                 }
                 Sender.Tell(write.FailureMessage);
             }
             else if (WritePending())
             {
                 if (_tcp.Settings.TraceLogging)
                 {
                     _log.Debug("Dropping write because queue is full");
                 }
                 Sender.Tell(write.FailureMessage);
                 if (info.UseResumeWriting)
                 {
                     _writingSuspended = true;
                 }
             }
             else
             {
                 _pendingWrite = CreatePendingWrite(Sender, write);
                 if (WritePending())
                 {
                     DoWrite(info);
                 }
             }
             return true;
         }
         if (message is Tcp.ResumeWriting)
         {
             /*
              * If more than one actor sends Writes then the first to send this
              * message might resume too early for the second, leading to a Write of
              * the second to go through although it has not been resumed yet; there
              * is nothing we can do about this apart from all actors needing to
              * register themselves and us keeping track of them, which sounds bad.
              *
              * Thus it is documented that useResumeWriting is incompatible with
              * multiple writers. But we fail as gracefully as we can.
              */
             _writingSuspended = false;
             if (WritePending())
             {
                 if (_interestedInResume == null)
                 {
                     _interestedInResume = Sender;
                 }
                 else
                 {
                     Sender.Tell(new Tcp.CommandFailed(IO.Tcp.ResumeWriting.Instance));
                 }
             }
             else
             {
                 Sender.Tell(IO.Tcp.WritingResumed.Instance);
             }
             return true;
         }
         var updatePendingWrite = message as UpdatePendingWriteAndThen;
         if (updatePendingWrite != null)
         {
             _pendingWrite = updatePendingWrite.RemainingWrite;
             updatePendingWrite.Work();
             if (WritePending())
             {
                 info.Registration.EnableInterest(SocketAsyncOperation.Send);
             }
             return true;
         }
         //TODO: File IO
         return false;
     });
 }
Example #58
0
        private void OnLine()
        {
            FamousActors.MongodbPlayerStatusActor.Tell(new InitStatus(_accountId));

            // ICancelable scheduleTellRepeatedlyCancelable = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(
            //     TimeSpan.FromMinutes(10),
            //     TimeSpan.FromMinutes(10),
            //     Self, SavePlayerDB.Instance
            //     , ActorRefs.Nobody);
            void ReallyLoginOk()
            {
                _temp.bankBaseResponse      = Tools.GenBankBaseResponseByPlayBank(_myWallet);
                _temp.charactersGetResponse = Tools.GenCharactersGetResponseByPlayerCharacters(_myCharacters);
                var aMsg = new AMsg
                {
                    type        = AMsg.Type.ResponseMsg,
                    responseMsg = { head = ResponseMsg.Head.LoginResponse, loginResponse = _temp }
                };

                _tcpActorRef.Tell(GenTcpWrite(aMsg));
            }

            Receive <PlayerStatus>(status =>
            {
                _myWallet     = status.PlayerBank;
                _myGames      = status.PlayerGames;
                _myCharacters = status.PlayerCharacters;
                ReallyLoginOk();
            });


            Receive <ErrorResponse>(response =>
                                    _tcpActorRef.Tell(GenTcpWrite(
                                                          new AMsg
            {
                type        = AMsg.Type.ResponseMsg,
                responseMsg = { head = ResponseMsg.Head.ErrorResponse, errorResponse = response }
            }
                                                          ))
                                    );
            Receive <Tcp.ConnectionClosed>(closed =>
            {
                OffLineSave(OutReason.Drop);
                _log.Info($"Stopped, remote connection [{_remote}] closed");
                Context.Stop(Self);
            });
            Receive <Terminated>(terminated =>
            {
                OffLineSave(OutReason.Drop);
                _log.Info($"Stopped, remote connection [{_remote}] died");

                Context.Stop(Self);
            });

            Receive <LogoutResponse>(response =>
            {
                _tcpActorRef.Tell(GenTcpWrite(new AMsg
                {
                    type        = AMsg.Type.ResponseMsg,
                    responseMsg = { head = ResponseMsg.Head.LogoutResponse, logoutResponse = response }
                }));
            });
            Receive <Tcp.Received>(received =>
            {
                var aMsg     = ProtoTool.DeSerialize <AMsg>(received.Data.ToArray());
                var aMsgType = aMsg.type;

                if (aMsgType == AMsg.Type.RequestMsg && _gameState == GameState.Online && _accountId != null)
                {
                    var aMsgRequestMsg = aMsg.requestMsg;
                    switch (aMsgRequestMsg.head)
                    {
                    case RequestMsg.Head.BankBaseRequest:

                        var genBankBaseResponseByPlayBank = Tools.GenBankBaseResponseByPlayBank(_myWallet);
                        Sender.Tell(GenTcpWrite(new AMsg()
                        {
                            type        = AMsg.Type.ResponseMsg,
                            responseMsg = new ResponseMsg()
                            {
                                head             = ResponseMsg.Head.BankBaseResponse,
                                bankBaseResponse = genBankBaseResponseByPlayBank
                            }
                        }));
                        break;

                    case RequestMsg.Head.BankItemAllRequest:

                        var genBankItemAllResponseByPlayBank = Tools.GenBankItemResponseByPlayBank(_myWallet);
                        Sender.Tell(GenTcpWrite(new AMsg()
                        {
                            type        = AMsg.Type.ResponseMsg,
                            responseMsg = new ResponseMsg()
                            {
                                head             = ResponseMsg.Head.BankItemResponse,
                                bankItemResponse = genBankItemAllResponseByPlayBank
                            }
                        }));
                        break;

                    case RequestMsg.Head.BankItemCustomRequest:
                        var genBankItemResponseByPlayBank =
                            Tools.GenBankItemResponseByPlayBank(_myWallet,
                                                                aMsgRequestMsg.bankCustomItemRequest.itemIds);
                        Sender.Tell(GenTcpWrite(new AMsg()
                        {
                            type        = AMsg.Type.ResponseMsg,
                            responseMsg = new ResponseMsg()
                            {
                                head             = ResponseMsg.Head.BankItemResponse,
                                bankItemResponse = genBankItemResponseByPlayBank
                            }
                        }));
                        break;


                    case RequestMsg.Head.LogoutRequest:

                        OffLineSave(OutReason.LogOut);
                        _gameState = GameState.OffLine;
                        Become(OffLine);
                        break;

                    default:
                        _tcpActorRef.Tell(Tcp.Close.Instance);
                        throw new ArgumentOutOfRangeException();
                    }
                }
                else
                {
                    _tcpActorRef.Tell(Tcp.Close.Instance);
                    throw new ArgumentOutOfRangeException();
                }
            });
        }
Example #59
0
        protected override void OnReceive(object message)
        {
            switch (message)
            {
            case Connect c when string.IsNullOrEmpty(c.UserName):
                Sender.Tell(new Err("Username can't be null or empty."));

                break;

            case Connect c:
                Sender.Tell(new Welcome(c.UserName, _roomCounts));
                break;

            case JoinRoom j when string.IsNullOrEmpty(j.RoomName) ||
                string.IsNullOrEmpty(j.UserName):
                Sender.Tell(new Err("room name and user name can't be empty."));

                break;

            case JoinRoom j when _roomCounts.ContainsKey(j.RoomName):     // pre-existing room
                var uriFriendly = Uri.EscapeUriString(j.RoomName);

                var child = Context.Child(uriFriendly);
                if (child.IsNobody())
                {
                    child = Context.ActorOf(Props.Create(() => new RoomManager(j.RoomName, Self)), uriFriendly);
                }
                child.Forward(j);
                if (_roomCounts.TryGetValue(j.RoomName, out var count))
                {
                    _roomCounts[j.RoomName] = count + 1;
                }
                else
                {
                    _roomCounts[j.RoomName] = 1;
                }
                Sender.Tell(new JoinConfirmed(j.RoomName), child);
                break;

            case JoinRoom j when !_roomCounts.ContainsKey(j.RoomName):     // room doesn't exist
                Sender.Tell(new Err($"room {j.RoomName} doesn't exist. Create it first!"));
                break;

            case CreateRoom c when string.IsNullOrEmpty(c.RoomName):
                Sender.Tell(new Err($"Room name must be non-empty."));

                break;

            case CreateRoom c:
                _roomCounts[c.RoomName] = 0;                             // creates the room
                Self.Tell(new JoinRoom(c.RoomName, c.UserName), Sender); // executes a join action for end-user
                break;

            case LeftRoom l:
                if (_roomCounts.TryGetValue(l.RoomName, out var nextCount))
                {
                    _roomCounts[l.RoomName] = nextCount - 1;
                }
                else
                {
                    _roomCounts[l.RoomName] = 0;
                }
                break;

            default:
                Unhandled(message);
                break;
            }
        }
 private void State3()
 {
     Command <string>(s => s == "UNBECOME", __ => UnbecomeStacked());
     Command <string>(s => Sender.Tell("string3:" + s, Self));
 }