private XDocument DecodeContentAndCreateDocument(InboundMessage message)
		{
			string content = HttpUtility.HtmlDecode(message.Body);
			Match match = _eventPattern.Match(content);
			var document = XDocument.Parse(match.Value);
			return document;
		}
		public void SetUp()
		{
			string validSample = File.ReadAllText(@".\TestData\ValidMessage.json");
			_validMessageNoHeaders = new InboundMessage(validSample, new Dictionary<string, string[]>());

			string invalidSample = File.ReadAllText(@".\TestData\InValidMessage.json");
			_inValidMessageNoHeaders = new InboundMessage(invalidSample, new Dictionary<string, string[]>());
		}
		public void Execute_matches_expectations_for_single_message_cointaining_three_commits()
		{
			string sample = File.ReadAllText(@".\TestData\ValidMessageWithThreeCommits.json");
			var message = new InboundMessage(sample, new Dictionary<string, string[]>());

			var result = _translator.Execute(message);

			var translationResult = (InboundMessageResponse.TranslationResult.Recognized)result.TranslationResult;
			Approvals.Verify(JsonConvert.SerializeObject(translationResult.commits, Formatting.Indented));
		}
		public Translation.Result Execute(InboundMessage message)
		{
			try
			{
				IEnumerable<CommitMessage> commitMessages = GetCommitMessages(message.Body);
				return Translation.Success(commitMessages);
			}
			catch
			{
				return Translation.Failure("It was not possible to translate the message.");
			}
		}
		public void SetUp()
		{
			var headers = new Dictionary<string, string[]>()
			{
				{ "User-Agent", new[] { "Team Foundation (TfsJobAgent.exe, 10.0.40219.1)" } }
			};

			var validSampleData = File.ReadAllText(@".\TestData\ValidMessage.xml");
			_validMessage = new InboundMessage(validSampleData, headers);


			var inValidSampleData = File.ReadAllText(@".\TestData\InValidMessage.xml");
			_invalidMessage = new InboundMessage(inValidSampleData, headers);
		}
Example #6
0
			public void process(AGateway gateway, org.smslib.Message.MessageTypes msgType, InboundMessage msg)
			{
				if (msgType == org.smslib.Message.MessageTypes.INBOUND) Console.WriteLine(">>> New Inbound message detected from Gateway: " + gateway.getGatewayId());
				else if (msgType == org.smslib.Message.MessageTypes.STATUSREPORT) Console.WriteLine(">>> New Inbound Status Report message detected from Gateway: " + gateway.getGatewayId());
				Console.WriteLine(msg);
				try
				{
					// Uncomment following line if you wish to delete the message upon arrival.
					// gateway.deleteMessage(msg);
				}
				catch (Exception e)
				{
					Console.WriteLine("Oops!!! Something gone bad...");
					Console.WriteLine(e.Message);
					Console.WriteLine(e.StackTrace);
				}
			}
		public Translation.Result Execute(InboundMessage message)
		{
			try
			{
				XDocument document = DecodeContentAndCreateDocument(message);
				CommitMessage commit = ParseXmlDocument(document);

				return Translation.SuccessWithContent(
					new List<CommitMessage> { commit },
					new StringContent(GetResponseBody(), Encoding.UTF8, GetMediaType())
					);
			}
			catch
			{
				return Translation.FailureWithContent(
					"It was not possible to translate the message.",
					new StringContent(GetResponseBody(), Encoding.UTF8, GetMediaType())
					);
			}
		}
Example #8
0
        public void Transform_InboundMessage_HeadersProperlyModified()
        {
            var policy = _errorPolicyBuilder.Move(TestEndpoint.GetDefault())
                         .Transform((msg, ex) => new TestEventTwo(), (headers, ex) =>
            {
                headers.Add("error", ex.GetType().Name);
                return(headers);
            });

            var message = new InboundMessage(
                Encoding.UTF8.GetBytes("hey oh!"),
                null,
                null, TestEndpoint.GetDefault(), true);

            message.Headers.Add("key", "value");
            policy.HandleError(new[] { message }, new Exception("test"));

            var producer   = (TestProducer)_broker.GetProducer(TestEndpoint.GetDefault());
            var newHeaders = producer.ProducedMessages[0].Headers;

            newHeaders.Count.Should().Be(6); // message-id, message-type, key, traceid, error, source-endpoint
        }
        public void Create_InboundMessage_ValuesPreserved()
        {
            var inboundMessage = new InboundMessage
            {
                Message        = 1,
                Endpoint       = TestEndpoint.Default,
                FailedAttempts = 3,
                Offset         = new TestOffset("a", "b"),
                MustUnwrap     = true
            };

            inboundMessage.Headers.Add("h1", "h1");
            inboundMessage.Headers.Add("h2", "h2");

            var newInboundMessage = InboundMessageHelper.CreateNewInboundMessage(2, inboundMessage);

            newInboundMessage.Endpoint.Should().BeEquivalentTo(inboundMessage.Endpoint);
            newInboundMessage.FailedAttempts.Should().Be(inboundMessage.FailedAttempts);
            newInboundMessage.Offset.Should().BeEquivalentTo(inboundMessage.Offset);
            newInboundMessage.MustUnwrap.Should().Be(inboundMessage.MustUnwrap);
            newInboundMessage.Headers.Should().BeEquivalentTo(inboundMessage.Headers);
        }
Example #10
0
        private Task ListenTo(InboundMessage inboundMessage)
        {
            if (inboundMessage == null)
            {
                return(Task.CompletedTask);
            }

            switch (inboundMessage.MessageType)
            {
            case MessageType.Message: return(HandleMessage((ChatMessage)inboundMessage));

            case MessageType.Group_Joined: return(HandleGroupJoined((GroupJoinedMessage)inboundMessage));

            case MessageType.Channel_Joined: return(HandleChannelJoined((ChannelJoinedMessage)inboundMessage));

            case MessageType.Im_Created: return(HandleDmJoined((DmChannelJoinedMessage)inboundMessage));

            case MessageType.Team_Join: return(HandleUserJoined((UserJoinedMessage)inboundMessage));
            }

            return(Task.CompletedTask);
        }
Example #11
0
        public Translation.Result Execute(InboundMessage message)
        {
            try
            {
                XDocument     document = DecodeContentAndCreateDocument(message);
                CommitMessage commit   = ParseXmlDocument(document);

                return(Translation.SuccessWithContent(
                           new List <CommitMessage> {
                    commit
                },
                           new StringContent(GetResponseBody(), Encoding.UTF8, GetMediaType())
                           ));
            }
            catch
            {
                return(Translation.FailureWithContent(
                           "It was not possible to translate the message.",
                           new StringContent(GetResponseBody(), Encoding.UTF8, GetMediaType())
                           ));
            }
        }
Example #12
0
        public void OBOLogoutTest()
        {
            SymOBOAuth oboAuth = new SymOBOAuth(symConfig);

            oboAuth.sessionAppAuthenticate();
            SymOBOUserAuth auth   = oboAuth.getUserAuth("*****@*****.**");
            SymOBOClient   client = SymOBOClient.initOBOClient(symConfig, auth);

            OutboundMessage message = new OutboundMessage();

            message.message = "<messageML>Hello Alexa</messageML>";

            apiClientDotNet.Models.Stream stream = new apiClientDotNet.Models.Stream();
            stream.streamId = "IzgD3nNbpoaNJ6_To7Ds0n___pmCBYMrdA";

            MessageClient  messageClient = new MessageClient(client);
            InboundMessage resp          = messageClient.sendMessage(stream.streamId, message, false);

            auth.logout();


            //Assert.IsTrue(resp.message != null);
        }
Example #13
0
        public void HandleError_InboundMessage_HeadersPreserved()
        {
            var policy = _errorPolicyBuilder.Move(TestEndpoint.GetDefault());

            var message = new InboundMessage(
                Encoding.UTF8.GetBytes("hey oh!"),
                null,
                null, TestEndpoint.GetDefault(), true)
            {
                Content = "hey oh!",
                Headers =
                {
                    { "key1", "value1" },
                    { "key2", "value2" }
                }
            };

            policy.HandleError(new[] { message }, new Exception("test"));

            var producer = (TestProducer)_broker.GetProducer(TestEndpoint.GetDefault());

            producer.ProducedMessages.Last().Headers.Should().Contain(message.Headers);
        }
Example #14
0
        protected override void UpdateReceived(Client c, InboundMessage m)
        {
            Player player;

            if (!playerObjects.TryGetValue(c.ID, out player))
            {
                return;
            }

            Keys pressed = (Keys)m.ReadByte();

            if ((pressed & Keys.Up) == Keys.Up)
            {
                player.sy = -Player.speed;
            }
            else if ((pressed & Keys.Down) == Keys.Down)
            {
                player.sy = Player.speed;
            }
            else
            {
                player.sy = 0;
            }

            if ((pressed & Keys.Left) == Keys.Left)
            {
                player.sx = -Player.speed;
            }
            else if ((pressed & Keys.Right) == Keys.Right)
            {
                player.sx = Player.speed;
            }
            else
            {
                player.sx = 0;
            }
        }
Example #15
0
 public void Add(InboundMessage m)
 {
     Add(m, false);
 }
Example #16
0
        protected virtual bool MessageReceived(Client c, InboundMessage m)
        {
            OutboundMessage o;

            switch ((EngineMessage)m.Type)
            {
            case EngineMessage.InitialData:
            {
                short num = m.ReadShort();
                for (int i = 0; i < num; i++)
                {
                    c.SetVariable(m.ReadString(), m.ReadString());
                }

                string name = c.Name;

                // tell all other clients about this new client
                o = OutboundMessage.CreateReliable((byte)EngineMessage.ClientConnected, false, SequenceChannel.System);
                o.Write(name);
                Client.SendToAllExcept(o, c);

                ClientConnected(c);

                // send ServerInfo to the newly-connected client, which as well as the network table hash,
                // tells them how/if we've modified their name, the names of everyone else on the server, and all the server variables

                // is it worth having name be a variable here?

                // how would name change work?
                // when you try to change the name, it always fails, but sends a "name change" to the server
                // that sends a "name change" to everyone else, and a special one back to you that actaully updates the variable
                o = OutboundMessage.CreateReliable((byte)EngineMessage.InitialData, false, SequenceChannel.System);
                o.Write(NetworkedEntity.NetworkTableHash);
                o.Write(CurrentTick);
                o.Write(c.Name);

                List <Client> otherClients = Client.GetAllExcept(c);
                o.Write((byte)otherClients.Count);
                foreach (Client other in otherClients)
                {
                    o.Write(other.Name);
                }

                ushort numVars = 0;
                var    allVars = Variable.GetEnumerable();

                foreach (var v in allVars)
                {
                    if (v.HasFlags(VariableFlags.Server))
                    {
                        numVars++;
                    }
                }
                o.Write(numVars);

                foreach (var v in allVars)
                {
                    if (v.HasFlags(VariableFlags.Server))
                    {
                        o.Write(v.Name);
                        o.Write(v.Value);
                    }
                }

                c.Send(o);
                c.NextSnapshotTime = FrameTime + c.SnapshotInterval;
                c.FullyConnected   = true;
                return(true);
            }

            case EngineMessage.ClientNameChange:
            {
                string oldName = c.Name;
                string name    = m.ReadString();
                c.Name = name;
                name   = c.Name;       // if it wasn't unique, it'll have been changed

                // tell everyone else about the change
                o = OutboundMessage.CreateReliable((byte)EngineMessage.ClientNameChange, false, SequenceChannel.Chat);
                o.Write(name);
                o.Write(false);
                o.Write(oldName);
                Client.SendToAllExcept(o, c);

                // tell this client their "tidied" name
                o = OutboundMessage.CreateReliable((byte)EngineMessage.ClientNameChange, false, SequenceChannel.Chat);
                o.Write(name);
                o.Write(true);
                c.Send(o);

                if (IsDedicated)
                {
                    Console.WriteLine("{0} changed name to {1}", oldName, name);
                }

                return(true);
            }

            case EngineMessage.VariableChange:
            {
                string name = m.ReadString();
                string val  = m.ReadString();

                c.SetVariable(name, val);
                return(true);
            }

            case EngineMessage.ClientUpdate:
            {
                if (!c.FullyConnected)
                {
                    return(true);        // this might come through before the InitialData message
                }
                c.LastAcknowledgedTick = m.ReadUInt();
                UpdateReceived(c, m);
                return(true);
            }

            default:
                return(false);
            }
        }
		private bool ContainsGitHubEventHeaderAndIsPush(InboundMessage message)
		{
			return message.Headers.ContainsKey("X-Github-Event")
				&& message.Headers["X-Github-Event"].Contains("push");
		}
        public Call GenerateCall(InboundMessage email, string managingUser, List <string> users, Department department, List <Call> activeCalls, List <Unit> units, int priority)
        {
            if (email == null)
            {
                return(null);
            }

            if (String.IsNullOrEmpty(email.HtmlBody))
            {
                return(null);
            }

            if (!email.Subject.Contains("Parkland County Incident") && !email.Subject.Contains("Incident Message"))
            {
                return(null);
            }

            var c = new Call();

            c.Notes = email.HtmlBody;

            try
            {
                var      data    = new List <string>();
                string[] rawData = email.HtmlBody.Split(new string[] { "\r\n", "\r\n\r\n" }, StringSplitOptions.None);

                if (rawData != null && rawData.Any())
                {
                    foreach (string s in rawData)
                    {
                        if (!string.IsNullOrWhiteSpace(s))
                        {
                            data.Add(s);
                        }
                    }

                    if (data.Count > 0)
                    {
                        c.Name = data[1].Trim().Replace("Type: ", "");

                        try
                        {
                            var location = data.FirstOrDefault(x => x.StartsWith("Location:"));

                            if (!String.IsNullOrWhiteSpace(location))
                            {
                                c.Address = location.Replace("//", "").Replace("Business Name:", "");
                            }

                            var coordinates = data.FirstOrDefault(x => x.Contains("(") && x.Contains(")"));

                            if (!String.IsNullOrWhiteSpace(coordinates))
                            {
                                coordinates       = coordinates.Replace("Common Place:", "");
                                coordinates       = coordinates.Trim();
                                c.GeoLocationData = coordinates.Replace("(", "").Replace(")", "");
                            }
                        }
                        catch
                        { }
                    }
                }
                else
                {
                    c.Name = "Call Import Type: Unknown";
                }
            }
            catch
            {
                c.Name = "Call Import Type: Unknown";
            }

            c.NatureOfCall     = email.HtmlBody;
            c.LoggedOn         = DateTime.UtcNow;
            c.Priority         = priority;
            c.ReportingUserId  = managingUser;
            c.Dispatches       = new List <CallDispatch>();
            c.CallSource       = (int)CallSources.EmailImport;
            c.SourceIdentifier = email.MessageID;

            foreach (var u in users)
            {
                var cd = new CallDispatch();
                cd.UserId = u;

                c.Dispatches.Add(cd);
            }


            return(c);
        }
Example #19
0
 public bool CanProcess(InboundMessage message)
 {
     return(ContainsGitHubEventHeaderAndIsPush(message));
 }
        public Call GenerateCall(InboundMessage email, string managingUser, List <string> users, Department department, List <Call> activeCalls, List <Unit> units, int priority)
        {
            if (email == null)
            {
                return(null);
            }

            if (String.IsNullOrEmpty(email.HtmlBody))
            {
                return(null);
            }

            if (String.IsNullOrEmpty(email.Subject))
            {
                return(null);
            }

            Call c = new Call();

            c.Notes = email.Subject + " " + email.HtmlBody;
            c.Name  = email.Subject;

            string[] data = email.HtmlBody.Split(char.Parse(","));

            if (data.Length >= 1)
            {
                int tryPriority;

                if (int.TryParse(data[0], out tryPriority))
                {
                    c.Priority = tryPriority;
                }
            }
            else
            {
                c.Priority = (int)ApiClient.Common.CallPriority.High;
            }

            if (data.Length >= 2)
            {
                if (data[1].Length > 3)
                {
                    c.NatureOfCall = data[1];
                }
            }
            else
            {
                c.NatureOfCall = email.HtmlBody;
            }

            if (data.Length >= 3)
            {
                if (data[2].Length > 3)
                {
                    string address = String.Empty;

                    if (!data[2].Contains("United Kingdom"))
                    {
                        address = data[2] + "United Kingdom";
                    }

                    c.Address = address;
                }
            }

            c.LoggedOn         = DateTime.UtcNow;
            c.Priority         = priority;
            c.ReportingUserId  = managingUser;
            c.Dispatches       = new List <CallDispatch>();
            c.CallSource       = (int)CallSources.EmailImport;
            c.SourceIdentifier = email.MessageID;

            //if (email.DispatchAudio != null)
            //{
            //	c.Attachments = new Collection<CallAttachment>();

            //	CallAttachment ca = new CallAttachment();
            //	ca.FileName = email.DispatchAudioFileName;
            //	ca.Data = email.DispatchAudio;
            //	ca.CallAttachmentType = (int)CallAttachmentTypes.DispatchAudio;

            //	c.Attachments.Add(ca);
            //}

            foreach (var u in users)
            {
                var cd = new CallDispatch();
                cd.UserId = u;

                c.Dispatches.Add(cd);
            }

            return(c);
        }
Example #21
0
 /// <summary>
 /// Creates a new envelope containing a message.
 /// </summary>
 /// <param name="msg">The message.</param>
 /// <param name="namespace">The namespace.</param>
 internal Envelope(InboundMessage msg, Namespace @namespace)
 {
     _msg       = msg;
     _namespace = @namespace;
 }
 public ExistsInDbState WithParameters(Mapping mappings, InboundMessage inboundMessage)
 {
     _inboundMessage = inboundMessage;
     _mappings       = mappings;
     return(this);
 }
		public bool CanProcess(InboundMessage message)
		{
			return IsUserAgentFromTfs(message.Headers) && IsCheckInEvent(message.Body);
		}
            public void postData(AGateway gateway, InboundMessage msg, String[] mssg)
            {
                if(mssg.Length == 7)
                    {
                    //means complete message with login key
                    url = "http://localhost/devfest/geocode.php?key=" + mssg[1] + "&name=" + mssg[2] + "&cnic=" + mssg[3]
                        + "&location=" + mssg[4].Trim() + "&disease=" + mssg[5] + "&contact=" + mssg[6];
                    a = false;
                    }
                else if(mssg.Length == 2)
                    {
                    //just to identify that key is correct. not used yet
                    }
                else if(mssg.Length == 5)
                    {
                    url = "http://localhost/devfest/geocodee.php?name=" + mssg[1] + "&cnic=" + mssg[2]
                        + "&location=" + mssg[3].Trim() + "&disease=" + mssg[4] + "&contact=" + msg.getOriginator();
                    a = true;
                    //means complete message without login key
                    }

                WebRequest request = HttpWebRequest.Create(url);

                WebResponse response = request.GetResponse();

                StreamReader reader = new StreamReader(response.GetResponseStream());

                string urlText = reader.ReadToEnd();
                Console.WriteLine(urlText);

                try
                    {
                    // Uncomment following line if you wish to delete the message upon arrival.
                    gateway.deleteMessage(msg);

                    }
                catch(Exception e)
                    {
                    Console.WriteLine("Oops!!! Something gone bad...");
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                    }
                OutboundMessage msg1 = new OutboundMessage("+"+msg.getOriginator(), urlText);
                srv.sendMessage(msg1);
                if(a)
                    {
                    checkThreats(mssg[4],mssg[3].Trim(),msg);
                    }
                else
                    {
                    checkThreats(mssg[5],mssg[4].Trim(),msg);
                    }
            }
 public void process(AGateway gateway, org.smslib.Message.MessageTypes msgType, InboundMessage msg)
 {
     string message = msg.getText().Trim();
     if(message.Substring(0,2).Equals("p?",StringComparison.OrdinalIgnoreCase))
         {
         Console.WriteLine(message);
         String[] mssg = message.Split('?');
         postData(gateway, msg, mssg);
         }
 }
            public void checkThreats(string desease,string location, InboundMessage msg)
            {
                if(desease.ToLower().Contains("dengue"))
                    {
                    url = "http://localhost/devfest/geocode.php?disease=" + desease + "&location="+location;
                    WebRequest request = HttpWebRequest.Create(url);

                    WebResponse response = request.GetResponse();

                    StreamReader reader = new StreamReader(response.GetResponseStream());

                    string urlText = reader.ReadToEnd();
                    if(urlText.Equals("alert")){
                        //Here the Alerts will be sent. For test case I am sending alert to my team member
                    OutboundMessage msg1 = new OutboundMessage("+923025474347", "Dengue Alert!!!\n Dengue is Spreading near "+location);
                    srv.sendMessage(msg1);
                    Console.WriteLine("Dengue Alert!!!\n Dengue is Spreading near " + location);
                        }
                    }
            }
        public Call GenerateCall(InboundMessage email, string managingUser, List <string> users, Department department, List <Call> activeCalls, List <Unit> units, int priority)
        {
            if (email == null)
            {
                return(null);
            }

            if (String.IsNullOrEmpty(email.HtmlBody))
            {
                return(null);
            }

            Call c = new Call();

            c.Notes = email.HtmlBody;
            c.Name  = email.Subject;

            int nonEmptyLineCount = 0;

            string[] rawData = email.HtmlBody.Split(new string[] { "\r\n", "\r\n\r\n" }, StringSplitOptions.None);

            foreach (var line in rawData)
            {
                if (line != null && !String.IsNullOrWhiteSpace(line))
                {
                    nonEmptyLineCount++;

                    switch (nonEmptyLineCount)
                    {
                    case 1:
                        //c.Name = line.Trim();
                        c.NatureOfCall = line.Trim();
                        break;

                    case 2:                             // Address
                                                        //c.Name = $"{c.Name} {line}";
                        c.NatureOfCall = c.NatureOfCall + " " + line;
                        break;

                    case 3:                             // Map and Radio Channel
                        break;

                    case 4:                             // Cross Street
                        break;

                    case 5:                             // Cross Street 2
                        break;
                    }
                }
            }

            c.LoggedOn         = DateTime.UtcNow;
            c.Priority         = priority;
            c.ReportingUserId  = managingUser;
            c.Dispatches       = new List <CallDispatch>();
            c.CallSource       = (int)CallSources.EmailImport;
            c.SourceIdentifier = email.MessageID;

            foreach (var u in users)
            {
                var cd = new CallDispatch();
                cd.UserId = u;

                c.Dispatches.Add(cd);
            }

            return(c);
        }
Example #28
0
 private bool ContainsGitHubEventHeaderAndIsPush(InboundMessage message)
 {
     return(message.Headers.ContainsKey("X-Github-Event") &&
            message.Headers["X-Github-Event"].Contains("push"));
 }
Example #29
0
 public bool CanProcess(InboundMessage message)
 {
     return(IsUserAgentFromTfs(message.Headers) && IsCheckInEvent(message.Body));
 }
 public void RaiseOnMessage(InboundMessage message)
 {
     OnMessage.Invoke(this, message);
 }
Example #31
0
        public Call GenerateCall(InboundMessage email, string managingUser, List <string> users, Department department, List <Call> activeCalls, List <Unit> units, int priority)
        {
            if (email == null)
            {
                return(null);
            }

            if (String.IsNullOrEmpty(email.HtmlBody) && String.IsNullOrWhiteSpace(email.TextBody))
            {
                return(null);
            }

            string body = String.Empty;

            if (!String.IsNullOrWhiteSpace(email.TextBody))
            {
                body = email.TextBody;
            }
            else
            {
                body = email.HtmlBody;
            }

            body = body.Replace("-- Confidentiality Notice --", "");
            body =
                body.Replace(
                    "This email message, including all the attachments, is for the sole use of the intended recipient(s) and contains confidential information. Unauthorized use or disclosure is prohibited.",
                    "");
            body =
                body.Replace(
                    "If you are not the intended recipient, you may not use, disclose, copy or disseminate this information.",
                    "");
            body =
                body.Replace(
                    "If you are not the intended recipient, please contact the sender immediately by reply email and destroy all copies of the original message,",
                    "");
            body =
                body.Replace(
                    "including attachments.",
                    "");
            body = body.Trim();

            var c = new Call();

            c.Notes = email.TextBody;

            if (String.IsNullOrWhiteSpace(c.Notes))
            {
                c.Notes = email.HtmlBody;
            }

            string[] data = body.Split(char.Parse(":"));
            c.IncidentNumber   = data[1].Replace(" L", "").Trim();
            c.Type             = data[3].Replace(" X", "").Trim().Replace("/", "");
            c.Address          = data[2].Replace(" T", "").Trim().Replace("/", "");
            c.NatureOfCall     = data[4].Trim();
            c.Name             = c.Type + " " + c.NatureOfCall;
            c.LoggedOn         = DateTime.UtcNow;
            c.Priority         = priority;
            c.ReportingUserId  = managingUser;
            c.Dispatches       = new List <CallDispatch>();
            c.CallSource       = (int)CallSources.EmailImport;
            c.SourceIdentifier = email.MessageID;

            foreach (var u in users)
            {
                var cd = new CallDispatch();
                cd.UserId = u;

                c.Dispatches.Add(cd);
            }

            return(c);
        }
Example #32
0
 protected abstract void UpdateReceived(Client c, InboundMessage m);
 protected override void When()
 {
     Result = SUT.InterpretMessage(Json);
 }
Example #34
0
        protected internal virtual bool MessageReceived(InboundMessage m)
        {
            switch ((EngineMessage)m.Type)
            {
            case EngineMessage.InitialData:
            {
                byte[] hash = m.ReadBytes(16);
                if (!NetworkedEntity.CheckNetworkTableHash(hash))
                {
                    Console.Error.WriteLine("Network table doesn't match server's");
                    Disconnect();
                    return(true);
                }

                CurrentTick = m.ReadUInt() - (uint)(LerpDelay.TotalSeconds / TickInterval.TotalSeconds);

                string name = m.ReadString();
                Name.ForceValue(name);
                Console.WriteLine("My name, corrected by server: " + name);

                byte numOthers = m.ReadByte();

                Console.WriteLine("There {0} {1} other {2} connected to this server{3}",
                                  numOthers == 1 ? "is" : "are",
                                  numOthers == 0 ? "no" : numOthers.ToString(),
                                  numOthers == 1 ? "client" : "clients",
                                  numOthers == 0 ? string.Empty : ":"
                                  );

                for (int i = 0; i < numOthers; i++)
                {
                    string otherName = m.ReadString();
                    Console.WriteLine(" * " + otherName);
                }

                ushort num = m.ReadUShort();
                for (int i = 0; i < num; i++)
                {
                    Variable var = Variable.Get(m.ReadString());
                    string   val = m.ReadString();
                    if (var != null)
                    {
                        var.ForceValue(val);
                    }
                }

                nextFrameTime  = DateTime.Now;
                FullyConnected = true;
                return(true);
            }

            case EngineMessage.ClientConnected:
            {
                string clientName = m.ReadString();

                Console.WriteLine(clientName + " joined the game");
                return(true);
            }

            case EngineMessage.ClientNameChange:
            {
                string newName = m.ReadString();

                if (m.ReadBool())
                {        // it's me!
                    //this is a cheeky hack, to avoid having to add a new variable just to stop the callback sending it's message again
                    FullyConnected = false;
                    Name.ForceValue(newName);
                    FullyConnected = true;
                    Console.WriteLine("You changed your name to {0}", newName);
                }
                else
                {        // someone else
                    string oldName = m.ReadString();
                    Console.WriteLine("{0} changed name to {1}", oldName, newName);
                }
                return(true);
            }

            case EngineMessage.Snapshot:
            {
                Snapshot.Read(m);
                return(true);
            }

            case EngineMessage.VariableChange:
            {
                string name = m.ReadString();
                string val  = m.ReadString();

                Variable var = Variable.Get(name);
                if (var != null)
                {
                    var.ForceValue(val);
                }
                Variable.WriteChange(name, val);
                return(true);
            }

            default:
                return(false);
            }
        }
        public Call GenerateCall(InboundMessage email, string managingUser, List <string> users, Department department, List <Call> activeCalls, List <Unit> units, int priority)
        {
            if (email == null)
            {
                return(null);
            }

            if (String.IsNullOrEmpty(email.HtmlBody))
            {
                return(null);
            }

            if (String.IsNullOrEmpty(email.Subject))
            {
                return(null);
            }

            if (!email.Subject.Contains("Perform Page"))
            {
                return(null);
            }

            Call c = new Call();

            c.Notes        = email.Subject + " " + email.HtmlBody;
            c.NatureOfCall = email.HtmlBody;

            List <string> data = new List <string>();

            string[] rawData = email.HtmlBody.Split(new string[] { "\r\n", "\r\n\r\n" }, StringSplitOptions.None);

            foreach (string s in rawData)
            {
                if (!string.IsNullOrWhiteSpace(s))
                {
                    data.Add(s);
                }
            }

            if (data.Count >= 1)
            {
                c.Name = data[0];
            }
            else
            {
                c.Name = email.Subject;
            }

            if (data.Count == 5)
            {
                string firstLine = string.Empty;

                if (data[1].ToUpper().Contains("AND"))
                {
                    string[] firstLineParts = data[1].Split(new string[] { "AND" }, StringSplitOptions.None);

                    if (!string.IsNullOrWhiteSpace(firstLineParts[0]))
                    {
                        firstLine = firstLineParts[0];
                    }
                }
                else if (data[1].ToUpper().Contains("/"))
                {
                    string[] firstLineParts = data[1].Split(new string[] { "/" }, StringSplitOptions.None);

                    if (!string.IsNullOrWhiteSpace(firstLineParts[0]))
                    {
                        firstLine = firstLineParts[0];
                    }
                }
                else
                {
                    firstLine = data[1];
                }

                c.Address = string.Format("{0} {1}", firstLine, data[2]);
            }
            else if (data.Count == 6)
            {
                c.Address = string.Format("{0} {1}", data[2], data[3]);
            }

            c.LoggedOn         = DateTime.UtcNow;
            c.Priority         = priority;
            c.ReportingUserId  = managingUser;
            c.Dispatches       = new List <CallDispatch>();
            c.CallSource       = (int)CallSources.EmailImport;
            c.SourceIdentifier = email.MessageID;

            //if (email.DispatchAudio != null)
            //{
            //	c.Attachments = new Collection<CallAttachment>();

            //	CallAttachment ca = new CallAttachment();
            //	ca.FileName = email.DispatchAudioFileName;
            //	ca.Data = email.DispatchAudio;
            //	ca.CallAttachmentType = (int)CallAttachmentTypes.DispatchAudio;

            //	c.Attachments.Add(ca);
            //}

            foreach (var u in users)
            {
                var cd = new CallDispatch();
                cd.UserId = u;

                c.Dispatches.Add(cd);
            }

            return(c);
        }
Example #36
0
        /// <summary>
        /// Save the given message to the underlying storage system.
        /// </summary>
        /// <param name="context">The session context.</param>
        /// <param name="transaction">The SMTP message transaction to store.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A unique identifier that represents this message in the underlying message store.</returns>
        public override Task <SmtpResponse> SaveAsync(ISessionContext context, IMessageTransaction transaction, CancellationToken cancellationToken)
        {
            Init();

            var         textMessage = (ITextMessage)transaction.Message;
            MimeMessage mailMessage = MimeMessage.Load(textMessage.Content);

            Message message = new Message();

            message.Id          = Guid.NewGuid();
            message.RetryCount  = 0;
            message.ErrorReason = "";
            message.Timestamp   = DateTime.UtcNow;

            var inboundMessage = new InboundMessage();

            string fromAddress = String.Empty;

            if (mailMessage.From != null && mailMessage.From.Count > 0)
            {
                var from = ((MailboxAddress)mailMessage.From[0]);
                inboundMessage.From     = from.Address;
                fromAddress             = from.Address;
                inboundMessage.FromFull = new FromFull()
                {
                    Email = from.Address, Name = from.Name
                };
            }

            string toAddress = String.Empty;

            if (mailMessage.To != null && mailMessage.To.Count > 0)
            {
                inboundMessage.ToFull = new List <ToFull>();
                foreach (var to in mailMessage.To)
                {
                    var toAdd = (MailboxAddress)to;

                    if (String.IsNullOrWhiteSpace(inboundMessage.To))
                    {
                        inboundMessage.To = toAdd.Address;
                        toAddress         = toAdd.Address;
                    }

                    inboundMessage.ToFull.Add(new ToFull()
                    {
                        Email = toAdd.Address, Name = toAdd.Name
                    });
                }
            }

            _logger.Information("Email Received {id} {fromAddress} {toAddress}", message.Id, fromAddress, toAddress);

            var attachments = new List <MimePart>();
            var multiparts  = new List <Multipart>();
            var iter        = new MimeIterator(mailMessage);

            // collect our list of attachments and their parent multiparts
            while (iter.MoveNext())
            {
                var multipart = iter.Parent as Multipart;
                var part      = iter.Current as MimePart;

                if (multipart != null && part != null && part.IsAttachment)
                {
                    // keep track of each attachment's parent multipart
                    multiparts.Add(multipart);
                    attachments.Add(part);
                }
            }

            // now remove each attachment from its parent multipart...
            for (int i = 0; i < attachments.Count; i++)
            {
                multiparts[i].Remove(attachments[i]);
            }

            inboundMessage.TextBody  = mailMessage.GetTextBody(MimeKit.Text.TextFormat.Plain);
            inboundMessage.HtmlBody  = mailMessage.HtmlBody;
            inboundMessage.Subject   = mailMessage.Subject;
            inboundMessage.MessageID = mailMessage.MessageId;

            inboundMessage.Attachments = new List <Attachment>();
            foreach (var attachment in attachments)
            {
                var att = new Attachment();

                StreamReader reader = new StreamReader(attachment.Content.Stream);
                att.Content = reader.ReadToEnd();

                att.Name        = attachment.FileName;
                att.ContentID   = attachment.ContentId;
                att.ContentType = attachment.ContentType.MimeType;

                inboundMessage.Attachments.Add(att);
            }

            message.InboundMessage = inboundMessage;

            var fileText = JsonConvert.SerializeObject(message);
            var filePath = _fileService.CreateFile($"{message.Id.ToString()}.rgm", "emails", fileText);

            if (!String.IsNullOrWhiteSpace(filePath))
            {
                _logger.Information("Email Saved {id}", message.Id);
                return(Task.FromResult(SmtpResponse.Ok));
            }
            else
            {
                _logger.Information("Email Not Saved {id}", message.Id);
                return(Task.FromResult(new SmtpResponse(SmtpReplyCode.MessageTimeout)));
            }
        }
Example #37
0
 public NotExistsInDbState WithParameters(InboundMessage inboundMessage)
 {
     _inboundMessage = inboundMessage;
     return(this);
 }
 public Task<ResponseMessage> Handle(InboundMessage inboundMessage, CancellationToken cancellationToken, Func<Task<ResponseMessage>> continuation)
 {
     return continuation();
 }
Example #39
0
 public void process(AGateway gateway, org.smslib.Message.MessageTypes msgType, InboundMessage msg)
 {
     if (msgType == org.smslib.Message.MessageTypes.INBOUND)
     {
         Console.WriteLine(">>> New Inbound message detected from Gateway: " + gateway.getGatewayId());
     }
     else if (msgType == org.smslib.Message.MessageTypes.STATUSREPORT)
     {
         Console.WriteLine(">>> New Inbound Status Report message detected from Gateway: " + gateway.getGatewayId());
     }
     Console.WriteLine(msg);
     try
     {
         // Uncomment following line if you wish to delete the message upon arrival.
         // gateway.deleteMessage(msg);
     }
     catch (Exception e)
     {
         Console.WriteLine("Oops!!! Something gone bad...");
         Console.WriteLine(e.Message);
         Console.WriteLine(e.StackTrace);
     }
 }
            public string Parse()
            {
                var message = InboundMessage.ToString();

                return(message.Substring(0, message.IndexOf(EofTerminator, StringComparison.Ordinal)));
            }
Example #41
0
 /// <summary>
 /// Creates a new envelope containing a message.
 /// </summary>
 /// <param name="msg">The message.</param>
 /// <param name="node">The receiving node.</param>
 internal Envelope(InboundMessage msg, Node node)
 {
     _msg  = msg;
     _node = node;
 }
        public Call GenerateCall(InboundMessage email, string managingUser, List <string> users, Department department, List <Call> activeCalls, List <Unit> units, int priority)
        {
            if (email == null)
            {
                return(null);
            }

            if (String.IsNullOrEmpty(email.HtmlBody))
            {
                return(null);
            }

            if (!email.Subject.Contains("Parkland County Incident") && !email.Subject.Contains("Incident Message"))
            {
                return(null);
            }

            bool     is2ndPage    = false;
            string   priorityChar = null;
            DateTime callTimeUtc  = DateTime.UtcNow;

            var c = new Call();

            c.Notes = email.HtmlBody;

            try
            {
                var      data    = new List <string>();
                string[] rawData = email.HtmlBody.Split(new string[] { "\r\n", "\r\n\r\n" }, StringSplitOptions.None);

                if (rawData != null && rawData.Any())
                {
                    foreach (string s in rawData)
                    {
                        if (!string.IsNullOrWhiteSpace(s))
                        {
                            data.Add(s);
                        }
                    }

                    if (data.Count > 0)
                    {
                        c.Name = data[1].Trim().Replace("Type: ", "");

                        var priorityString = c.Name.Substring(0, c.Name.IndexOf(char.Parse("-"))).Trim();
                        priorityChar = Regex.Replace(priorityString, @"\d", "").Trim();

                        TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById(department.TimeZone);
                        callTimeUtc = new DateTimeOffset(DateTime.Parse(data[0].Replace("Date:", "").Trim()), timeZone.BaseUtcOffset).UtcDateTime;

                        is2ndPage = c.Notes.Contains("WCT2ndPage");

                        try
                        {
                            var location = data.FirstOrDefault(x => x.StartsWith("Location:"));

                            if (!String.IsNullOrWhiteSpace(location))
                            {
                                c.Address = location.Replace("//", "").Replace("Business Name:", "");
                            }

                            var coordinates = data.FirstOrDefault(x => x.Contains("(") && x.Contains(")"));

                            if (!String.IsNullOrWhiteSpace(coordinates))
                            {
                                coordinates       = coordinates.Replace("Common Place:", "");
                                coordinates       = coordinates.Trim();
                                c.GeoLocationData = coordinates.Replace("(", "").Replace(")", "");
                            }
                        }
                        catch
                        { }
                    }
                }
                else
                {
                    c.Name = "Call Import Type: Unknown";
                }
            }
            catch
            {
                c.Name = "Call Import Type: Unknown";
            }

            c.NatureOfCall     = email.HtmlBody;
            c.LoggedOn         = callTimeUtc;
            c.Priority         = PriorityMapping(priorityChar, is2ndPage, priority);
            c.ReportingUserId  = managingUser;
            c.Dispatches       = new List <CallDispatch>();
            c.UnitDispatches   = new List <CallDispatchUnit>();
            c.CallSource       = (int)CallSources.EmailImport;
            c.SourceIdentifier = email.MessageID;

            foreach (var u in users)
            {
                var cd = new CallDispatch();
                cd.UserId = u;

                c.Dispatches.Add(cd);
            }

            if (units != null && units.Any())
            {
                foreach (var unit in units)
                {
                    var ud = new CallDispatchUnit();
                    ud.UnitId           = unit.Id;
                    ud.LastDispatchedOn = DateTime.UtcNow;

                    c.UnitDispatches.Add(ud);
                }
            }

            // Search for an active call
            if (activeCalls != null && activeCalls.Any())
            {
                var activeCall = activeCalls.FirstOrDefault(x => x.Name == c.Name && x.LoggedOn == c.LoggedOn);

                if (activeCall != null)
                {
                    activeCall.Priority         = c.Priority;
                    activeCall.Notes            = c.Notes;
                    activeCall.LastDispatchedOn = DateTime.UtcNow;
                    activeCall.DispatchCount++;

                    return(activeCall);
                }
            }

            return(c);
        }
    public InboundMessage[] DoIt()
    {
        // Create new Service object - the parent of all and the main interface to you.
        Service srv;
        srv = Service.getInstance();
        InboundMessage[] list = new InboundMessage[100];

        // Modem Settings
        String comPort = "com6";
        String modemName = "huwawei";
        int port = 12000;
        String manufacturer = "huwawei";
        int portSpeed = 9600;

        // *** The tricky part ***
        // *** Comm2IP Driver ***
        // Create (and start!) as many Comm2IP threads as the modems you are using.
        // Be careful about the mappings - use the same mapping in the Gateway definition.
        Comm2IP.Comm2IP com1 = new Comm2IP.Comm2IP(new byte[] { 127, 0, 0, 1 }, port, comPort, portSpeed);

        try
        {
            Console.WriteLine("Example: Read messages from a serial gsm modem.");
            Console.WriteLine(Library.getLibraryDescription());
            Console.WriteLine("Version: " + Library.getLibraryVersion() + " test");

            // Start the COM listening thread.
            new Thread(new ThreadStart(com1.Run)).Start();

            // Lets set some callbacks.
            srv.setInboundMessageNotification(new InboundNotification());
            srv.setCallNotification(new CallNotification());
            srv.setGatewayStatusNotification(new GatewayStatusNotification());

            // Create the Gateway representing the serial GSM modem.
            // Due to the Comm2IP bridge, in SMSLib for .NET all modems are considered IP modems.
            IPModemGateway gateway = new IPModemGateway("modem.com4", "127.0.0.1", port, manufacturer, modemName);
            gateway.setIpProtocol(ModemGateway.IPProtocols.BINARY);

            // Set the modem protocol to PDU (alternative is TEXT). PDU is the default, anyway...
            gateway.setProtocol(AGateway.Protocols.PDU);

            // Do we want the Gateway to be used for Inbound messages?
            gateway.setInbound(true);

            // Do we want the Gateway to be used for Outbound messages?
            gateway.setOutbound(true);

            // Let SMSLib know which is the SIM PIN.
            gateway.setSimPin("0000");

            // Add the Gateway to the Service object.
            srv.addGateway(gateway);

            // Similarly, you may define as many Gateway objects, representing
            // various GSM modems, add them in the Service object and control all of them.

            // Start! (i.e. connect to all defined Gateways)
            srv.startService();

            // Printout some general information about the modem.
            Console.WriteLine();
            Console.WriteLine("Modem Information:");
            Console.WriteLine("  Manufacturer: " + gateway.getManufacturer());
            Console.WriteLine("  Model: " + gateway.getModel());
            Console.WriteLine("  Serial No: " + gateway.getSerialNo());
            Console.WriteLine("  SIM IMSI: " + gateway.getImsi());
            Console.WriteLine("  Signal Level: " + gateway.getSignalLevel() + "dBm");
            Console.WriteLine("  Battery Level: " + gateway.getBatteryLevel() + "%");
            Console.WriteLine();

            // Read Messages. The reading is done via the Service object and
            // affects all Gateway objects defined. This can also be more directed to a specific
            // Gateway - look the JavaDocs for information on the Service method calls.
            list = srv.readMessages(org.smslib.InboundMessage.MessageClasses.ALL);

        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
        }
        finally
        {

            com1.Stop();
            srv.stopService();
        }

        return list;
    }
		public bool CanProcess(InboundMessage message)
		{
			return ContainsGitHubEventHeaderAndIsPush(message);
		}
 public Task<ResponseMessage> Handle(InboundMessage inboundMessage, CancellationToken cancellationToken, Func<Task<ResponseMessage>> continuation)
 {
     return new Task<ResponseMessage>(() => new ResponseMessage(string.Format("Message '{0}' handled.", inboundMessage.Message)));
 }
Example #46
0
        public static void Read(InboundMessage m)
        {
            // As we're only using timestamps, how should we determine (when trying to apply it) if we're MISSING a snapshot, or not?
            // Rather than have a frame number in the snapshot, we can compare the time difference to the server frame interval variable.
            // That would struggle when the variable changes ... or would it? If the variable change wasn't applied until the relevant snapshot came in, we might get away with it.

            Snapshot s = new Snapshot(m.ReadUInt());

            while (m.HasMoreData())
            {
                ushort             entityID     = m.ReadUShort();
                EntitySnapshotType snapshotType = (EntitySnapshotType)m.ReadByte();
                NetworkedEntity    ent;
                switch (snapshotType)
                {
                case EntitySnapshotType.Full:
                    string type = m.ReadString();
                    if (!NetworkedEntity.NetworkedEntities.TryGetValue(entityID, out ent))
                    {
                        s.ScheduleCreation(entityID, type, m, s.Tick);
                    }
                    else if (ent.NetworkedType != type)
                    {    // delete and create new (this was an error, so also log it)
                        s.Deletions.Add(entityID);
                        s.ScheduleCreation(entityID, type, m, s.Tick);
                        Console.Error.WriteLine("Error reading snapshot: entity {0} has the wrong type (got {1}, update has {2})", entityID, ent.NetworkedType, type);
                        return;
                    }
                    else
                    {
                        ent.ReadSnapshot(m, s.Tick, false);
                    }
                    break;

                case EntitySnapshotType.Partial:
                    if (NetworkedEntity.NetworkedEntities.TryGetValue(entityID, out ent))
                    {
                        ent.ReadSnapshot(m, s.Tick, true);
                    }
                    else
                    {
                        Console.Error.WriteLine("Error reading snapshot: received an update for unknown entity " + entityID);
                        return;
                    }
                    break;

                case EntitySnapshotType.Delete:
                    s.Deletions.Add(entityID);
                    break;

                case EntitySnapshotType.Replace:
                    // delete then treat like a full update
                    s.Deletions.Add(entityID);
                    s.ScheduleCreation(entityID, m.ReadString(), m, s.Tick);
                    break;

                default:
                    Console.Error.WriteLine("Error reading snapshot: invalid EntitySnapshotType: " + snapshotType);
                    return;
                }
            }

            if (s.Tick > GameClient.Instance.LatestSnapshotTick)
            {
                GameClient.Instance.LatestSnapshotTick = s.Tick;
            }

            if (s.Creations.Count != 0 || s.Deletions.Count != 0)
            {
                Enqueue(s);
            }
        }