示例#1
0
        private void btnCancelBooking_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                bool   isCanceled = Convert.ToBoolean(dataGridView1.CurrentRow.Cells["IsCanceled"].Value.ToString());
                string bookingID  = dataGridView1.CurrentRow.Cells["Id"].Value.ToString();

                if (!isCanceled)
                {
                    BookingModel bookingModel = new BookingModel();
                    bookingModel.GetBooking(bookingID);

                    FlightsModel flightsModel = new FlightsModel();
                    string       flightNumber = dataGridView1.CurrentRow.Cells["Flight"].Value.ToString();
                    flightsModel.GetFlight(flightNumber);

                    PersonModel personModel = new PersonModel();
                    string      id          = dataGridView1.CurrentRow.Cells["Cust. Id"].Value.ToString();
                    personModel.GetPerson(id);

                    FormAddBooking form = new FormAddBooking(personModel, flightsModel, bookingModel);
                    form.ShowDialog();
                }
                else
                {
                    string message = $"This booking order {bookingID} is already canceled!!!";
                    MessageInformation.Information(message);
                }
            }
        }
示例#2
0
        private void btnAddPerson_Click(object sender, EventArgs e)
        {
            if (ValidateInputs())
            {
                try
                {
                    personModel.InsertPerson(
                        txtFirstName.Text,
                        txtLastName.Text,
                        txtPhone.Text,
                        txtEmail.Text,
                        txtStreet.Text,
                        txtCity.Text,
                        txtProvince.Text,
                        txtPostalCode.Text);

                    string message = "Insert Successful !!!";
                    MessageInformation.Success(message);
                    //string caption = "Access to the Database";
                    //MessageBox.Show(message, caption, MessageBoxButton.OK, MessageBoxImage.Hand);
                }
                catch (Exception ex)
                {
                    MessageInformation.Error(ex.ToString());
                }

                Close();
            }
        }
示例#3
0
        private void btnSaveEdition_Click(object sender, EventArgs e)
        {
            if (ValidateInputs())
            {
                try
                {
                    personModel.EditPerson(
                        id,
                        txtFirstName.Text,
                        txtLastName.Text,
                        txtPhone.Text,
                        txtEmail.Text,
                        txtStreet.Text,
                        txtCity.Text,
                        txtProvince.Text,
                        txtPostalCode.Text);

                    string message = "Update Successful!!!";
                    // string caption = "Access to the Database";
                    MessageInformation.Success(message);

                    //Close();
                }
                catch (Exception ex)
                {
                    MessageInformation.Error(ex.ToString());
                }
            }
        }
示例#4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MessagePath"/> class.
 /// </summary>
 /// <param name="information">The information.</param>
 /// <param name="forParent">if set to <c>true</c> [for parent].</param>
 public MessagePath(MessageInformation information, bool forParent)
 {
     this.Configuration = IoC.Get<IServiceConfiguration>();
     this.SecurityManager = IoC.Get<ISecurityManager>();
     this.Information = information;
     this.Build(forParent);
 }
示例#5
0
        private void btnAddFlight_Click(object sender, EventArgs e)
        {
            if (ValidateInputs())
            {
                try
                {
                    flight.InsertFlight(txtFlightNumber.Text,
                                        txtPortOrigin.Text,
                                        txtDestinationPort.Text,
                                        txtMaxNumberSeats.Text,
                                        txtPrice.Text,
                                        txtFlightDate.Text,
                                        txtFlightTime.Text,
                                        txtDuration.Text);

                    string message = "Insert Successful !!!";
                    // string caption = "Access to the Database";
                    MessageInformation.Success(message);

                    Close();
                }
                catch (Exception ex)
                {
                    MessageInformation.Error("Insertion fail\n\n" + ex);
                }
            }
        }
示例#6
0
        internal static void MessageBeginPost(MessageDestination destination, int messageType, IntPtr floatValue, IntPtr playerEntity)
        {
            if (firstMessage)
            {
                // there is no event which intercepts between
                // the registering part and the first message (weaponlist in cstrike case)
                // so we need to initialize the game mode before the first message so we can
                // intercept this valuable information
                switch (Server.GameDirectory)
                {
                case "cstrike":
                    CounterStrike.CounterStrike.Init();
                    break;
                }
                firstMessage = false;
            }

                        #if DEBUG
            messageInformation = new MessageInformation(destination, messageType, floatValue, playerEntity);
            messageInformation.CallTimeBegin = DateTime.Now;
                        #endif

            message_header   = new MessageHeader(destination, messageType, floatValue, playerEntity);
            message_elements = new List <object>();

            MetaModEngine.SetResult(MetaResult.Handled);
        }
示例#7
0
        public MessageModalViewModel(MessageInformation messageInformation)
        {
            Title     = messageInformation.Title;
            Message   = messageInformation.Message;
            OkMessage = messageInformation.OkMessage;

            OkCommand = new RelaySimpleCommand(Ok);
        }
        private void Messenger_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            MessageInformation receivedMessage = e.Message;

            logger.InfoFormat("Received message from [{0}] on [{1}]", receivedMessage.PhoneNumber, receivedMessage.ReceivedDate.ToString());

            // Save the message
            SaveIncomingMessage(receivedMessage);
        }
示例#9
0
 public Message Get(Message message)
 {
     MessageInformation information = new MessageInformation(message);
     try
     {
         string sessionToken = this.GetSessionToken(information);
         MessagePath path = new MessagePath(information);
         ISecurityManager securityManager = IoC.Get<ISecurityManager>();
         object response;
         if (path.IsByParent)
         {
             MessagePath parentPath = new MessagePath(information, true);
             if (!parentPath.HasKeyParameter)
             {
                 throw new ArgumentException("A link to a parent must have parameter key");
             }
             dynamic bo = securityManager.DynamicGetBO(parentPath.DtoType, sessionToken);
             object parent = bo.GetOne(string.Empty, parentPath.QueryInfo);
             IObjectProxy proxy = ObjectProxyFactory.Get(parent);
             object value = proxy.GetValue(parent, path.ParentKeyParameter);
             QueryInfo query = new QueryInfo();
             query.Equal(path.KeyParameterName, value.ToString());
             bo = securityManager.DynamicGetBO(path.DtoType, sessionToken);
             response = bo.GetOne(string.Empty, query);
         }
         else
         {
             dynamic bo = securityManager.DynamicGetBO(path.DtoType, sessionToken);
             if (path.HasKeyParameter)
             {
                 response = bo.GetOne(string.Empty, path.QueryInfo);
             }
             else
             {
                 response = bo.GetAll(path.QueryInfo);
             }
         }
         IServiceConfiguration configuration = IoC.Get<IServiceConfiguration>();
         JsonSerializerSettings settings = IoC.Get<JsonSerializerSettings>();
         if (configuration.IsHateoas)
         {
             response = this.ConvertToHateoas(response, configuration, path);
         }
         return response.ToJsonMessage(settings, configuration.Indented);
     }
     catch (Exception ex)
     {
         if (ex is TargetInvocationException)
         {
             return ex.InnerException.Message.ToJsonMessage();
         }
         else
         {
             return ex.Message.ToJsonMessage();
         }
     }
 }
示例#10
0
        public async Task ProcessSingleMessageFailTest()
        {
            var messageDetails = new MessageInformation
            {
                Body      = Encoding.UTF8.GetBytes(GetMessageBody()),
                LockToken = Guid.NewGuid().ToString(),
                SessionId = "dc04c21f-091a-44a9-a661-9211dd9ccf35",
                MessageId = Guid.NewGuid().ToString()
            };

            var output = new GroupMembershipMessageResponse
            {
                CompletedGroupMembershipMessages = new List <GroupMembershipMessage>
                {
                    new GroupMembershipMessage {
                        LockToken = messageDetails.LockToken
                    }
                },
                ShouldCompleteMessage = true
            };

            var status = new DurableOrchestrationStatus
            {
                RuntimeStatus = OrchestrationRuntimeStatus.Running,
                Output        = JToken.FromObject(output)
            };

            _durableClientMock
            .Setup(x => x.StartNewAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <GraphUpdaterFunctionRequest>()))
            .ReturnsAsync(_instanceId);

            var attempt = 1;

            _durableClientMock
            .Setup(x => x.GetStatusAsync(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>()))
            .Callback(() =>
            {
                if (attempt > 1)
                {
                    status.RuntimeStatus = OrchestrationRuntimeStatus.Terminated;
                }

                attempt++;
            })
            .ReturnsAsync(status);

            _messageService.Setup(x => x.GetMessageProperties(It.IsAny <Message>())).Returns(messageDetails);

            var starterFunction = new StarterFunction(_loggerMock, _messageService.Object, _configuration.Object);
            await starterFunction.RunAsync(new Message(), _durableClientMock.Object, _messageSessionMock.Object);

            _messageSessionMock.Verify(mock => mock.CompleteAsync(It.IsAny <IEnumerable <string> >()), Times.Never());
            _messageSessionMock.Verify(mock => mock.CloseAsync(), Times.Never());

            Assert.IsNotNull(_loggerMock.MessagesLogged.Single(x => x.Message.Contains("Error: Status of instance")));
            Assert.IsNotNull(_loggerMock.MessagesLogged.Single(x => x.Message.Contains("function complete")));
        }
示例#11
0
        public ActionResult <string> Decipher(MessageInformation messageInformation)
        {
            List <Models_Server.Crypto> settings = this.cryptoDAO.SelectDailySettings(messageInformation.DayOfYear, messageInformation.Hour);

            this.cryptoLogic.SetRotors(settings[0].Rotors, settings[0].BetaOrGamma, settings[0].StartingPosition);

            string degroupedMessage  = messageInformation.Message.ToUpper().RemoveSpaces();
            string decipheredMessage = cryptoLogic.Encrypt(degroupedMessage).FormatPunctuation(true);

            return(Ok(decipheredMessage));
        }
示例#12
0
    public void Send(RPCOption mode, MessageInformation message, bool reliable = true)
    {
        string outdata = "";

        System.Type t = message.value.GetType();
        //CODIFICA IN BASE AL TIPO DI INPUT
        if (t.Equals(typeof(string)))
        {
            outdata = "string:" + message.name + ":" + message.value;
        }
        else if (t.Equals(typeof(int)))
        {
            outdata = "int:" + message.name + ":" + message.value.ToString();
        }
        else if (t.Equals(typeof(float)))
        {
            outdata = "float:" + message.name + ":" + message.value.ToString();
        }
        else if (t.Equals(typeof(Vector2)))
        {
            outdata = "Vector2:" + message.name + ":" + ((Vector2)message.value).x + ":" + ((Vector2)message.value).y;
        }
        else if (t.Equals(typeof(Vector3)))
        {
            outdata = "Vector3:" + message.name + ":" + ((Vector3)message.value).x + ":" + ((Vector3)message.value).y + ":" + ((Vector3)message.value).z;
        }
        else if (t.Equals(typeof(bool)))
        {
            outdata = "bool:" + message.name + ":" + message.value.ToString();
        }
        else if (t.Equals(typeof(Texture2D)))
        {
            Texture2D te = ((Texture2D)message.value);
            outdata = "Texture2D:" + message.name + ":";
            byte[] pixelsdata = te.EncodeToJPG();
            outdata += System.Convert.ToBase64String(pixelsdata);
        }
        else
        {
            Debug.LogError("data type not supported");
            return;
        }

        byte[] dataBYTE = System.Text.ASCIIEncoding.Default.GetBytes(outdata);
        Debug.LogWarning("Sent data of " + dataBYTE.Length + "bytes");

        switch (mode)
        {
        case RPCOption.Everyone:
            MC.PgamePlatform_instance.RealTime.SendMessageToAll(reliable, dataBYTE);
            break;
        }
    }
示例#13
0
        private void btnAddBooking_Click(object sender, EventArgs e)
        {
            if (ValidateInputs())
            {
                if ((capacity - numberPassengers) >= Convert.ToInt16(txtNumberPassengers.Text))
                {
                    BookingModel bookingModel = new BookingModel();

                    try
                    {
                        bookingModel.InsertBooking(textBox7.Text, textBox8.Text, customerId, textBox1.Text);

                        string message = "Insert Successful !!!";
                        MessageInformation.Success(message);

                        clearSelecion();
                        clearFlightDetails();
                    }
                    catch (SqlException ex)
                    {
                        string message = $"Customer {personModel.FirstName} {personModel.LastName} was already booked.\n" +
                                         $"Flight {flightModel.FlightNumber}.\n" +
                                         $"Destination {flightModel.Destination}";
                        MessageInformation.Error(message);
                    }
                    catch (Exception ex)
                    {
                        string message = "Booking was not added !!!";
                        MessageInformation.Error(message);
                    }
                }
                else
                {
                    string message = $"Flight {textBox1.Text}\n\nIt has not capacity!!!";
                    MessageInformation.Error(message);
                }
            }
            else
            {
                string message = "";

                if (cmbSelectCustomer.SelectedValue == null)
                {
                    message += "- Please select a Customer\n\n";
                }
                else
                {
                    message += "- Please select a flight";
                }

                MessageInformation.Error(message);
            }
        }
示例#14
0
        private void StartGame_Click(object sender, RoutedEventArgs e)
        {
            switch (GameManager.IsUserSelected)
            {
            case true:
                CollapseIrelevantUI();
                GameManager.StartGame();
                break;

            default:
                MessageInformation.CarSelectionMessage();
                break;
            }
        }
示例#15
0
        public void Init()
        {
            FakeClient.OnClientReceivedData += Proxy_FakeClient_OnClientReceivedData;
            Client.OnClientReceivedData     += Proxy_Client_OnClientReceivedData;

            FakeClient.OnClientDisconnected += Proxy_FakeClient_OnClientDisconnected;
            Client.OnClientDisconnected     += Proxy_Client_OnClientDisconnected;

            ClientMessageInformation = new MessageInformation(true);
            ServerMessageInformation = new MessageInformation(false);

            ClientMessageInformation.OnMessageParsed += ClientMessageInformation_OnMessageParsed;
            ServerMessageInformation.OnMessageParsed += ServerMessageInformation_OnMessageParsed;

            FakeClient.Connect(FakeClientRemoteIp);
        }
示例#16
0
        public void EndGame()
        {
            MovmentManager.StopTimers();

            switch (MessageInformation.WhenGameEnds())
            {
            case MessageBoxResult.Yes:
                RestartGame();
                break;

            case MessageBoxResult.No:
                MessageInformation.GoodByMessage();
                Application.Current.Shutdown();
                break;
            }
        }
        public void LogFailedMessage(IMessage message)
        {
            object handler;

            try
            {
                handler = _objectBuilder.GetInstance(_handlerType);
            }
            catch
            {
                handler = _handlerType;
            }

            object deserializedMessageBody;

            try
            {
                deserializedMessageBody = _serializer.Deserialize(_concreteMessageType, message.Body);
            }
            catch
            {
                deserializedMessageBody = null;
            }

            var messageInformation = new MessageInformation
            {
                UniqueIdentifier        = Guid.NewGuid(),
                Topic                   = _topic,
                Channel                 = _channel,
                HandlerType             = handler.GetType(),
                MessageType             = _messageType,
                Message                 = message,
                DeserializedMessageBody = deserializedMessageBody,
                Started                 = DateTime.UtcNow
            };

            _messageAuditor.TryOnFailed(_logger, _bus,
                                        new FailedMessageInformation
                                        (
                                            messageInformation,
                                            FailedMessageQueueAction.Finish,
                                            FailedMessageReason.MaxAttemptsExceeded,
                                            null
                                        )
                                        );
        }
示例#18
0
        private bool ValidateInputs()
        {
            bool validate = true;

            if (!Validation.IsEmpty(txtFlightNumber))
            {
                validate = false;
            }
            if (!Validation.IsInteger(txtMaxNumberSeats))
            {
                validate = false;
            }
            if (!Validation.IsEmpty(txtPortOrigin))
            {
                validate = false;
            }
            if (!Validation.IsString(txtDestinationPort))
            {
                validate = false;
            }
            if (!Validation.IsDouble(txtPrice))
            {
                validate = false;
            }
            if (!Validation.IsDateTime(txtFlightDate))
            {
                validate = false;
            }
            if (!Validation.IsTime(txtFlightTime))
            {
                validate = false;
            }
            if (!Validation.IsTimeSpan(txtDuration))
            {
                validate = false;
            }

            if (!validate)
            {
                string message = "It is not allowed empty values or values are invalided !!!";
                MessageInformation.Error(message);
            }

            return(validate);
        }
示例#19
0
        private void btnCancelBooking_Click(object sender, EventArgs e)
        {
            string message = $"Flight number: {flightModel.FlightNumber} \n" +
                             $"From {flightModel.Origin} to {flightModel.Destination}\n" +
                             $"Customer: {personModel.FirstName} {personModel.LastName}\n\n" +
                             $"Do you want to cancel this order";

            MessageBoxResult result = MessageBox.Show(message, $"Cancel Booking Order: {bookingModel.Id}", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (result == MessageBoxResult.Yes)
            {
                bookingModel.CancelBooking(bookingModel.Id.ToString());
                string temp = "-" + textBox7.Text;
                message = "Booking was Successful Canceled!!!";
                MessageInformation.Success(message);
            }

            Close();
        }
        private void SaveIncomingMessage(MessageInformation message)
        {
            try
            {
                // Set this to blank to save database space
                message.RawMessage = string.Empty;
                message.DataBytes  = null;

                IncomingMessage msg = new IncomingMessage()
                {
                    MsgContent = EntityHelper.ToCommonRepresentation <MessageInformation>(message)
                };
                database.IncomingMesages.Add(msg);
                database.SaveChanges();
            }
            catch (Exception ex)
            {
                logger.Error("Failed to save message", ex);
            }
        }
示例#21
0
        public ActionResult <string> Cipher(MessageInformation messageInformation)
        {
            if (!IsEnciphered(messageInformation.Message))
            {
                List <Models_Server.Crypto> settings = this.cryptoDAO.SelectDailySettings(messageInformation.DayOfYear, messageInformation.Hour);

                this.cryptoLogic.SetRotors(settings[0].Rotors, settings[0].BetaOrGamma, settings[0].StartingPosition);

                return($"{messageInformation.DayOfYear}:{messageInformation.Hour} {Encipher(messageInformation.Message)}");
            }
            else
            {
                List <string> split = messageInformation.Message.Substring(0, messageInformation.Message.IndexOf(" ")).Split(":").ToList();

                List <Models_Server.Crypto> settings = this.cryptoDAO.SelectDailySettings(int.Parse(split[0]), int.Parse(split[1]));

                this.cryptoLogic.SetRotors(settings[0].Rotors, settings[0].BetaOrGamma, settings[0].StartingPosition);

                return(Decipher(messageInformation.Message));
            }
        }
示例#22
0
        /// <summary>
        /// 修改调度配置
        /// </summary>
        /// <param name="config">配置</param>
        /// <returns>保存结果</returns>
        public static MessageInformation SaveChanges(RuleConfig config)
        {
            var messageInformation = new MessageInformation();

            try {
                config.UniqueCode = Utils.Guid;
                var data = DapperDbContext.GetConnection.QueryFirstOrDefault <RuleConfig>(
                    "Select * from RuleConfig r where (r.jobName = :JobName or triggername = :TriggerName or servicename= :ServiceName) and r.Id <> :Id",
                    config);
                if (data != null)
                {
                    throw new ValidationException("JobName,TriggerName,MethodName必须唯一");
                }
                string sql = @"Update RuleConfig
                               set Cron             = :Cron,
                                   Description      = :Description,
                                   TriggerName      = :TriggerName,
                                   JobName          = :JobName,
                                   Method           = :Method,
                                   PostBody         = :PostBody,
                                   ServiceName      = :ServiceName,
                                   Author           = :Author,
                                   ContentType      = :ContentType,
                                   IsAuthentication = :IsAuthentication,
                                   UserName         = :UserName,
                                   Password         = :Password,
                                   GroupName        = :GroupName,
                                   Address          = :Address,
                                   Status           = :Status,
                                   IsWebService     = :IsWebService,
                                   UniqueCode       = :UniqueCode,
                                   RunStatus        = :RunStatus
                             where Id = :Id ";
                DapperDbContext.Execute(sql, config);
                messageInformation.ExecuteSuccess("数据更新成功");
            } catch (Exception e) {
                messageInformation.ExecuteError(e);
            }
            return(messageInformation);
        }
示例#23
0
        public Message Delete(Message message)
        {
            MessageInformation information = new MessageInformation(message);
            try
            {
                string sessionToken = this.GetSessionToken(information);
                MessagePath path = new MessagePath(information);
                if (!path.HasKeyParameter)
                {
                    throw new ArgumentException("DELETE operation must have a key parameter in the path.");
                }
                ISecurityManager securityManager = IoC.Get<ISecurityManager>();
                dynamic bo = securityManager.DynamicGetBO(path.DtoType, sessionToken);
                object response = bo.Delete(path.KeyParameter);
                return response.ToJsonMessage();

            }
            catch (Exception ex)
            {
                return ex.Message.ToJsonMessage();
            }
        }
示例#24
0
 private void btnSave_Click(object sender, EventArgs e)
 {
     if (ValidateInputs())
     {
         try
         {
             flight.EditFlight(txtFlightNumber.Text,
                               txtPortOrigin.Text,
                               txtDestinationPort.Text,
                               txtMaxNumberSeats.Text,
                               txtPrice.Text,
                               txtFlightDate.Text,
                               txtFlightTime.Text,
                               txtDuration.Text);
             Close();
         }
         catch (Exception ex)
         {
             MessageInformation.Error(ex.ToString());
         }
     }
 }
        private void SetSessionTracker(MessageInformation messageDetails, GroupMembership groupMembership)
        {
            if (_sessionsTracker.ContainsKey(messageDetails.SessionId))
            {
                var sessionTracker = _sessionsTracker[messageDetails.SessionId];
                var lockTokens     = sessionTracker.LockTokens;

                lockTokens.Add(messageDetails.LockToken);
                _sessionsTracker.TryUpdate(messageDetails.SessionId,
                                           new SessionTracker
                {
                    LastAccessTime      = DateTime.UtcNow,
                    LatestMessageId     = messageDetails.MessageId,
                    RunId               = groupMembership.RunId,
                    LockTokens          = lockTokens,
                    JobPartitionKey     = groupMembership.SyncJobPartitionKey,
                    JobRowKey           = groupMembership.SyncJobRowKey,
                    ReceivedLastMessage = groupMembership.IsLastMessage
                },
                                           sessionTracker
                                           );
            }
            else
            {
                _sessionsTracker.TryAdd(messageDetails.SessionId,
                                        new SessionTracker
                {
                    LastAccessTime  = DateTime.UtcNow,
                    LatestMessageId = messageDetails.MessageId,
                    RunId           = groupMembership.RunId,
                    LockTokens      = new List <string> {
                        messageDetails.LockToken
                    },
                    JobPartitionKey     = groupMembership.SyncJobPartitionKey,
                    JobRowKey           = groupMembership.SyncJobRowKey,
                    ReceivedLastMessage = groupMembership.IsLastMessage
                });
            }
        }
示例#26
0
        private bool ValidateInputs()
        {
            bool validate = true;

            if (cmbSelectCustomer.SelectedValue == null)
            {
                validate = false;
            }
            if (!Validation.IsEmpty(textBox1))
            {
                validate = false;
            }
            if (!Validation.IsEmpty(textBox2))
            {
                validate = false;
            }
            if (!Validation.IsEmpty(textBox3))
            {
                validate = false;
            }
            if (!Validation.IsEmpty(textBox4))
            {
                validate = false;
            }
            if (!Validation.IsEmpty(textBox5))
            {
                validate = false;
            }


            if (!validate)
            {
                string message = "It is not allowed empty values or values are invalided !!!";
                MessageInformation.Error(message);
            }

            return(validate);
        }
示例#27
0
        private bool ValidateInputs()
        {
            bool validate = true;

            if (!Validation.IsString(txtFirstName))
            {
                validate = false;
            }
            if (!Validation.IsString(txtLastName))
            {
                validate = false;
            }
            if (!Validation.IsValidEmail(txtEmail))
            {
                validate = false;
            }
            if (!Validation.IsValidPhone(txtPhone))
            {
                validate = false;
            }
            if (!Validation.IsString(txtCity))
            {
                validate = false;
            }
            if (!Validation.IsString(txtProvince))
            {
                validate = false;
            }

            if (!validate)
            {
                string message = "It is not allowed empty values or values are invalided !!!";
                MessageInformation.Error(message);
            }

            return(validate);
        }
        /// <summary>
        /// Does the work.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void DoWork(object sender, ElapsedEventArgs e)
        {
            bool isDataConnectionAvailable = false;

            try
            {
                // Disable and wait until finish execution
                this.timer.Enabled = false;

                messenger = messengerService.Messenger;
                if (messenger == null)
                {
                    return;
                }

                if (logger.IsInfoEnabled)
                {
                    logger.Info("Checking unprocessed message");
                }

                // Get unprocessed messages
                List <IncomingMessage> unProcessedMsgs = database.IncomingMesages.Where(msg => msg.Status == IncomingMessage.ProcessingStatus.NotProcessed).ToList <IncomingMessage>();
                if (unProcessedMsgs.Count > 0)
                {
                    logger.Info("Processing " + unProcessedMsgs.Count + " messages");
                    foreach (IncomingMessage msg in unProcessedMsgs)
                    {
                        MessageInformation msgInfo = EntityHelper.FromCommonRepresentation <MessageInformation>(msg.MsgContent);
                        logger.Info("Processing message from " + msgInfo.PhoneNumber);

                        // Check for matching employee

                        string   employeeID = msgInfo.Content;
                        Employee employee   = database.Employees.Find(employeeID);
                        Gateway  gateway    = database.Gateways.Find(GlobalConstants.DefaultGatewayID);
                        if (employee != null && gateway != null)
                        {
                            if (messenger.InitializeDataConnection())
                            {
                                isDataConnectionAvailable = true;

                                // Send MMS
                                Mms mms = Mms.NewInstance(employee.EmployeeName, gateway.GatewayPhoneNumber);

                                // Multipart mixed
                                mms.MultipartRelatedType = MultimediaMessageConstants.ContentTypeApplicationMultipartMixed;
                                mms.PresentationId       = "<0000>";
                                mms.TransactionId        = EntityHelper.GenerateGuid();
                                mms.AddToAddress(msgInfo.PhoneNumber, MmsAddressType.PhoneNumber);

                                MultimediaMessageContent multimediaMessageContent = new MultimediaMessageContent();
                                multimediaMessageContent.SetContent(employee.EmployeePhoto, 0, employee.EmployeePhoto.Length);
                                multimediaMessageContent.ContentId = EntityHelper.GenerateGuid();
                                multimediaMessageContent.Type      = employee.PhotoImageType;
                                mms.AddContent(multimediaMessageContent);
                                if (messenger.Send(mms))
                                {
                                    msg.Status = IncomingMessage.ProcessingStatus.Processed;
                                }
                                else
                                {
                                    msg.Status   = IncomingMessage.ProcessingStatus.Error;
                                    msg.ErrorMsg = messenger.LastError.Message;
                                }
                                database.SaveChanges();
                            }
                            else
                            {
                                logger.Error("Unable to establish a data connection through the modem. Check if you modem support MMS");
                                if (messenger.LastError != null)
                                {
                                    logger.Error(messenger.LastError.ToString());
                                }
                            }
                        }
                        else
                        {
                            // Employee not found
                            msg.Status   = IncomingMessage.ProcessingStatus.Error;
                            msg.ErrorMsg = "Employee not found";
                            database.SaveChanges();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error polling messages", ex);
            }
            finally
            {
                if (isDataConnectionAvailable)
                {
                    messengerService.StartMessenger();
                }
                this.timer.Enabled = true;
            }
        }
示例#29
0
        /// <summary>
        /// 新增调度配置
        /// </summary>
        /// <param name="config">配置</param>
        /// <returns>保存结果</returns>
        public static MessageInformation InsertRule(RuleConfig config)
        {
            var messageInformation = new MessageInformation();

            try {
                config.UniqueCode = Utils.Guid;
                bool isValid =
                    DapperDbContext.GetConnection.QueryFirstOrDefault <RuleConfig>(
                        "Select * from RuleConfig r where r.jobName = :JobName or triggername = :TriggerName or servicename= :ServiceName",
                        config) == null;
                if (!isValid)
                {
                    throw new ValidationException("JobName,TriggerName,MethodName必须唯一");
                }
                string sql = @"insert into RuleConfig
                              (id,
                               cron,
                               description,
                               triggername,
                               jobname,
                               method,
                               postbody,
                               servicename,
                               author,
                               contenttype,
                               isauthentication,
                               username,
                               password,
                               groupname,
                               address,
                               status,
                               isWebService,
                               uniqueCode,
                               runStatus)
                            values
                              (s_RuleConfig.Nextval,
                               :Cron,
                               :Description,
                               :TriggerName,
                               :JobName,
                               :Method,
                               :PostBody,
                               :ServiceName,
                               :Author,
                               :ContentType,
                               :IsAuthentication,
                               :UserName,
                               :Password,
                               :GroupName,
                               :Address,
                               :Status,
                               :IsWebService,
                               :UniqueCode,
                               :RunStatus)";
                DapperDbContext.Execute(sql, config);
                messageInformation.ExecuteSuccess("数据插入成功");
            } catch (Exception e) {
                messageInformation.ExecuteError(e);
            }
            return(messageInformation);
        }
        /// <summary>
        /// Saves the message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="gatewayId">The gateway id.</param>
        /// <returns></returns>
        private bool SaveIncomingMessage(MessageInformation message)
        {
            bool isSuccessful = true;
            try
            {
                IncomingMessage incomingMessage = new IncomingMessage();
                incomingMessage.Id = GatewayHelper.GenerateUniqueIdentifier();
                incomingMessage.GatewayId = message.GatewayId;
                incomingMessage.Originator = message.PhoneNumber;
                incomingMessage.OriginatorReceivedDate = message.DestinationReceivedDate;
                incomingMessage.Timezone = message.Timezone;
                incomingMessage.Message = message.Content;
                incomingMessage.MessageType = StringEnum.GetStringValue(message.MessageType);
                incomingMessage.DeliveryStatus = message.DeliveryStatus.ToString();
                incomingMessage.ReceivedDate = message.ReceivedDate;
                incomingMessage.ValidityTimeStamp = message.ValidityTimestamp;
                incomingMessage.OriginatorRefNo = message.ReferenceNo;
                incomingMessage.MessageStatusType = message.MessageStatusType.ToString();
                incomingMessage.SrcPort = message.SourcePort;
                incomingMessage.DestPort = message.DestinationPort;
                incomingMessage.Status = StringEnum.GetStringValue(MessageStatus.Received);
                incomingMessage.RawMessage = message.RawMessage;
                incomingMessage.LastUpdate = DateTime.Now;
                incomingMessage.CreateDate = incomingMessage.LastUpdate;
                incomingMessage.Indexes = string.Join(",", (message.Indexes.ConvertAll<string>(delegate(int i) { return i.ToString(); })).ToArray());
                incomingMessage.Save();
            }
            catch (Exception ex)
            {
                log.Error("Failed to save message");
                log.Error(ex.Message, ex);
                isSuccessful = false;
            }

            return isSuccessful;
        }
        public void HandleMessage(IMessage message)
        {
            var messageInformation = new MessageInformation
            {
                UniqueIdentifier        = Guid.NewGuid(),
                Topic                   = _topic,
                Channel                 = _channel,
                HandlerType             = _handlerType,
                MessageType             = _messageType,
                Message                 = message,
                DeserializedMessageBody = null,
                Started                 = DateTime.UtcNow
            };

            _bus.SetCurrentMessageInformation(messageInformation);

            // Get handler
            object handler;

            try
            {
                handler = _objectBuilder.GetInstance(_handlerType);
                messageInformation.HandlerType = handler.GetType();
            }
            catch (Exception ex)
            {
                messageInformation.Finished = DateTime.UtcNow;

                _messageAuditor.TryOnFailed(_logger, _bus,
                                            new FailedMessageInformation
                                            (
                                                messageInformation,
                                                FailedMessageQueueAction.Finish,
                                                FailedMessageReason.HandlerConstructor,
                                                ex
                                            )
                                            );

                message.Finish();
                return;
            }

            // Get deserialized value
            object value;

            try
            {
                value = _serializer.Deserialize(_concreteMessageType, message.Body);
            }
            catch (Exception ex)
            {
                messageInformation.Finished = DateTime.UtcNow;

                _messageAuditor.TryOnFailed(_logger, _bus,
                                            new FailedMessageInformation
                                            (
                                                messageInformation,
                                                FailedMessageQueueAction.Finish,
                                                FailedMessageReason.MessageDeserialization,
                                                ex
                                            )
                                            );

                message.Finish();
                return;
            }

            // Handle message
            messageInformation.DeserializedMessageBody = value;
            _messageAuditor.TryOnReceived(_logger, _bus, messageInformation);

            try
            {
                _handleMethod.Invoke(handler, new[] { value });
            }
            catch (Exception ex)
            {
                bool requeue = (message.Attempts < message.MaxAttempts);

                messageInformation.Finished = DateTime.UtcNow;

                if (requeue)
                {
                    message.Requeue();
                }
                else
                {
                    message.Finish();
                }

                _messageAuditor.TryOnFailed(_logger, _bus,
                                            new FailedMessageInformation
                                            (
                                                messageInformation,
                                                requeue ? FailedMessageQueueAction.Requeue : FailedMessageQueueAction.Finish,
                                                requeue ? FailedMessageReason.HandlerException : FailedMessageReason.MaxAttemptsExceeded,
                                                ex
                                            )
                                            );

                return;
            }

            messageInformation.Finished = DateTime.UtcNow;

            _messageAuditor.TryOnSucceeded(_logger, _bus, messageInformation);
        }
示例#32
0
文件: MetaMod.cs 项目: txdv/sharpmod
		internal static void MessageBeginPost(MessageDestination destination, int messageType, IntPtr floatValue, IntPtr playerEntity)
		{
			if (firstMessage) {
				// there is no event which intercepts between
				// the registering part and the first message (weaponlist in cstrike case)
				// so we need to initialize the game mode before the first message so we can
				// intercept this valuable information
				switch (Server.GameDirectory) {
				case "cstrike":
					CounterStrike.CounterStrike.Init();
					break;
				}
				firstMessage = false;
			}

			#if DEBUG
			messageInformation = new MessageInformation(destination, messageType, floatValue, playerEntity);
			messageInformation.CallTimeBegin = DateTime.Now;
			#endif

			message_header = new MessageHeader(destination, messageType, floatValue, playerEntity);
			message_elements = new List<object>();

			MetaModEngine.SetResult(MetaResult.Handled);
			}
示例#33
0
 /// <summary>
 /// Gets the session token.
 /// </summary>
 /// <param name="information">The information.</param>
 /// <returns></returns>
 /// <exception cref="System.ArgumentNullException">A session token must be provided</exception>
 private string GetSessionToken(MessageInformation information)
 {
     if (!information.LowParameters.ContainsKey("sessiontoken"))
     {
         throw new ArgumentNullException("A session token must be provided");
     }
     return information.LowParameters["sessiontoken"];
 }
示例#34
0
        public async Task ProcessSessionWithLastMessageTest()
        {
            var messageCount          = 5;
            var messages              = new List <MessageInformation>();
            var messageResponses      = new List <GroupMembershipMessageResponse>();
            var orchestrationStatuses = new List <DurableOrchestrationStatus>();

            for (int i = 0; i < messageCount; i++)
            {
                // Generate sample messages
                var isLastMessage   = messageCount - 1 == i;
                var groupMembership = JsonConvert.DeserializeObject <GroupMembership>(GetMessageBody());

                groupMembership.IsLastMessage = isLastMessage;

                var messageDetails = new MessageInformation
                {
                    Body      = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(groupMembership)),
                    LockToken = Guid.NewGuid().ToString(),
                    SessionId = "dc04c21f-091a-44a9-a661-9211dd9ccf35"
                };

                messages.Add(messageDetails);

                // Generate sample membership message responses
                var output = new GroupMembershipMessageResponse
                {
                    CompletedGroupMembershipMessages = new List <GroupMembershipMessage>
                    {
                        new GroupMembershipMessage {
                            LockToken = messageDetails.LockToken
                        }
                    },
                    ShouldCompleteMessage = isLastMessage
                };

                messageResponses.Add(output);

                // Generate sample orchestration statuses
                orchestrationStatuses.Add
                (
                    new DurableOrchestrationStatus
                {
                    RuntimeStatus = OrchestrationRuntimeStatus.Completed,
                    Output        = JToken.FromObject(output)
                }
                );
            }

            var messageIndex = 0;

            _messageService.Setup(x => x.GetMessageProperties(It.IsAny <Message>()))
            .Returns(() =>
            {
                messages[messageIndex].MessageId = Guid.NewGuid().ToString();
                var message = messages[messageIndex];
                messageIndex++;
                return(message);
            });

            var messageSessionIndex = 0;

            _messageSessionMock.SetupGet(x => x.SessionId).Returns(() =>
            {
                var sessionId = messages[messageSessionIndex].SessionId;
                messageSessionIndex++;
                return(sessionId);
            });

            _configuration.SetupGet(x => x["GraphUpdater:LastMessageWaitTimeout"]).Returns("1");

            var cancelationRequestCount = 0;

            _durableClientMock
            .Setup(x => x.StartNewAsync(It.IsAny <string>(), It.IsAny <GraphUpdaterFunctionRequest>()))
            .Callback <string, object>((name, request) =>
            {
                var graphUpdaterRequest = request as GraphUpdaterFunctionRequest;
                if (graphUpdaterRequest != null && graphUpdaterRequest.IsCancelationRequest)
                {
                    cancelationRequestCount++;
                }
            })
            .ReturnsAsync(_instanceId);

            var statusIndex = 0;

            _durableClientMock
            .Setup(x => x.GetStatusAsync(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>()))
            .ReturnsAsync(() =>
            {
                var status = orchestrationStatuses[statusIndex];
                statusIndex++;
                return(status);
            });

            var starterFunction = new StarterFunction(_loggerMock, _messageService.Object, _configuration.Object);

            for (int i = 0; i < messageCount; i++)
            {
                await starterFunction.RunAsync(new Message(), _durableClientMock.Object, _messageSessionMock.Object);
            }

            await Task.Delay(TimeSpan.FromSeconds(90));

            _durableClientMock.Verify(x => x.StartNewAsync(It.IsAny <string>(), It.IsAny <GraphUpdaterFunctionRequest>()), Times.Exactly(messageCount));
            Assert.AreEqual(0, cancelationRequestCount);
        }
示例#35
0
        public Message Post(Message message)
        {
            MessageInformation information = new MessageInformation(message);
            try
            {
                string sessionToken = this.GetSessionToken(information);
                MessagePath path = new MessagePath(information);
                ISecurityManager securityManager = IoC.Get<ISecurityManager>();
                IServiceConfiguration configuration = IoC.Get<IServiceConfiguration>();
                JsonSerializerSettings settings = IoC.Get<JsonSerializerSettings>();
                if (path.IsQuery)
                {
                    dynamic bo = securityManager.DynamicGetBO(path.DtoType, sessionToken);
                    QueryInfo info = information.GetBody<QueryInfo>();
                    info.AddFacetsFrom(path.QueryInfo);
                    object response;
                    if (path.HasKeyParameter)
                    {
                        response = bo.GetOne(string.Empty, info);
                    }
                    else
                    {
                        response = bo.GetAll(info);
                    }
                    if (configuration.IsHateoas)
                    {
                        response = this.ConvertToHateoas(response, configuration, path);
                    }
                    return response.ToJsonMessage(settings, configuration.Indented);
                }
                else
                {
                    if (path.HasKeyParameter)
                    {
                        throw new ArgumentException("POST operation cannot have a key parameter in the path.");
                    }
                    dynamic bo = securityManager.DynamicGetBO(path.DtoType, sessionToken);
                    dynamic dto = information.GetBody(path.DtoType);
                    object response = bo.Insert(dto);
                    if (configuration.IsHateoas)
                    {
                        response = ConvertToHateoas(response, configuration, path, true);
                    }
                    return response.ToJsonMessage();
                }

            }
            catch (Exception ex)
            {
                return ex.Message.ToJsonMessage();
            }
        }
示例#36
0
 public Message Put(Message message)
 {
     MessageInformation information = new MessageInformation(message);
     try
     {
         string sessionToken = this.GetSessionToken(information);
         MessagePath path = new MessagePath(information);
         if (path.HasKeyParameter)
         {
             throw new ArgumentException("POST operation cannot have a key parameter in the path.");
         }
         ISecurityManager securityManager = IoC.Get<ISecurityManager>();
         dynamic bo = securityManager.DynamicGetBO(path.DtoType, sessionToken);
         dynamic dto = information.GetBody(path.DtoType);
         object response = bo.Update(dto);
         IServiceConfiguration configuration = IoC.Get<IServiceConfiguration>();
         JsonSerializerSettings settings = IoC.Get<JsonSerializerSettings>();
         if (configuration.IsHateoas)
         {
             response = this.ConvertToHateoas(response, configuration, path);
         }
         return response.ToJsonMessage(settings, configuration.Indented);
     }
     catch (Exception ex)
     {
         return ex.Message.ToJsonMessage();
     }
 }
        public void ShowInformation(MessageInformation messageInformation)
        {
            var modal = new MessageModalViewModel(messageInformation);

            Modal = modal;
        }
示例#38
0
 public void ClearVariable(MessageInformation msg, string senderID)
 {
     //clear all the values of that variable
     Messages.Remove(new KeyValuePair <string, MessageInformation>(senderID, msg));
 }