Esempio n. 1
0
 static void Main()
 {
     var mess = new Message();
     Message errMess = new ErrorMessage();
     mess.Print();
     errMess.Print();
 }
Esempio n. 2
0
 public void TestSerialize()
 {
     const string type = "fatal";
     const string message = "error message";
     var error = new ErrorMessage{ Error = new ErrorMessage.ConctreteError { Type = type, Message = message } };
     string json = Serializer.Serialize(error);
     const string expectedJson = "{\"Error\":{\"Type\":\"fatal\",\"Message\":\"error message\"}}";
     Assert.AreEqual(expectedJson, json);
 }
 public void RevievingErrorMessage(ErrorMessage message)
 {
     _syncContext.Post(m =>
                           {
                               addToList(m);
                               if (MessageArrived != null)
                                   MessageArrived(this, new MessageRecievedEventArgs(MessageType.Error));
                           }, message.Error);
 }
Esempio n. 4
0
            /// <summary><para>Überladener Konstruktor mit einem Parameter für die Fehler-Nachricht.</para></summary>
            /// <param name="message">Ein Fehlertext.</param>
            internal GeoException(ErrorMessage message) : base(message.Text)
            {
#if COMPACT_FRAMEWORK
#else
                if (this.Data != null) this.Data["ExtraInfo"] = message.ID;
#endif

                _id = message.ID;
            }
Esempio n. 5
0
 public CompError(string fLine, int lNum, ErrorMessage cError, string eInfo1 = "", string eInfo2 = "")
 {
     lineNumber = lNum;
     characterNumber = 0;
     errorMessage = cError;
     extraInfo1 = eInfo1;
     extraInfo2 = eInfo2;
     fullLine = fLine;
 }
Esempio n. 6
0
 public void TestErrorProperty()
 {
     const string type = "fatal";
     const string message = "error message";
     var errorMessage = new ErrorMessage {Error = new ErrorMessage.ConctreteError { Type = type, Message = message }};
     Assert.NotNull(errorMessage.Error);
     Assert.AreEqual(type, errorMessage.Error.Type);
     Assert.AreEqual(message, errorMessage.Error.Message);
 }
 public void AddError(ErrorMessage e)
 {
     lock (errorLocker)
     {
         errors.Add(e);
         File.AppendAllLines(dumpFileLocation, new List<string> {
             String.Format("{0} : {1} :: {2}",e.when,e.category,e.message)
         }.Concat(describeException(e.exception)).Concat(new List<string> { "" }));
     }
 }
        public void Parse_NoShifts_ErrorLoggedWithEmptyResult()
        {
            ErrorLogger.ClearLog();
            var tokenList = ShiftsStatement.NoStatement.AsTokens();
            var parser = new ShiftsFactory(tokenList, task, date, interval, exceedingAllowed);

            var actualShifts = parser.Parse();
            var expectedErrorMessage = new ErrorMessage(new DanishMessageContentProvider().GetMessageNoStatementInShiftsField(task.Name, date));

            Assert.IsTrue(actualShifts.Count == 0
                && ErrorLogger.LoggedErrors.Count == 1
                && ErrorLogger.LoggedErrors.Contains(expectedErrorMessage));
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="rawMessage">'7::' [endpoint] ':' [reason] '+' [advice]</param>
 /// <returns>ErrorMessage</returns>
 public static ErrorMessage Deserialize(string rawMessage)
 {
     ErrorMessage errMsg = new ErrorMessage();
     string[] args = rawMessage.Split(':');
     if (args.Length == 4)
     {
         errMsg.Endpoint = args[2];
         errMsg.MessageText = args[3];
         string[] complex = args[3].Split(new char[] { '+' });
         if (complex.Length > 1)
         {
             errMsg.Advice = complex[1];
             errMsg.Reason = complex[0];
         }
     }
     return errMsg;
 }
        public string WriteToLog(ErrorMessage message)
        {
            string path = string.Empty;
            if (!String.IsNullOrEmpty(message.Message))
            {
                try
                {
                    path = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath + "/qblog.txt");
                }
                catch (Exception)
                {
                    path = "/qblog.txt";
                }
                FileStream fileStream = null;

                //If the file exists, then append it
                if (File.Exists(path))
                {
                    fileStream = new FileStream(path, FileMode.Append);
                }
                else
                {
                    fileStream = new FileStream(path, FileMode.OpenOrCreate);
                }
                StreamWriter sw = new StreamWriter(fileStream);
                try
                {
                    sw.WriteLine(String.Format("{0} : {1} {2} {3}", message.ApplicationName, message.Severity, DateTime.Now, message.Message));
                    return "OK";
                }
                //If there is an error, just do nothing. Don't stop.
                catch (Exception ex)
                {
                    return ex.ToString();
                }
                finally
                {
                    sw.Close();
                    fileStream.Close();
                }

            }

            return "Message is null or empty";
        }
Esempio n. 11
0
        public override void Handle(DhtEngine engine, Node node)
        {
            base.Handle(engine, node);

            if (!engine.Torrents.ContainsKey(InfoHash))
                engine.Torrents.Add(InfoHash, new List<Node>());

            Message response;
            if (engine.TokenManager.VerifyToken(node, Token))
            {
                engine.Torrents[InfoHash].Add(node);
                response = new AnnouncePeerResponse(engine.RoutingTable.LocalNode.Id, TransactionId);
            }
            else
                response = new ErrorMessage(ErrorCode.ProtocolError, "Invalid or expired token received");

            engine.MessageLoop.EnqueueSend(response, node.EndPoint);
        }
        public static UdpTrackerMessage DecodeMessage(byte[] buffer, int offset, int count, MessageType type)
        {
            UdpTrackerMessage m = null;
            var action = type == MessageType.Request ? ReadInt(buffer, offset + 8) : ReadInt(buffer, offset);
            switch (action)
            {
                case 0:
                    if (type == MessageType.Request)
                        m = new ConnectMessage();
                    else
                        m = new ConnectResponseMessage();
                    break;
                case 1:
                    if (type == MessageType.Request)
                        m = new AnnounceMessage();
                    else
                        m = new AnnounceResponseMessage();
                    break;
                case 2:
                    if (type == MessageType.Request)
                        m = new ScrapeMessage();
                    else
                        m = new ScrapeResponseMessage();
                    break;
                case 3:
                    m = new ErrorMessage();
                    break;
                default:
                    throw new ProtocolException(string.Format("Invalid udp message received: {0}", buffer[offset]));
            }

            try
            {
                m.Decode(buffer, offset, count);
            }
            catch
            {
                m = new ErrorMessage(0, "Couldn't decode the tracker response");
            }
            return m;
        }
        /// <summary>
        /// Update an existing ErrorMessage
        /// </summary>
        /// <param name="entity"></param>
        public void Update(ErrorMessage entity)
        {
            var set = _entityContext.Set<ErrorMessage>();
            var entry = set.Local.SingleOrDefault(f => f.Id == entity.Id);

            if (entry != null)
            {
                var attachedFeature = _entityContext.Entry(entry);
                attachedFeature.CurrentValues.SetValues(entity);
                attachedFeature.State = EntityState.Modified;
            }
            else
            {
                _entityContext.ErrorMessages.Attach(entity);
                _entityContext.Entry(entity).State = EntityState.Modified;
            }
        }
        public Tuple <bool, List <object> > UploadValidate(List <GarmentCurrencyViewModel> Data, List <KeyValuePair <string, StringValues> > Body)
        {
            const string DATE_KEYWORD = "date";

            DateTime Date;
            string   DateString = Body.SingleOrDefault(s => s.Key.Equals(DATE_KEYWORD)).Value;
            bool     ValidDate  = DateTime.TryParseExact(DateString, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out Date);

            List <object> ErrorList = new List <object>();
            string        ErrorMessage;
            bool          Valid = true;

            foreach (GarmentCurrencyViewModel garmentCurrencyVM in Data)
            {
                ErrorMessage = "";

                if (string.IsNullOrWhiteSpace(garmentCurrencyVM.code))
                {
                    ErrorMessage = string.Concat(ErrorMessage, "Mata Uang tidak boleh kosong, ");
                }

                double Rate = 0;
                if (string.IsNullOrWhiteSpace(garmentCurrencyVM.rate))
                {
                    ErrorMessage = string.Concat(ErrorMessage, "Kurs tidak boleh kosong, ");
                }
                else if (!double.TryParse(garmentCurrencyVM.rate, out Rate))
                {
                    ErrorMessage = string.Concat(ErrorMessage, "Kurs harus numerik, ");
                }
                else if (Rate < 0)
                {
                    ErrorMessage = string.Concat(ErrorMessage, "Kurs harus lebih besar dari 0, ");
                }
                else
                {
                    string[] RateSplit = garmentCurrencyVM.rate.Split('.');
                    if (RateSplit.Count().Equals(2) && RateSplit[1].Length > 4)
                    {
                        ErrorMessage = string.Concat(ErrorMessage, "Kurs maksimal memiliki 4 digit dibelakang koma, ");
                    }
                }

                if (!ValidDate)
                {
                    ErrorMessage = string.Concat(ErrorMessage, "Tanggal tidak boleh kosong, ");
                }
                else if (Date > DateTime.Now)
                {
                    ErrorMessage = string.Concat(ErrorMessage, "Tanggal tidak boleh lebih dari tanggal hari ini, ");
                }

                if (string.IsNullOrEmpty(ErrorMessage))
                {
                    /* Service Validation */
                    if (!this.DbContext.Set <Currency>().Any(d => d._IsDeleted.Equals(false) && d.Code.Equals(garmentCurrencyVM.code)))
                    {
                        ErrorMessage = string.Concat(ErrorMessage, "Mata Uang tidak terdaftar dalam master Mata Uang, ");
                    }

                    if (Data.Any(d => d != garmentCurrencyVM && d.code.Equals(garmentCurrencyVM.code) && d.date.Equals(garmentCurrencyVM.date)) || this.DbSet.Any(d => d._IsDeleted.Equals(false) && d.Code.Equals(garmentCurrencyVM.code) && d.Date.Equals(Date)))
                    {
                        ErrorMessage = string.Concat(ErrorMessage, "Mata Uang dan Tanggal tidak boleh duplikat, ");
                    }
                }

                if (string.IsNullOrEmpty(ErrorMessage))
                {
                    garmentCurrencyVM.rate = Rate;
                    garmentCurrencyVM.date = Date.ToUniversalTime();
                }
                else
                {
                    ErrorMessage = ErrorMessage.Remove(ErrorMessage.Length - 2);
                    var Error = new ExpandoObject() as IDictionary <string, object>;

                    Error.Add("Mata Uang", garmentCurrencyVM.code);
                    Error.Add("Kurs", garmentCurrencyVM.rate);
                    Error.Add("Error", ErrorMessage);

                    ErrorList.Add(Error);
                }
            }

            if (ErrorList.Count > 0)
            {
                Valid = false;
            }

            return(Tuple.Create(Valid, ErrorList));
        }
 /// <summary>
 /// Add a new ErrorMessage to the data store
 /// </summary>
 /// <param name="entity"></param>
 public void Save(ErrorMessage entity)
 {
     _entityContext.ErrorMessages.Add(entity);
 }
Esempio n. 16
0
        // Token: 0x06002B9E RID: 11166 RVA: 0x001043C0 File Offset: 0x001025C0
        public static void ShowRotationControlsHint()
        {
            string format = Language.main.GetFormat <string, string>("GhostRotateInputHint", uGUI.FormatButton(Builder.buttonRotateCW, true, ", "), uGUI.FormatButton(Builder.buttonRotateCCW, true, ", "));

            ErrorMessage.AddError(format);
        }
Esempio n. 17
0
        /// <summary>
        /// 发送模板消息
        /// </summary>
        /// <param name="userName">公众号</param>
        /// <param name="touser">接收消息的账号</param>
        /// <param name="templateId">模板id</param>
        /// <param name="detailUrl">详情地址</param>
        /// <param name="topColor">顶端颜色</param>
        /// <param name="data">数据</param>
        /// <param name="errorMessage">返回发送是否成功</param>
        /// <returns>返回消息id;如果发送失败,返回-1。</returns>
        public static long Send(string userName, string touser, string templateId, string detailUrl, Color topColor,
                                Tuple <string, string, Color>[] data, out ErrorMessage errorMessage)
        {
            errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "");
            long id = -1;

            //校验参数
            if (string.IsNullOrWhiteSpace(touser))
            {
                errorMessage.errmsg = "接收消息的账号不能为空。";
                return(id);
            }
            if (string.IsNullOrWhiteSpace(templateId))
            {
                errorMessage.errmsg = "模板id不能为空。";
                return(id);
            }
            if (data == null || data.Length == 0)
            {
                errorMessage.errmsg = "模板数据不能为空。";
                return(id);
            }
            foreach (Tuple <string, string, Color> item in data)
            {
                if (string.IsNullOrWhiteSpace(item.Item1) || string.IsNullOrWhiteSpace(item.Item2))
                {
                    errorMessage.errmsg = "模板数据不能为空。";
                    return(id);
                }
            }
            //获取许可令牌
            AccessToken token = AccessToken.Get(userName);

            if (token == null)
            {
                errorMessage.errmsg = "获取许可令牌失败。";
                return(id);
            }
            string url = string.Format(urlForSending, token.access_token);
            //生成待发送的数据
            dynamic postData = new ExpandoObject();

            postData.touser      = touser;
            postData.template_id = templateId;
            postData.url         = detailUrl ?? string.Empty;
            postData.topcolor    = Utility.GetColorString(topColor);
            postData.data        = new ExpandoObject();
            IDictionary <string, object> dataDict = (IDictionary <string, object>)postData.data;

            foreach (Tuple <string, string, Color> item in data)
            {
                dataDict.Add(item.Item1, new { value = item.Item2, color = Utility.GetColorString(item.Item3) });
            }
            string json = JsonConvert.SerializeObject(postData);
            //发送数据
            string responseContent;

            if (!HttpHelper.Request(url, out responseContent, httpMethod, json))
            {
                errorMessage.errmsg = "提交数据到微信服务器失败。";
                return(id);
            }
            //解析结果
            JObject jo = JObject.Parse(responseContent);
            JToken  jt;

            if (jo.TryGetValue("errcode", out jt) && jo.TryGetValue("errmsg", out jt))
            {
                errorMessage.errcode = (int)jo["errcode"];
                errorMessage.errmsg  = (string)jo["errmsg"];
                if (jo.TryGetValue("msgid", out jt))
                {
                    id = (long)jt;
                }
            }
            else
            {
                errorMessage.errmsg = "解析返回结果失败。";
            }
            return(id);
        }
Esempio n. 18
0
 public void Error(Message message, ErrorMessage errorMessage)
 {
     throw new NotImplementedException();
 }
Esempio n. 19
0
 public void Destroy()
 {
     ErrorMessage.AddMessage($"{PlayerName} left the game.");
     Object.DestroyImmediate(Body);
 }
Esempio n. 20
0
        public ProcVarsOnlyOneOutOfRangeForm(INumericFormat iNumericFormat, IProcessVarOwner solvable, ErrorMessage error)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            this.Text     = error.Title;
            this.solvable = solvable;

            // display the message
            this.labelMessage.Text = error.Message;

            this.var = (ProcessVar)error.ProcessVarsAndValues.ProcessVarList[0];

            // dispaly the variable
            this.labelProcVarName.InitializeVariable(var);
            this.labelProcVarName.BorderStyle = BorderStyle.None;
            this.textBoxExistingValue.InitializeVariable(iNumericFormat, var);

            string averageValStr = "";
            object minMaxValues  = error.ProcessVarsAndValues.GetVarRange(var);

            // note: the min and max values are not converted to the current unit system,
            //       and they also needs formating
            if (var is ProcessVarDouble)
            {
                DoubleRange doubleRange = (DoubleRange)minMaxValues;

                double valMin  = doubleRange.MinValue;
                double val2Min = 0.0;
                val2Min = UnitSystemService.GetInstance().ConvertFromSIValue(var.Type, valMin);
                if (val2Min == Constants.NO_VALUE)
                {
                    this.textBoxMinValue.Text = "";
                }
                else
                {
                    this.textBoxMinValue.Text = val2Min.ToString(iNumericFormat.NumericFormatString);
                }

                double valMax  = doubleRange.MaxValue;
                double val2Max = 0.0;
                val2Max = UnitSystemService.GetInstance().ConvertFromSIValue(var.Type, valMax);
                if (val2Max == Constants.NO_VALUE)
                {
                    this.textBoxMaxValue.Text = "";
                }
                else
                {
                    this.textBoxMaxValue.Text = val2Max.ToString(iNumericFormat.NumericFormatString);
                }

                double averageVal = (val2Min + val2Max) / 2;
                averageValStr = averageVal.ToString(iNumericFormat.NumericFormatString);
            }
            else if (var is ProcessVarInt)
            {
                IntRange intRange = (IntRange)minMaxValues;

                int valMin = intRange.MinValue;
                if (valMin == Constants.NO_VALUE_INT)
                {
                    this.textBoxMinValue.Text = "";
                }
                else
                {
                    this.textBoxMinValue.Text = valMin.ToString(UI.DECIMAL);
                }

                int valMax = intRange.MaxValue;
                if (valMax == Constants.NO_VALUE_INT)
                {
                    this.textBoxMaxValue.Text = "";
                }
                else
                {
                    this.textBoxMaxValue.Text = valMax.ToString(UI.DECIMAL);
                }

                int averageVal = (int)((valMin + valMax) / 2);
                averageValStr = averageVal.ToString(iNumericFormat.NumericFormatString);
            }

            // as convenience, initialize the new value with the recommended value
            this.textBoxNewValue.Text = averageValStr;

            this.textBoxExistingValue.BackColor = Color.Gainsboro;
            this.textBoxMinValue.BackColor      = Color.Gainsboro;
            this.textBoxMaxValue.BackColor      = Color.Gainsboro;
        }
Esempio n. 21
0
 /// <summary>
 /// Creates a new InteractiveBrokersException with the specified error and message
 /// </summary>
 /// <param name="error">The error code returned from the Interactive Broker's server</param>
 /// <param name="message">The error message that explains the reason for the exception.</param>
 /// <param name="inner">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param>
 public InteractiveBrokersException(ErrorMessage error, string message, Exception inner)
     : base(message, inner)
 {
     Error = error;
 }
        static int Main(string[] args)
        {
            HpToolsLauncher.ConsoleQuickEdit.Disable();
            Console.OutputEncoding = System.Text.Encoding.GetEncoding("utf-8");
            log("starting analysis launcher");
            int iPassed = (int)Launcher.ExitCodeEnum.Passed;//variable to keep track of whether all of the SLAs passed

            try
            {
                if (args.Length != 3)
                {
                    ShowHelp();
                    return((int)Launcher.ExitCodeEnum.Aborted);
                }

                string lrrlocation  = args[0];
                string lralocation  = args[1];
                string htmlLocation = args[2];

                log("creating analysis COM object");
                LrAnalysis analysis = new LrAnalysis();

                Session session = analysis.Session;
                log("creating analysis session");
                if (session.Create(lralocation, lrrlocation))
                {
                    log("analysis session created");
                    log("creating HTML reports");
                    HtmlReportMaker reportMaker = session.CreateHtmlReportMaker();
                    reportMaker.AddGraph("Connections");
                    reportMaker.AddGraph("ConnectionsPerSecond");
                    reportMaker.CreateDefaultHtmlReport(
                        Path.Combine(Path.GetDirectoryName(htmlLocation), "IE", Path.GetFileName(htmlLocation)),
                        ApiBrowserType.IE);
                    reportMaker.CreateDefaultHtmlReport(
                        Path.Combine(Path.GetDirectoryName(htmlLocation), "Netscape", Path.GetFileName(htmlLocation)),
                        ApiBrowserType.Netscape);
                    log("HTML reports created");

                    XmlDocument xmlDoc = new XmlDocument();

                    log("loading errors, if any");
                    session.ErrorMessages.LoadValuesIfNeeded();
                    if (session.ErrorMessages.Count != 0)
                    {
                        log("error count: " + session.ErrorMessages.Count);
                        if (session.ErrorMessages.Count > 1000)
                        {
                            log("more then 1000 error during scenario run, analyzing only the first 1000.");
                        }
                        log(Resources.ErrorsReportTitle);
                        XmlElement errorRoot = xmlDoc.CreateElement("Errors");
                        xmlDoc.AppendChild(errorRoot);
                        int            limit  = 1000;
                        ErrorMessage[] errors = session.ErrorMessages.ToArray();
                        //foreach (ErrorMessage err in session.ErrorMessages)
                        for (int i = 0; i < limit && i < errors.Length; i++)
                        {
                            ErrorMessage err  = errors[i];
                            XmlElement   elem = xmlDoc.CreateElement("Error");
                            elem.SetAttribute("ID", err.ID.ToString());
                            elem.AppendChild(xmlDoc.CreateTextNode(err.Name));
                            log("ID: " + err.ID + " Name: " + err.Name);
                            errorRoot.AppendChild(elem);
                        }
                        xmlDoc.Save(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(lrrlocation)), "Errors.xml"));

                        xmlDoc.RemoveAll();
                        log("");
                    }
                    XmlDocument runReprotDoc = new XmlDocument();
                    log("Gathering Run statistics");
                    XmlElement runsRoot = runReprotDoc.CreateElement("Runs");
                    runReprotDoc.AppendChild(runsRoot);

                    XmlElement general = runReprotDoc.CreateElement("General");
                    runsRoot.AppendChild(general);

                    XmlElement durationElement = runReprotDoc.CreateElement("Time");
                    durationElement.SetAttribute("End", "-1");
                    durationElement.SetAttribute("Start", "-1");
                    durationElement.SetAttribute("Duration", "-1");

                    Stopper stopper = new Stopper(10000);
                    stopper.Start();
                    //foreach (Run currentRun in analysis.Session.Runs)
                    //{
                    //    stopper.Start();
                    //    log("Gathering Duration statistics");
                    //    stopper.Start();
                    //DateTime startTime = Helper.FromUnixTime(currentRun.StartTime);
                    //DateTime endTime = Helper.FromUnixTime(currentRun.EndTime);
                    //durationElement.SetAttribute("End", endTime.ToString());
                    //durationElement.SetAttribute("Start", startTime.ToString());
                    //durationElement.SetAttribute("Duration", Helper.GetScenarioDuration(currentRun));
                    //}
                    general.AppendChild(durationElement);

                    XmlElement vUsers = runReprotDoc.CreateElement("VUsers");
                    //log("Adding VUser statistics");
                    Dictionary <string, int> vuserCountDictionary = new Dictionary <string, int>(4)
                    {
                        { "Passed", 0 },
                        { "Stopped", 0 },
                        { "Failed", 0 },
                        { "Error", 0 }
                    };
                    //vuserCountDictionary = Helper.GetVusersCountByStatus(analysis);
                    foreach (KeyValuePair <string, int> kvp in vuserCountDictionary)
                    {
                        //log(msg: String.Format("{0} vUsers: {1}", kvp.Key, kvp.Value));
                        vUsers.SetAttribute(kvp.Key, kvp.Value.ToString());
                    }
                    vUsers.SetAttribute("Count", session.VUsers.Count.ToString());
                    general.AppendChild(vUsers);

                    XmlElement transactions = runReprotDoc.CreateElement("Transactions");
                    Dictionary <string, double> transactionSumStatusDictionary = new Dictionary <string, double>()
                    {
                        { "Count", 0 },
                        { "Pass", 0 },
                        { "Fail", 0 },
                        { "Stop", 0 }
                    };
                    Dictionary <string, Dictionary <string, double> > transactionDictionary =
                        Helper.CalcFailedTransPercent(analysis);
                    foreach (KeyValuePair <string, Dictionary <string, double> > kvp in transactionDictionary)
                    {
                        XmlElement transaction = runReprotDoc.CreateElement("Transaction");
                        foreach (var transStatus in kvp.Value)
                        {
                            transaction.SetAttribute(transStatus.Key, transStatus.Value.ToString());
                            transactionSumStatusDictionary[transStatus.Key] += transStatus.Value;
                            transactionSumStatusDictionary["Count"]         += transStatus.Value;
                        }
                        transaction.SetAttribute("Name", kvp.Key);
                        transactions.AppendChild(transaction);
                    }
                    foreach (var transStatus in transactionSumStatusDictionary)
                    {
                        transactions.SetAttribute(transStatus.Key, transStatus.Value.ToString());
                        //log(msg: String.Format("{0} transaction: {1}", transStatus.Key, transStatus.Value));
                    }
                    general.AppendChild(transactions);

                    string connectionsMaximum = "0";
                    //connectionsMaximum = Helper.GetConnectionsCount(analysis).ToString();
                    XmlElement connections = runReprotDoc.CreateElement("Connections");
                    connections.SetAttribute("MaxCount", connectionsMaximum);
                    general.AppendChild(connections);


                    log("");
                    log("closing session");
                    session.Close();
                    log(Resources.SLAReportTitle);
                    log("calculating SLA");
                    SlaResult slaResult = Session.CalculateSla(lralocation, true);
                    log("SLA calculation done");
                    XmlElement root = xmlDoc.CreateElement("SLA");
                    xmlDoc.AppendChild(root);

                    int iCounter = 0; // set counter
                    log("WholeRunRules : " + slaResult.WholeRunRules.Count);
                    CultureInfo formatProvider = new CultureInfo("en-US");
                    foreach (SlaWholeRunRuleResult a in slaResult.WholeRunRules)
                    {
                        log(Resources.DoubleLineSeperator);
                        XmlElement elem;
                        if (a.Measurement.Equals(SlaMeasurement.PercentileTRT))
                        {
                            SlaPercentileRuleResult b = slaResult.TransactionRules.PercentileRules[iCounter];
                            elem = xmlDoc.CreateElement("SLA_GOAL"); //no white space in the element name
                            log("Transaction Name : " + b.TransactionName);
                            elem.SetAttribute("TransactionName", b.TransactionName.ToString());
                            log("Percentile : " + b.Percentage);
                            elem.SetAttribute("Percentile", b.Percentage.ToString(formatProvider));
                            elem.SetAttribute("FullName", b.RuleUiName);
                            log("Full Name : " + b.RuleUiName);
                            log("Measurement : " + b.Measurement);
                            elem.SetAttribute("Measurement", b.Measurement.ToString());
                            log("Goal Value : " + b.GoalValue);
                            elem.SetAttribute("GoalValue", b.GoalValue.ToString(formatProvider));
                            log("Actual value : " + b.ActualValue);
                            elem.SetAttribute("ActualValue", b.ActualValue.ToString(formatProvider));
                            log("status : " + b.Status);
                            elem.AppendChild(xmlDoc.CreateTextNode(b.Status.ToString()));

                            if (b.Status.Equals(SlaRuleStatus.Failed)) // 0 = failed
                            {
                                iPassed = (int)Launcher.ExitCodeEnum.Failed;
                            }
                            iCounter++;
                        }
                        else
                        {
                            elem = xmlDoc.CreateElement("SLA_GOAL"); //no white space in the element name
                            elem.SetAttribute("FullName", a.RuleUiName);
                            log("Full Name : " + a.RuleUiName);
                            log("Measurement : " + a.Measurement);
                            elem.SetAttribute("Measurement", a.Measurement.ToString());
                            log("Goal Value : " + a.GoalValue);
                            elem.SetAttribute("GoalValue", a.GoalValue.ToString(formatProvider));
                            log("Actual value : " + a.ActualValue);
                            elem.SetAttribute("ActualValue", a.ActualValue.ToString(formatProvider));
                            log("status : " + a.Status);
                            elem.AppendChild(xmlDoc.CreateTextNode(a.Status.ToString()));

                            if (a.Status.Equals(SlaRuleStatus.Failed)) // 0 = failed
                            {
                                iPassed = (int)Launcher.ExitCodeEnum.Failed;
                            }
                        }
                        root.AppendChild(elem);
                        log(Resources.DoubleLineSeperator);
                    }

                    iCounter = 0; // reset counter
                    log("TimeRangeRules : " + slaResult.TimeRangeRules.Count);
                    foreach (SlaTimeRangeRuleResult a in slaResult.TimeRangeRules)
                    {
                        log(Resources.DoubleLineSeperator);
                        XmlElement rule;
                        if (a.Measurement.Equals(SlaMeasurement.AverageTRT))
                        {
                            SlaTransactionTimeRangeRuleResult b = slaResult.TransactionRules.TimeRangeRules[iCounter];
                            rule = xmlDoc.CreateElement("SLA_GOAL"); //no white space in the element name
                            log("Transaction Name: " + b.TransactionName);
                            rule.SetAttribute("TransactionName", b.TransactionName);
                            log("Full Name : " + b.RuleUiName);
                            rule.SetAttribute("FullName", b.RuleUiName);
                            log("Measurement : " + b.Measurement);
                            rule.SetAttribute("Measurement", b.Measurement.ToString());
                            log("SLA Load Threshold Value : " + b.CriteriaMeasurement);
                            rule.SetAttribute("SLALoadThresholdValue", b.CriteriaMeasurement.ToString());
                            log("LoadThresholds : " + b.LoadThresholds.Count);
                            foreach (SlaLoadThreshold slat in b.LoadThresholds)
                            {
                                XmlElement loadThr = xmlDoc.CreateElement("SlaLoadThreshold");
                                loadThr.SetAttribute("StartLoadValue", slat.StartLoadValue.ToString(formatProvider));
                                loadThr.SetAttribute("EndLoadValue", slat.EndLoadValue.ToString(formatProvider));
                                loadThr.SetAttribute("ThresholdValue", slat.ThresholdValue.ToString(formatProvider));
                                rule.AppendChild(loadThr);
                            }
                            XmlElement timeRanges = xmlDoc.CreateElement("TimeRanges");
                            log("TimeRanges : " + b.TimeRanges.Count);
                            int passed = 0;
                            int failed = 0;
                            int noData = 0;
                            foreach (SlaTimeRangeInfo slatri in b.TimeRanges)
                            {
                                XmlElement subsubelem = xmlDoc.CreateElement("TimeRangeInfo");
                                subsubelem.SetAttribute("StartTime", slatri.StartTime.ToString());
                                subsubelem.SetAttribute("EndTime", slatri.EndTime.ToString());
                                subsubelem.SetAttribute("GoalValue", slatri.GoalValue.ToString(formatProvider));
                                subsubelem.SetAttribute("ActualValue", slatri.ActualValue.ToString(formatProvider));
                                subsubelem.SetAttribute("LoadValue", slatri.LoadValue.ToString(formatProvider));
                                subsubelem.InnerText = slatri.Status.ToString();
                                switch (slatri.Status)
                                {
                                case SlaRuleStatus.Failed:
                                    failed++;
                                    break;

                                case SlaRuleStatus.Passed:
                                    passed++;
                                    break;

                                case SlaRuleStatus.NoData:
                                    noData++;
                                    break;

                                default:
                                    break;
                                }
                                timeRanges.AppendChild(subsubelem);
                            }
                            rule.AppendChild(timeRanges);
                            SlaRuleStatus currentRuleStatus = b.Status;
                            if (currentRuleStatus.Equals(SlaRuleStatus.NoData) && (passed > noData))
                            {
                                currentRuleStatus = SlaRuleStatus.Passed;
                            }
                            log("status : " + currentRuleStatus);
                            rule.AppendChild(xmlDoc.CreateTextNode(currentRuleStatus.ToString()));
                            if (currentRuleStatus.Equals(SlaRuleStatus.Failed)) // 0 = failed
                            {
                                iPassed = (int)Launcher.ExitCodeEnum.Failed;
                            }
                            iCounter++;
                        }
                        else
                        {
                            rule = xmlDoc.CreateElement("SLA_GOAL"); //no white space in the element name
                            log("Full Name : " + a.RuleUiName);
                            rule.SetAttribute("FullName", a.RuleUiName);
                            log("Measurement : " + a.Measurement);
                            rule.SetAttribute("Measurement", a.Measurement.ToString());
                            log("SLA Load Threshold Value : " + a.CriteriaMeasurement);
                            rule.SetAttribute("SLALoadThresholdValue", a.CriteriaMeasurement.ToString());
                            log("LoadThresholds : " + a.LoadThresholds.Count);
                            foreach (SlaLoadThreshold slat in a.LoadThresholds)
                            {
                                XmlElement loadThr = xmlDoc.CreateElement("SlaLoadThreshold");
                                loadThr.SetAttribute("StartLoadValue", slat.StartLoadValue.ToString(formatProvider));
                                loadThr.SetAttribute("EndLoadValue", slat.EndLoadValue.ToString(formatProvider));
                                loadThr.SetAttribute("ThresholdValue", slat.ThresholdValue.ToString(formatProvider));
                                rule.AppendChild(loadThr);
                            }
                            XmlElement timeRanges = xmlDoc.CreateElement("TimeRanges");
                            log("TimeRanges : " + a.TimeRanges.Count);
                            int passed = 0;
                            int failed = 0;
                            int noData = 0;
                            foreach (SlaTimeRangeInfo slatri in a.TimeRanges)
                            {
                                XmlElement subsubelem = xmlDoc.CreateElement("TimeRangeInfo");
                                subsubelem.SetAttribute("StartTime", slatri.StartTime.ToString());
                                subsubelem.SetAttribute("EndTime", slatri.EndTime.ToString());
                                subsubelem.SetAttribute("GoalValue", slatri.GoalValue.ToString(formatProvider));
                                subsubelem.SetAttribute("ActualValue", slatri.ActualValue.ToString(formatProvider));
                                subsubelem.SetAttribute("LoadValue", slatri.LoadValue.ToString(formatProvider));
                                subsubelem.InnerText = slatri.Status.ToString();
                                switch (slatri.Status)
                                {
                                case SlaRuleStatus.Failed:
                                    failed++;
                                    break;

                                case SlaRuleStatus.Passed:
                                    passed++;
                                    break;

                                case SlaRuleStatus.NoData:
                                    noData++;
                                    break;

                                default:
                                    break;
                                }
                                timeRanges.AppendChild(subsubelem);
                            }
                            rule.AppendChild(timeRanges);
                            SlaRuleStatus currentRuleStatus = a.Status;
                            if (currentRuleStatus.Equals(SlaRuleStatus.NoData) && (passed > noData))
                            {
                                currentRuleStatus = SlaRuleStatus.Passed;
                            }
                            log("status : " + currentRuleStatus);
                            rule.AppendChild(xmlDoc.CreateTextNode(currentRuleStatus.ToString()));
                            if (currentRuleStatus.Equals(SlaRuleStatus.Failed))
                            {
                                iPassed = (int)Launcher.ExitCodeEnum.Failed;
                            }
                        }
                        root.AppendChild(rule);

                        log(Resources.DoubleLineSeperator);
                    }

                    XmlNode slaNode = runReprotDoc.ImportNode(root, true);
                    runsRoot.AppendChild(slaNode);
                    log("saving RunReport.xml to " +
                        Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(lrrlocation)), "RunReport.xml"));
                    runReprotDoc.Save(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(lrrlocation)),
                                                   "RunReport.xml"));
                    runReprotDoc.RemoveAll();

                    //write XML to location:
                    log("saving SLA.xml to " +
                        Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(lrrlocation)), "SLA.xml"));
                    xmlDoc.Save(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(lrrlocation)), "SLA.xml"));
                }
                else
                {
                    log(Resources.CannotCreateSession);
                    return((int)Launcher.ExitCodeEnum.Aborted);
                }
                log("closing analysis session");
                session.Close();
            }
            catch (TypeInitializationException ex)
            {
                if (ex.InnerException is UnauthorizedAccessException)
                {
                    log(
                        "UnAuthorizedAccessException: Please check the account privilege of current user, LoadRunner tests should be run by administrators.");
                }
                else
                {
                    log(ex.Message);
                    log(ex.StackTrace);
                }
                return((int)Launcher.ExitCodeEnum.Aborted);
            }
            catch (Exception e)
            {
                log(e.Message);
                log(e.StackTrace);
                return((int)Launcher.ExitCodeEnum.Aborted);
            }


            // return SLA status code, if any SLA fails return a fail here.
            // writer.Flush();
            // writer.Close();
            return(iPassed);
        }
        public void ManagedUpdate()
        {
            if (timeLastDrilled + 0.5f > Time.time)
            {
                drillable.modelRoot.transform.position = transform.position + new Vector3(Mathf.Sin(Time.time * 60f), Mathf.Cos(Time.time * 58f + 0.5f), Mathf.Cos(Time.time * 64f + 2f)) * 0.011f;
            }
            if (lootPinataObjects.Count > 0 && drillingMoth)
            {
                List <GameObject> list = new List <GameObject>();

                foreach (GameObject gameObject in lootPinataObjects)
                {
                    if (gameObject == null)
                    {
                        list.Add(gameObject);
                    }
                    else
                    {
                        Vector3 b = drillingMoth.transform.position + new Vector3(0f, 0.8f, 0f);

                        gameObject.transform.position = Vector3.Lerp(gameObject.transform.position, b, Time.deltaTime * 5f);

                        float num = Vector3.Distance(gameObject.transform.position, b);

                        if (num < 3f)
                        {
                            Pickupable pickupable = gameObject.GetComponentInChildren <Pickupable>();

                            if (pickupable)
                            {
                                SeamothArmManager control = drillingMoth.GetComponent <SeamothArmManager>();

                                if (!control.HasRoomForItem(pickupable))
                                {
                                    if (Player.main.GetVehicle() == drillingMoth)
                                    {
                                        ErrorMessage.AddMessage(Language.main.Get("ContainerCantFit"));
                                    }
                                }
                                else
                                {
                                    string arg = Language.main.Get(pickupable.GetTechName());
                                    ErrorMessage.AddMessage(Language.main.GetFormat("VehicleAddedToStorage", arg));
                                    uGUI_IconNotifier.main.Play(pickupable.GetTechType(), uGUI_IconNotifier.AnimationType.From, null);
                                    pickupable = pickupable.Initialize();
                                    InventoryItem item = new InventoryItem(pickupable);
                                    control.GetRoomForItem(pickupable).UnsafeAdd(item);
                                    pickupable.PlayPickupSound();
                                }
                                list.Add(gameObject);
                            }
                        }
                    }
                }

                if (list.Count > 0)
                {
                    foreach (GameObject item2 in list)
                    {
                        lootPinataObjects.Remove(item2);
                    }
                }
            }
        }
Esempio n. 24
0
 public Error(string FieldName, ErrorMessage Message)
 {
     this.FieldName = FieldName;
     this.Message   = Message;
 }
Esempio n. 25
0
        protected override void MouseDownHandler(Point p)
        {
            if (this.flowsheet.Activity == FlowsheetActivity.AddingConnStepOne)
            {
                int idx = -1;
                if (HitTestGasIn(p) || HitTestGasOut(p) || HitTestLiquidOut(p))
                {
                    if (HitTestGasIn(p))
                    {
                        idx = ScrubberCondenser.GAS_INLET_INDEX;
                    }
                    else if (HitTestGasOut(p))
                    {
                        idx = ScrubberCondenser.GAS_OUTLET_INDEX;
                    }
                    else if (HitTestLiquidOut(p))
                    {
                        idx = ScrubberCondenser.LIQUID_OUTLET_INDEX;
                    }

                    if (this.ScrubberCondenser.CanConnect(idx))
                    {
                        // ok for the second step
                        this.flowsheet.firstStepCtrl = this;
                        this.flowsheet.Activity      = FlowsheetActivity.AddingConnStepTwo;
                        this.flowsheet.attachIndex   = idx;
                    }
                }
                else
                {
                    this.flowsheet.ResetActivity();
                }
            }
            else if (this.flowsheet.Activity == FlowsheetActivity.AddingConnStepTwo)
            {
                if (this.flowsheet.firstStepCtrl.Solvable is ProcessStreamBase)
                {
                    int idx = -1;
                    if (HitTestGasIn(p))
                    {
                        idx = ScrubberCondenser.GAS_INLET_INDEX;
                    }
                    else if (HitTestGasOut(p))
                    {
                        idx = ScrubberCondenser.GAS_OUTLET_INDEX;
                    }
                    else if (HitTestLiquidOut(p))
                    {
                        idx = ScrubberCondenser.LIQUID_OUTLET_INDEX;
                    }

                    ProcessStreamBaseControl ctrl = (ProcessStreamBaseControl)this.flowsheet.firstStepCtrl;
                    if (this.ScrubberCondenser.CanAttachStream(ctrl.ProcessStreamBase, idx))
                    {
                        // update the model, the UI will be updated in the listener
                        ErrorMessage error = this.ScrubberCondenser.AttachStream(ctrl.ProcessStreamBase, idx);
                        UI.ShowError(error);
                    }
                }
                this.flowsheet.ResetActivity();
            }
            else
            {
                this.flowsheet.ResetActivity();
                this.PerformSelection();
                this.PrepareForTheMove(p.X, p.Y);
            }
        }
Esempio n. 26
0
        public Tuple <bool, List <object> > UploadValidate(ref List <COAViewModel> Data, List <KeyValuePair <string, StringValues> > Body)
        {
            List <object> ErrorList = new List <object>();
            string        ErrorMessage;
            bool          Valid  = true;
            var           dbData = DbSet.ToList();

            foreach (COAViewModel coaVM in Data)
            {
                ErrorMessage = "";

                if (string.IsNullOrWhiteSpace(coaVM.Code))
                {
                    ErrorMessage = string.Concat(ErrorMessage, "Kode tidak boleh kosong, ");
                }
                else if (Data.Any(d => d != coaVM && d.Code.Equals(coaVM.Code)))
                {
                    ErrorMessage = string.Concat(ErrorMessage, "Kode tidak boleh duplikat, ");
                }
                else
                {
                    var codeArray = coaVM.Code.Split('.', StringSplitOptions.RemoveEmptyEntries);
                    if (codeArray.Count() != CODE_COUNT)
                    {
                        ErrorMessage = string.Concat(ErrorMessage, "Kode tidak valid, ");
                    }
                    else
                    {
                        if (!codeArray[0].All(char.IsDigit) || !codeArray[1].All(char.IsDigit) || !codeArray[2].All(char.IsDigit) || !codeArray[3].All(char.IsDigit))
                        {
                            ErrorMessage = string.Concat(ErrorMessage, "Kode tidak valid, ");
                        }
                        if (codeArray[0].Length > CODE1_LENGTH)
                        {
                            ErrorMessage = string.Concat(ErrorMessage, "Kode tidak valid, ");
                        }
                        else if (codeArray[0].Length < CODE1_LENGTH && codeArray[0].Length > 0)
                        {
                            string firstCode = codeArray[0];
                            codeArray[0] = firstCode.PadLeft(CODE1_LENGTH, '0');
                        }

                        if (codeArray[1].Length > CODE2_LENGTH)
                        {
                            ErrorMessage = string.Concat(ErrorMessage, "Kode tidak valid, ");
                        }
                        else if (codeArray[1].Length < CODE2_LENGTH && codeArray[1].Length > 0)
                        {
                            string secondCode = codeArray[1];
                            codeArray[1] = secondCode.PadLeft(CODE2_LENGTH, '0');
                        }

                        if (codeArray[2].Length > CODE3_LENGTH)
                        {
                            ErrorMessage = string.Concat(ErrorMessage, "Kode tidak valid, ");
                        }

                        if (codeArray[3].Length > CODE4_LENGTH)
                        {
                            ErrorMessage = string.Concat(ErrorMessage, "Kode tidak valid, ");
                        }
                        else if (codeArray[3].Length < CODE4_LENGTH && codeArray[3].Length > 0)
                        {
                            string fourthCode = codeArray[3];
                            codeArray[3] = fourthCode.PadLeft(CODE4_LENGTH, '0');
                        }
                        coaVM.Code = string.Join('.', codeArray);
                        if (dbData.Any(x => x.Code == coaVM.Code))
                        {
                            ErrorMessage = string.Concat(ErrorMessage, "Kode sudah ada di database, ");
                        }
                        if (dbData.Any(x => x.Name == coaVM.Name))
                        {
                            ErrorMessage = string.Concat(ErrorMessage, "Nama sudah ada di database, ");
                        }
                    }
                }

                if (string.IsNullOrWhiteSpace(coaVM.Name))
                {
                    ErrorMessage = string.Concat(ErrorMessage, "Nama tidak boleh kosong, ");
                }
                else if (Data.Any(d => d != coaVM && d.Name.Equals(coaVM.Name)))
                {
                    ErrorMessage = string.Concat(ErrorMessage, "Nama tidak boleh duplikat, ");
                }



                if (!string.IsNullOrEmpty(ErrorMessage))
                {
                    ErrorMessage = ErrorMessage.Remove(ErrorMessage.Length - 2);
                    var Error = new ExpandoObject() as IDictionary <string, object>;

                    Error.Add("Kode", coaVM.Code);
                    Error.Add("Nama", coaVM.Name);
                    Error.Add("Path", coaVM.Path);
                    Error.Add("Report Type", coaVM.ReportType);
                    Error.Add("Nature", coaVM.Nature);
                    Error.Add("Cash Account", coaVM.CashAccount);
                    Error.Add("Error", ErrorMessage);

                    ErrorList.Add(Error);
                }
            }

            if (ErrorList.Count > 0)
            {
                Valid = false;
            }

            return(Tuple.Create(Valid, ErrorList));
        }
Esempio n. 27
0
 public void Handle(ErrorMessage message)
 {
     throw new AmbiguousMatchException();
 }
Esempio n. 28
0
 /// <summary>
 /// Creates a new InteractiveBrokersException with the specified error and message
 /// </summary>
 /// <param name="error">The error code returned from the Interactive Broker's server</param>
 /// <param name="tickerID">The order ID or the ticker ID that generated the error, or zero if the error is not associated with any order or ticker</param>
 /// <param name="message">The error message that explains the reason for the exception.</param>
 /// <param name="inner">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param>
 public InteractiveBrokersException(ErrorMessage error, int tickerID, string message, Exception inner)
     : base(message, inner)
 {
     Error    = error;
     TickerID = tickerID;
 }
 /// <summary>
 /// Creates a new InteractiveBrokersException with the specified error and message
 /// </summary>
 /// <param name="error">The error code returned from the Interactive Broker's server</param>
 /// <param name="message">The error message that explains the reason for the exception.</param>
 /// <param name="inner">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param>
 public InteractiveBrokersException(ErrorMessage error, string message, Exception inner)
     : base(message, inner)
 {
     Error = error;
 }
Esempio n. 30
0
        protected override void OnAfterTransition(RegulatorState oldState, RegulatorState newState, object data)
        {
            switch (newState.Name)
            {
            case "AuthLogin":
                var loginData = (AuthRequest)data;
                var result    = AuthClient.Authenticate(loginData);

                if (result == null || !result.Valid)
                {
                    if (result.ReasonText != null)
                    {
                        base.ThrowErrorAndReset(ErrorMessage.FromLiteral(result.ReasonText));
                    }
                    else if (result.ReasonCode != null)
                    {
                        base.ThrowErrorAndReset(ErrorMessage.FromLiteral(
                                                    (GameFacade.Strings.GetString("210", result.ReasonCode) ?? "Unknown Error")
                                                    .Replace("EA.com", AuthClient.BaseUrl.Substring(7).TrimEnd('/'))
                                                    ));
                    }
                    else
                    {
                        base.ThrowErrorAndReset(new Exception("Unknown error"));
                    }
                }
                else
                {
                    this.AuthResult = result;
                    AsyncTransition("InitialConnect");
                }
                break;

            case "InitialConnect":
                try {
                    var connectResult = CityClient.InitialConnectServlet(
                        new InitialConnectServletRequest {
                        Ticket  = AuthResult.Ticket,
                        Version = "Version 1.1097.1.0"
                    });

                    if (connectResult.Status == InitialConnectServletResultType.Authorized)
                    {
                        if (RequireUpdate(connectResult.UserAuthorized))
                        {
                            AsyncTransition("UpdateRequired", connectResult.UserAuthorized);
                        }
                        else
                        {
                            AsyncTransition("AvatarData");
                        }
                    }
                    else if (connectResult.Status == InitialConnectServletResultType.Error)
                    {
                        base.ThrowErrorAndReset(ErrorMessage.FromLiteral(connectResult.Error.Code, connectResult.Error.Message));
                    }
                }catch (Exception ex)
                {
                    base.ThrowErrorAndReset(ex);
                }
                break;

            case "UpdateRequired":
                break;

            case "AvatarData":
                try {
                    Avatars = CityClient.AvatarDataServlet();
                    AsyncTransition("ShardStatus");
                }
                catch (Exception ex)
                {
                    base.ThrowErrorAndReset(ex);
                }
                break;

            case "ShardStatus":
                try {
                    ((ClientShards)Shards).All = CityClient.ShardStatus();
                    AsyncTransition("LoggedIn");
                }
                catch (Exception ex)
                {
                    base.ThrowErrorAndReset(ex);
                }
                break;

            case "LoggedIn":
                FSOFacade.Controller.ShowPersonSelection();
                break;
            }
        }
Esempio n. 31
0
 public SendQueryEventArgs(Node node, IPEndPoint endpoint, QueryMessage query, ErrorMessage error)
 {
     EndPoint = endpoint;
     Error    = error;
     Node     = node;
     Query    = query;
     Response = null;
 }
Esempio n. 32
0
 /// <summary>
 /// Handles an Error Message from the client
 /// </summary>
 /// <param name="message"></param>
 private void HandleErrorMessage(ErrorMessage message)
 {
 }
Esempio n. 33
0
        // This method using WebRequest
        private OrderSimOutCollection OrderSimulateToSAP(OrderSimInputCollection collection)
        {
            OrderSimOutCollection orderSimOutCollection = new OrderSimOutCollection();

            try
            {
                // Get Cookies and csrfToken
                if (string.IsNullOrEmpty(csrfTokenOrderSimulate))
                {
                    GetCSRFTokenForSimulation();
                }

                // Using the HTTPWebRequest.
                var            cookieContainerOrderSimulate = new CookieContainer();
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sapOrderSimulationPost);

                // Add Credentional, Header, Token & Cookies
                req.Credentials = new NetworkCredential(sapUserName, sapPassword);
                req.Method      = "POST";
                req.Headers.Add("X-CSRF-Token", csrfTokenOrderSimulate);
                req.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
                req.Accept            = "application/json";
                req.ContentType       = "application/json";
                cookieContainerOrderSimulate.Add(new Uri(sapOrderSimulationPost), cookiestopassOrderSimulate);
                req.CookieContainer = cookieContainerOrderSimulate;

                // Get Order Simulate JSON Data from Entity
                var jsonData = JsonConvert.SerializeObject(collection, settings);

                // Enclding JSON Data
                UTF8Encoding encoding = new UTF8Encoding();
                Byte[]       bytes    = encoding.GetBytes(jsonData);

                Stream newStream = req.GetRequestStream();
                newStream.Write(bytes, 0, bytes.Length);
                newStream.Close();

                using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
                {
                    // Get the response Content from Webresponse
                    var rawJson = new StreamReader(response.GetResponseStream()).ReadToEnd();

                    if (response.StatusCode == HttpStatusCode.Created)
                    {
                        // Deserialize the Response JSON data to Order data.
                        OrderSimOutCollection responseCollection = JsonConvert.DeserializeObject <OrderSimOutCollection>(rawJson);

                        if (responseCollection != null)
                        {
                            orderSimOutCollection = responseCollection;
                        }
                    }
                    else if (response.StatusCode == HttpStatusCode.BadRequest)
                    {
                        // Log for the bad request.
                        string errorMessage = rawJson;
                        //Log.Info(errorMessage);
                    }
                }
            }
            catch (WebException webex)
            {
                var exceptionJson = new StreamReader(webex.Response.GetResponseStream()).ReadToEnd();

                // Deserialize the Response JSON data to Error Model
                ErrorMessage errorMessage = JsonConvert.DeserializeObject <ErrorMessage>(exceptionJson);

                // Log
                string message = errorMessage.error.message.value;
                //Log.Info(errorMessage);
            }
            catch (Exception ex)
            {
                // Log the message in case any exception
                //Log.Info(ex.Message);
            }

            return(orderSimOutCollection);
        }
Esempio n. 34
0
 public void Log(string text)
 {
     ErrorMessage.AddMessage(text);
 }
Esempio n. 35
0
        private async Task ReadErrorMessage(HttpContext ctx)
        {
            var interaction = ctx.RequestServices.GetRequiredService <IIdentityServerInteractionService>();

            ErrorMessage = await interaction.GetErrorContextAsync(ctx.Request.Query["errorId"].FirstOrDefault());
        }
 public void RevievingErrorMessage(ErrorMessage message)
 {
     _errorMessage = message;
 }
Esempio n. 37
0
        private void ProcessErrorMessage(string msg)
        {
            var errorMessage = ErrorMessage.Parse(msg);

            Error?.Invoke(errorMessage);
        }
Esempio n. 38
0
		/// <summary>
		/// Adds a single new message to a table and displays it
		/// </summary>
		/// <param name="textBox">The text box where the error appears</param>
		/// <param name="message">The error message you wish to add</param>
		public void AddMessage(TextBox textBox, ErrorMessage message)
		{
			Set<ErrorMessage> listOfMessages = null;
			if (errorTable.TryGetValue(textBox, out listOfMessages))
			{
				// An entry for this message box exists
				listOfMessages.Add(message);
			}
			else
			{
				// Not found, so initialize it.
				listOfMessages = new Set<ErrorMessage>();
				listOfMessages.Add(message);
				errorTable.Add(textBox, listOfMessages);
			}
			DisplayErrorTable();
		}
 public UnauthorizedException(ErrorMessage errorMessage)
     : base(errorMessage)
 {
 }
Esempio n. 40
0
 void HandleException(Exception exception)
 {
     ErrorMessage error = new ErrorMessage(exception.Message);
     QueueMessage(new ServerToClientMessage(error));
     ShuttingDown = true;
 }
 /// <summary>
 /// Remove a ErrorMessage from the data store
 /// </summary>
 /// <param name="entity"></param>
 public void Delete(ErrorMessage entity)
 {
     _entityContext.ErrorMessages.Remove(entity);
 }
Esempio n. 42
0
 /// <summary>
 /// Gets the error page HTML.
 /// </summary>
 /// <param name="errorMessage">The error message.</param>
 /// <returns></returns>
 private static string GetErrorPageHtml(ErrorMessage errorMessage)
 {
     return string.Format(ErrorPageHtmlFmt,
                          Resources.SalesLogix.ExceptionPageTitle,
                          Resources.SalesLogix.CannotCompleteRequest,
                          errorMessage.ToString(MessageProperty.FormatType.HtmlEncoded));
 }
    public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId, NetworkReader extraMessageReader)
    {
        Debug.Log("OnServerAddPlayer " + conn.connectionId);
        //cannot add base.OnServerAddPlayer(conn, playerControllerId);
        string playerName = "";
        if (extraMessageReader != null)
        {
            var s = extraMessageReader.ReadMessage<PlayerMessage>();
            playerName = s.userName;
            Debug.Log("my name is " + s.userName);
        }
        switch (currentMode)
        {
            case NetworkMode.Level: 
            case NetworkMode.Lobby:
                Debug.Log("OnServerAddPlayer Lobby ");
                //find out the name does not exist
                if(!CheckUserNameValid(playerName)){
                    ErrorMessage em = new ErrorMessage();
                    em.errorMessage = "This Account Has Already Connected to Server.";
                    NetworkServer.SendToClient(conn.connectionId, ErrorMessage.MsgType, em);
                    return;
                }
                //find a empty slot
                int i = 0;
                for (; i < maxPlayers; i++)
                    if (lobbyPlayerArray[i] == null) break;
                if (i == maxPlayers) return;
                //create lobby object
                var player = (GameObject)GameObject.Instantiate(LobbyPlayerPrefab, Vector3.zero, Quaternion.identity);
                player.GetComponent<LobbyPlayer>().slot = i;
                player.GetComponent<LobbyPlayer>().ownRole = PlayerRole.Unselected;

                //player.GetComponent<LobbyPlayer>().currentMode = currentMode;

                Debug.Log("OnServerAddPlayer Lobby ");

                lobbyPlayerArray[i] = player.GetComponent<LobbyPlayer>();

                //player.GetComponent<LobbyPlayer>().ToggleVisibility(false);
                NetworkServer.AddPlayerForConnection(conn, player, playerControllerId);
                if(currentMode == NetworkMode.Lobby)
                { // make lobby visible amoung all clients and server
                    ChangeVisibilityOfLobbyPlayerEverywhere(true);
                }
                break;
            case NetworkMode.Game:
                Debug.Log("OnServerAddPlayer Game ");
                bool isExistingPlayer = false;
                for (int k = 0; k < maxPlayers; k++)
                {
                    if (disconnectedPlayerControllers[k] != null)
                    {
                        DisconnectedPlayerController dpc = (DisconnectedPlayerController)disconnectedPlayerControllers[k];
                        int dpcconnid = dpc.connId;
                        // Disconnected player to Game Player
                        if (dpc.username == playerName)
                        {
                            //TODO: Disconnect to Player
                            isExistingPlayer = true;
                            Debug.Log(k + " existing " + dpcconnid);
                            disconnectedPlayerControllers[k] = null;

                            GameObject selectedprefab = StrikerPrefab;
                            switch (dpc.currentRole)
                            {
                                case PlayerRole.Engineer:
                                    selectedprefab = EngineerPrefab;
                                    Debug.Log("Reconnect EngineerPrefab");
                                    break;
                            }

                            GameObject gamePlayer = (GameObject)Instantiate(selectedprefab, Vector3.zero, Quaternion.identity);
                            gameplayerControllers[k] = gamePlayer.GetComponent<PlayerController>();
                            PlayerController pc = gamePlayer.GetComponent<PlayerController>();
                            pc.slot = k;
                            pc.username = dpc.username;
                            pc.role = dpc.currentRole;
                            pc.rank = dpc.rank;
                            pc.exp = dpc.exp;
                            pc.score = dpc.score;
                            pc.skill1Counter = dpc.skill1Counter;
                            pc.skill2Counter = dpc.skill2Counter;
                            pc.supportCounter = dpc.supportCounter;
                            pc.setInGame();
                            pc.disconnectCrystal = dpc.crystals;
                            pc.InitializeDisconnectCrystals(dpc.crystals);
                            pc.isPause = dpc.isPause;

                            if (dpc.currentRole == PlayerRole.Engineer)
                            {
                                SetUpEngineerTeammateInfo(gamePlayer.GetComponent<EngineerController>());
                                pc.GetComponent<EngineerController>().initializeData();
                            }
                            else
                            {
                                pc.GetComponent<PlayerController>().initializeData();
                            }

                            Debug.Log("Network Manager InitializeData");

                            gamePlayer.GetComponent<PlayerInfo>().setHealth(dpc.health);

                            NetworkServer.AddPlayerForConnection(conn, gamePlayer, playerControllerId);
                            Destroy(dpc.gameObject);
                        }
                    }
                }
                if (!isExistingPlayer)
                {
                    Debug.Log("No Existing User on the Server");
                    ErrorMessage em = new ErrorMessage();
                    em.errorMessage = "No Existing User on the Server";
                    NetworkServer.SendToClient(conn.connectionId, ErrorMessage.MsgType, em);
                }
                break;
            case NetworkMode.Complete:
                ErrorMessage eem = new ErrorMessage();
                eem.errorMessage = "Game Ended!";
                NetworkServer.SendToClient(conn.connectionId, ErrorMessage.MsgType, eem);
                break;
        }

    }
Esempio n. 44
0
        /// <summary>
        /// Method to get volume value
        /// </summary>
        /// <param name="gradeId">Grade Id</param>
        /// <param name="pumpId">Pump Id</param>
        /// <param name="saleNumber">Sale number</param>
        /// <param name="tillNumber">Till number</param>
        /// <param name="registerNumber">Register number</param>
        /// <param name="propaneValue">Propane value</param>
        /// <param name="error">Error message</param>
        /// <returns>Volume value</returns>
        public string GetVolumeValue(int gradeId, int pumpId, int saleNumber, int tillNumber, byte registerNumber,
                                     decimal propaneValue, out ErrorMessage error)
        {
            string quantity = "";
            var    sale     = _saleManager.GetCurrentSale(saleNumber, tillNumber, registerNumber, UserCode, out error);
            var    offSet   = _policyManager.LoadStoreInfo().OffSet;

            if (!string.IsNullOrEmpty(error?.MessageStyle?.Message))
            {
                return(null);
            }

            var grades = CacheManager.GetPropaneGrades();

            if (grades == null)
            {
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 38, 76, null)
                };
                return(null);
            }
            var firstOrdDefault = grades.FirstOrDefault(p => p.Id == gradeId);

            if (firstOrdDefault == null)
            {
                error = new ErrorMessage
                {
                    MessageStyle = new MessageStyle
                    {
                        Message     = "Invalid Request",
                        MessageType = MessageType.Critical
                    }
                };
                return(null);
            }
            var pumps = _fuelPumpService.GetPumpsByPropaneGradeId(gradeId);

            if (pumps == null || !pumps.Any(p => p.Id == pumpId))
            {
                error = new ErrorMessage
                {
                    MessageStyle = new MessageStyle
                    {
                        Message     = "Invalid Request",
                        MessageType = MessageType.Critical
                    }
                };
                return(null);
            }

            var stockCode = firstOrdDefault.StockCode;


            if (sale.DeletePrepay)
            {
                // "There's no Pump set for " & Stock_Code(index) & ". Please set it in Fuel Control at first.", vbinformation+vbokonly
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 0, 1150, null, InformationOkMessageType)
                };
                return(null);
            }

            var slProp = new Sale_Line();

            _saleLineManager.SetPluCode(ref sale, ref slProp, stockCode, out error);
            slProp.GradeID = (byte)gradeId;
            if (slProp.Regular_Price == 0)
            {
                // "There's no price for " & Stock_Code(Index) & ". Please set it in BackOffice at first.", vbInformation + vbOKOnly
                //MsgBoxStyle temp_VbStyle = (int)MsgBoxStyle.Information + MsgBoxStyle.OkOnly;
                //Chaps_Main.DisplayMessage(this, (short)11, temp_VbStyle, Stock_Code[Index], (byte)0);
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 48, 11, stockCode, InformationOkMessageType)
                };
                return(null);
            }

            if (slProp.Regular_Price > 0)
            {
                quantity = (Conversion.Val(propaneValue) / slProp.Regular_Price).ToString("#####0.000");
            }
            return(quantity);
        }
Esempio n. 45
0
 public void RevievingErrorMessage(ErrorMessage message)
 {
     _logger.Info(message.Error);
 }
Esempio n. 46
0
        /// <summary>
        /// Method to add propane sale
        /// </summary>
        /// <param name="gradeId">Grade Id</param>
        /// <param name="pumpId">Pump Id</param>
        /// <param name="saleNumber">Sale number</param>
        /// <param name="tillNumber">Till number</param>
        /// <param name="registerNumber">Register number</param>
        /// <param name="isAmount">Is amount</param>
        /// <param name="propaneValue">Propane value</param>
        /// <param name="error">Error message</param>
        /// <returns>Sale</returns>
        public Sale AddPropaneSale(int gradeId, int pumpId, int saleNumber, int tillNumber, byte registerNumber,
                                   bool isAmount, decimal propaneValue, out ErrorMessage error)
        {
            var sale   = _saleManager.GetCurrentSale(saleNumber, tillNumber, registerNumber, UserCode, out error);
            var offSet = _policyManager.LoadStoreInfo().OffSet;

            if (!string.IsNullOrEmpty(error?.MessageStyle?.Message))
            {
                return(null);
            }

            var grades = CacheManager.GetPropaneGrades();

            if (grades == null)
            {
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 38, 76, null)
                };
                return(null);
            }
            var firstOrdDefault = grades.FirstOrDefault(p => p.Id == gradeId);

            if (firstOrdDefault == null)
            {
                error = new ErrorMessage
                {
                    MessageStyle = new MessageStyle
                    {
                        Message     = "Invalid Request",
                        MessageType = MessageType.Critical
                    }
                };
                return(null);
            }
            var pumps = _fuelPumpService.GetPumpsByPropaneGradeId(gradeId);

            if (pumps == null || !pumps.Any(p => p.Id == pumpId))
            {
                error = new ErrorMessage
                {
                    MessageStyle = new MessageStyle
                    {
                        Message     = "Invalid Request",
                        MessageType = MessageType.Critical
                    }
                };
                return(null);
            }

            var stockCode = firstOrdDefault.StockCode;


            if (sale.DeletePrepay)
            {
                // "There's no Pump set for " & Stock_Code(index) & ". Please set it in Fuel Control at first.", vbinformation+vbokonly
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 0, 1150, null, InformationOkMessageType)
                };
                return(null);
            }

            var slProp = new Sale_Line();

            _saleLineManager.SetPluCode(ref sale, ref slProp, stockCode, out error);
            slProp.GradeID = (byte)gradeId;
            if (slProp.Regular_Price == 0)
            {
                // "There's no price for " & Stock_Code(Index) & ". Please set it in BackOffice at first.", vbInformation + vbOKOnly
                //MsgBoxStyle temp_VbStyle = (int)MsgBoxStyle.Information + MsgBoxStyle.OkOnly;
                //Chaps_Main.DisplayMessage(this, (short)11, temp_VbStyle, Stock_Code[Index], (byte)0);
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 48, 11, stockCode, InformationOkMessageType)
                };
                return(null);
            }

            slProp.pumpID     = (byte)pumpId;
            slProp.PositionID = (byte)_fuelPumpService.GetPositionId(pumpId, gradeId);

            SetQuantity(ref slProp, isAmount, propaneValue, out error);

            if (!string.IsNullOrEmpty(error?.MessageStyle?.Message))
            {
                return(null);
            }

            if (_policyManager.USE_CUST)
            {
                if (_policyManager.USE_LOYALTY && Strings.UCase(System.Convert.ToString(_policyManager.LOYAL_TYPE)) == "PRICES" && sale.Customer.Loyalty_Code.Length > 0 && sale.Customer.CL_Status == "A" && (!slProp.LOY_EXCLUDE))
                {
                    var loyalPricecode = System.Convert.ToInt16(_policyManager.LOYAL_PRICE);
                    if (loyalPricecode > 0)
                    {
                        _saleLineManager.SetPriceNumber(ref slProp, loyalPricecode);
                    }
                    else
                    {
                        _saleLineManager.SetPriceNumber(ref slProp, sale.Customer.Price_Code != 0 ? sale.Customer.Price_Code : (short)1);
                    }
                }
                else
                {
                    _saleLineManager.SetPriceNumber(ref slProp, sale.Customer.Price_Code != 0 ? sale.Customer.Price_Code : (short)1);
                }
            }
            else
            {
                //SL_Prop.Price_Number = (short)1;
                _saleLineManager.SetPriceNumber(ref slProp, (short)1);
            }
            _saleManager.Add_a_Line(ref sale, slProp, UserCode, sale.TillNumber, out error, true);

            CacheManager.AddCurrentSaleForTill(tillNumber, saleNumber, sale);
            return(sale);
        }
 /// <summary>
 /// Creates a new InteractiveBrokersException with the specified error and message
 /// </summary>
 /// <param name="error">The error code returned from the Interactive Broker's server</param>
 /// <param name="tickerID">The order ID or the ticker ID that generated the error, or zero if the error is not associated with any order or ticker</param>
 /// <param name="message">The error message that explains the reason for the exception.</param>
 /// <param name="inner">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param>
 public InteractiveBrokersException(ErrorMessage error, int tickerID, string message, Exception inner)
     : base(message, inner)
 {
     Error = error;
     TickerID = tickerID;
 }
        public void RefreshPage()
        {
            Address BillingAddress  = new Address();
            Address ShippingAddress = new Address();

            BillingAddress.LoadByCustomer(ThisCustomer.CustomerID, ThisCustomer.PrimaryBillingAddressID, AddressTypes.Billing);
            ShippingAddress.LoadByCustomer(ThisCustomer.CustomerID, ThisCustomer.PrimaryShippingAddressID, AddressTypes.Shipping);

            if (Checkout)
            {
                pnlCheckoutImage.Visible  = true;
                pnlAccountInfoMP.Visible  = false;
                pnlOrderHistoryMP.Visible = false;
                if (ThisCustomer.PrimaryBillingAddressID == 0 || ThisCustomer.PrimaryShippingAddressID == 0 || !ThisCustomer.HasAtLeastOneAddress())
                {
                    ErrorMsgLabel.Text = AppLogic.GetString("account.aspx.73", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);;
                }
            }

            pnlCheckoutImage.Visible = Checkout;
            ErrorMessage e = new ErrorMessage(CommonLogic.QueryStringNativeInt("errormsg"));

            ErrorMsgLabel.Text       += Server.HtmlEncode(e.Message);
            pnlAccountUpdated.Visible = AccountUpdated;
            if (AccountUpdated)
            {
                if (!NewEmailAddressAllowed)
                {
                    lblAcctUpdateMsg.Text += CommonLogic.IIF(lblAcctUpdateMsg.Text.Trim() == "", "", "<br/>") + AppLogic.GetString("account.aspx.3", SkinID, ThisCustomer.LocaleSetting);
                }
                else
                {
                    lblAcctUpdateMsg.Text = CommonLogic.IIF(lblAcctUpdateMsg.Text.Trim() == "", "", "<br/>") + AppLogic.GetString("account.aspx.2", SkinID, ThisCustomer.LocaleSetting);
                }
            }

            OriginalEMail.Text            = ThisCustomer.EMail;
            btnContinueToCheckOut.Visible = phContinueCheckout.Visible = Checkout;

            if (ThisCustomer.PrimaryBillingAddressID == 0)
            {
                pnlBilling.Visible = false;
            }
            if (ThisCustomer.PrimaryShippingAddressID == 0)
            {
                pnlShipping.Visible = false;
            }

            lnkAddBillingAddress.NavigateUrl  = "address.aspx?add=true&addressType=Billing&Checkout=" + Checkout.ToString() + "&returnURL=" + Server.UrlEncode("account.aspx?checkout=" + Checkout.ToString());
            lnkAddBillingAddress.Text         = AppLogic.GetString("account.aspx.63", SkinID, ThisCustomer.LocaleSetting);
            lnkAddShippingAddress.NavigateUrl = "address.aspx?add=true&addressType=Shipping&Checkout=" + Checkout.ToString() + "&returnURL=" + Server.UrlEncode("account.aspx?checkout=" + Checkout.ToString());
            lnkAddShippingAddress.Text        = AppLogic.GetString("account.aspx.62", SkinID, ThisCustomer.LocaleSetting);

            litBillingAddress.Text = BillingAddress.DisplayHTML(Checkout);
            if (BillingAddress.PaymentMethodLastUsed.Length != 0)
            {
                litBillingAddress.Text += "<b>" + AppLogic.GetString("account.aspx.31", SkinID, ThisCustomer.LocaleSetting) + "</b><br/>";
                litBillingAddress.Text += BillingAddress.DisplayPaymentMethodInfo(ThisCustomer, BillingAddress.PaymentMethodLastUsed);
            }

            litShippingAddress.Text = ShippingAddress.DisplayHTML(Checkout);
            pnlOrderHistory.Visible = !Checkout;

            if (!String.IsNullOrEmpty(ShippingAddress.Address1))
            {
                litShipTeaser.Text = "(" + TextUtil.ClipText(ShippingAddress.Address1, 15) + ")";
            }

            if (!String.IsNullOrEmpty(BillingAddress.Address1))
            {
                litBillTeaser.Text = "(" + TextUtil.ClipText(BillingAddress.Address1, 15) + ")";
            }

            string[] TrxStates = { DB.SQuote(AppLogic.ro_TXStateAuthorized), DB.SQuote(AppLogic.ro_TXStateCaptured), DB.SQuote(AppLogic.ro_TXStatePending) };

            using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
            {
                con.Open();
                using (IDataReader rs = DB.GetRS(string.Format("Select OrderNumber, OrderDate, RecurringSubscriptionID, PaymentMethod, CardNumber, TransactionState, QuoteCheckout, ShippedOn, ShippedVIA, ShippingTrackingNumber, DownloadEMailSentOn, QuoteCheckout, PaymentMethod, " +
                                                               "OrderTotal, CouponType, isnull(CouponDiscountAmount, 0) CouponDiscountAmount, CustomerServiceNotes  from dbo.orders   with (NOLOCK)  where TransactionState in ({0}) and CustomerID={1} and ({2} = 0 or StoreID = {3}) order by OrderDate desc", String.Join(",", TrxStates),
                                                               ThisCustomer.CustomerID, CommonLogic.IIF(AppLogic.GlobalConfigBool("AllowCustomerFiltering") == true, 1, 0), AppLogic.StoreID()), con))
                {
                    orderhistorylist.DataSource = rs;
                    orderhistorylist.DataBind();
                }
            }

            accountaspx55.Visible = (orderhistorylist.Items.Count == 0);

            #region Vortx Mobile Modification
            pnlOrderHistory.Visible = !accountaspx55.Visible;
            #endregion

            ctrlAccount.Password        = String.Empty;
            ctrlAccount.PasswordConfirm = String.Empty;

            ClientScriptManager cs = Page.ClientScript;
            cs.RegisterClientScriptBlock(this.GetType(), Guid.NewGuid().ToString(), "function ReOrder(OrderNumber) {if(confirm('" + AppLogic.GetString("account.aspx.64", SkinID, ThisCustomer.LocaleSetting) + "')) {top.location.href='reorder.aspx?ordernumber='+OrderNumber;} }", true);
        }
Esempio n. 49
0
        public static void MetalHands_InitializationMethod()
        {
            Config = OptionsPanelHandler.Main.RegisterModOptions <IngameConfigMenu>();

            var GloveBlueprint = new MetalHandsMK1();

            GloveBlueprint.Patch();
            MetalHandsMK1TechType = GloveBlueprint.TechType;
            var GloveMK2Blueprint = new MetalHandsMK2();

            GloveMK2Blueprint.Patch();
            MetalHandsMK2TechType = GloveMK2Blueprint.TechType;
            var GRAVHANDBlueprint = new MetalHandsClawModule();

            GRAVHANDBlueprint.Patch();
            MetalHandsClawModuleTechType = GRAVHANDBlueprint.TechType;

            if (MetalHands.Config.Config_Hardcore == true)
            {
                BiomesToSpawnIn_pre = new List <LootDistributionData.BiomeData>
                {
                    new LootDistributionData.BiomeData()
                    {
                        biome       = BiomeType.BloodKelp_TechSite_Scatter,
                        count       = 1,
                        probability = 0.01f
                    },
                    new LootDistributionData.BiomeData()
                    {
                        biome       = BiomeType.CragField_Grass,
                        count       = 1,
                        probability = 0.01f
                    },
                    new LootDistributionData.BiomeData()
                    {
                        biome       = BiomeType.UnderwaterIslands_TechSite_Scatter,
                        count       = 1,
                        probability = 0.01f
                    },
                    new LootDistributionData.BiomeData()
                    {
                        biome       = BiomeType.SeaTreaderPath_TechSite_Scatter,
                        count       = 1,
                        probability = 0.02f
                    }
                };
            }
            else
            {
                BiomesToSpawnIn_pre = new List <LootDistributionData.BiomeData>
                {
                    new LootDistributionData.BiomeData()
                    {
                        biome       = BiomeType.GrassyPlateaus_Grass,
                        count       = 1,
                        probability = 0.01f
                    },
                    new LootDistributionData.BiomeData()
                    {
                        biome       = BiomeType.SparseReef_Techsite,
                        count       = 1,
                        probability = 0.02f
                    },
                    new LootDistributionData.BiomeData()
                    {
                        biome       = BiomeType.GrassyPlateaus_TechSite_Scattered,
                        count       = 1,
                        probability = 0.02f
                    },
                    new LootDistributionData.BiomeData()
                    {
                        biome       = BiomeType.CragField_Grass,
                        count       = 1,
                        probability = 0.02f
                    },
                    new LootDistributionData.BiomeData()
                    {
                        biome       = BiomeType.BloodKelp_TechSite_Scatter,
                        count       = 1,
                        probability = 0.02f
                    },
                    new LootDistributionData.BiomeData()
                    {
                        biome       = BiomeType.SeaTreaderPath_TechSite_Scatter,
                        count       = 1,
                        probability = 0.02f
                    },
                    new LootDistributionData.BiomeData()
                    {
                        biome       = BiomeType.UnderwaterIslands_TechSite_Scatter,
                        count       = 1,
                        probability = 0.02f
                    }
                };
            }

            Databox myDatabox = new Databox()
            {
                DataboxID            = "MetalHandDatabox",
                PrimaryDescription   = "Metal Hand Safety Glove Databox",
                SecondaryDescription = "Contains Crafting Tree for Improved Safety Gloves - Alterrra Copyright",
                BiomesToSpawnIn      = BiomesToSpawnIn_pre,
                TechTypeToUnlock     = MetalHands.MetalHandsMK1TechType
            };

            myDatabox.Patch();

            Logger.Log(Logger.Level.Debug, "MetalHands Initialization");
            Harmony harmony = new Harmony("MetalHands");

            harmony.PatchAll(Assembly.GetExecutingAssembly());
            Logger.Log(Logger.Level.Info, "MetalHands Patched");

            IncreasedChunkDrops_exist = QModServices.Main.ModPresent("IncreasedChunkDrops");
            if (IncreasedChunkDrops_exist)
            {
                Logger.Log(Logger.Level.Info, "MetalHands has detected Increased Chunk Drops");
                ErrorMessage.AddMessage("Attention MetalHands does not work properly with Increased Chunk Drops");
                //QModServices.Main.AddCriticalMessage("Attention MetalHands does not work properly with Increased Chunk Drops");
            }
            else
            {
                Logger.Log(Logger.Level.Info, "MetalHands has NOT detected Increased Chunk Drops");
            }

            //QModServices.Main.AddCriticalMessage("Warning the MetalHands Mod is in BETA Status !");
        }
Esempio n. 50
0
        /// <summary>
        /// Method to set quantity
        /// </summary>
        /// <param name="saleLine">Sale line</param>
        /// <param name="isAmount">Is amount</param>
        /// <param name="propaneValue">propane value</param>
        /// <param name="error">Error message</param>
        private void SetQuantity(ref Sale_Line saleLine, bool isAmount, decimal propaneValue, out ErrorMessage
                                 error)
        {
            error = new ErrorMessage();
            var offSet = _policyManager.LoadStoreInfo().OffSet;

            if (Conversion.Val(propaneValue) != 0)
            {
                if (!isAmount)
                {
                    if (Conversion.Val(propaneValue) > MaxVolumn)
                    {
                        //MsgBoxStyle temp_VbStyle = (int)MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation;
                        //Chaps_Main.DisplayMessage(this, (short)14, temp_VbStyle, null, (byte)0);
                        error = new ErrorMessage
                        {
                            MessageStyle = _resourceManager.CreateMessage(offSet, 48, 14, null, ExclamationOkMessageType)
                        };
                        return;
                    }
                    _saleLineManager.SetQuantity(ref saleLine, (float)(Conversion.Val(propaneValue)));

                    if (saleLine.Regular_Price > 0)
                    {
                        decimal amount = System.Convert.ToDecimal(saleLine.Regular_Price) * propaneValue;
                        _saleLineManager.SetAmount(ref saleLine, amount);
                    }
                }
                else //um="$"
                {
                    if (Conversion.Val(propaneValue) > MaxAmt)
                    {
                        //MsgBoxStyle temp_VbStyle2 = (int)MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation;
                        //Chaps_Main.DisplayMessage(this, (short)13, temp_VbStyle2, null, (byte)0);
                        error = new ErrorMessage
                        {
                            MessageStyle = _resourceManager.CreateMessage(offSet, 48, 13, null, ExclamationOkMessageType)
                        };
                        return;
                    }
                    else if (saleLine.Regular_Price > 0)
                    {
                        // SL_Prop.Quantity = float.Parse((Conversion.Val(txtValue.Text) / SL_Prop.Regular_Price).ToString("#####0.000"));
                        _saleLineManager.SetQuantity(ref saleLine, float.Parse((Conversion.Val(propaneValue) / saleLine.Regular_Price).ToString("#####0.000")));
                        _saleLineManager.SetAmount(ref saleLine, (decimal)(Conversion.Val(propaneValue)));

                        //string temp_Policy_Name = "FUEL_UM";
                        //lbQuantity.Text = "(" + System.Convert.ToString(SL_Prop.Quantity) + System.Convert.ToString(modPolicy.GetPol(temp_Policy_Name, SL_Prop)) + ")";
                    }
                }
            }
            else //if change to 0
            {
                error = new ErrorMessage
                {
                    MessageStyle = new MessageStyle
                    {
                        Message     = "Please Set Amount/Volume for Prepay Sale",
                        MessageType = MessageType.Critical
                    }
                };
            }
        }
Esempio n. 51
0
 public ErrorMessageEventArgs(ErrorMessage message)
 {
     Message = message;
 }
        /// <summary>
        /// タイプID、データIDを指定して可変DBのデータ名を取得する。
        /// </summary>
        /// <param name="dbKind">[NotNull] DB種別</param>
        /// <param name="typeId">タイプID</param>
        /// <param name="dataId">データID</param>
        /// <returns>
        ///     存在フラグとデータ名。
        ///     存在しない場合、専用の文字列。
        ///     dataId が変数アドレス値の場合、専用の文字列。
        /// </returns>
        /// <exception cref="ArgumentNullException">dbKindがnullの場合</exception>
        public (bool, string) GetDatabaseDataName(DBKind dbKind, int?typeId,
                                                  int dataId)
        {
            if (dbKind is null)
            {
                throw new ArgumentNullException(
                          ErrorMessage.NotNull(nameof(dbKind)));
            }

            if (typeId is null)
            {
                return(false, DatabaseDataNotFound);
            }

            if (dataId.IsVariableAddressSimpleCheck())
            {
                return(true, TargetIdVariableAddress);
            }

            var refer = GetDatabaseRefer(dbKind);

            var typeDescList = refer.TypeDescList;

            if (typeId < 0 || typeDescList.Count <= typeId)
            {
                return(false, DatabaseDataNotFound);
            }
            var typeDesc = typeDescList[typeId.Value];

            var dataDescList = typeDesc.DataDescList;

            if (dataId < 0 || dataDescList.Count <= dataId)
            {
                return(false, DatabaseDataNotFound);
            }

            var dataSettingType = typeDesc.DataSettingType;

            if (dataSettingType == DBDataSettingType.Manual)
            {
                return(true, dataDescList[dataId].DataName);
            }

            if (dataSettingType == DBDataSettingType.EqualBefore)
            {
                if (typeId == 0)
                {
                    return(false, DatabaseDataNotFound);
                }

                return(GetDatabaseDataName(dbKind, typeId - 1, dataId));
            }

            if (dataSettingType == DBDataSettingType.FirstStringData)
            {
                var targetItemIndex = typeDesc.DBItemSettingList
                                      .FindIndex(x => x.ItemType == DBItemType.String);

                if (targetItemIndex == -1)
                {
                    return(true, string.Empty);
                }
                return(true, typeDesc.DataDescList[dataId].ItemValueList[targetItemIndex].StringValue);
            }

            if (dataSettingType == DBDataSettingType.DesignatedType)
            {
                return(GetDatabaseDataName(typeDesc.DBKind, typeDesc.TypeId, dataId));
            }

            // 通常ここへは来ない
            throw new InvalidOperationException();
        }
Esempio n. 53
0
 private void _addSchemaOrValidationError(Exception e, string message) {
    string text = message.Substitute(e.Message);
    string details = null;
    if (e is XmlSchemaException) {
       var e1 = (XmlSchemaException)e;
       details = "at line {0}, position {1}.".Substitute(e1.LineNumber, e1.LinePosition);
    }
    var error = new ErrorMessage(Severity.Error, text, details);
    Errors.Add(error);
 }
Esempio n. 54
0
 public ErrorViewModel(string error)
 {
     Error = new ErrorMessage {
         Error = error
     };
 }
Esempio n. 55
0
        // process incoming messages
        public static byte[] RemoteMessaging_ReceiveMessage( string typeName, byte[] data, out string answerType )
        {
            answerType = null;

            TransferMessage inMsg = null;
            TransferMessage outMsg = null;

            Type type = Type.GetType( typeName );

            if ( type != null )
            {

                inMsg = TransferMessage.Decompress( data, type );

                if ( inMsg != null )
                {
                    // check message authentication
                    string authstatus = Authenticate(inMsg);

                    if(authstatus != null)
                    {
                        outMsg = new ErrorMessage( String.Format("Message request refused. {0}", authstatus) );
                    }
                    else
                    {

                        // if the message has been tagged for execution in the RunUO server thread
                        // then queue it up and wait for the response
                        if(inMsg.UseMainThread)
                        {
                            AddRequest(inMsg);
                            while(!ServerRequestProcessed(inMsg))
                            {
                                Thread.Sleep( 100 );
                            }
                            outMsg = ServerRequestResult(inMsg);
                            RemoveRequest(inMsg);
                        }
                        else
                        {

                            // otherwise just run it in the current thread
                            try
                            {
                                // process the message
                                outMsg = inMsg.ProcessMessage();
                            }
                            catch (Exception e)
                            {
                                outMsg = new ErrorMessage( String.Format("Error processing outgoing message. {0}",e.Message) );
                            }
                        }
                    }

                }
                else
                {
                    outMsg = new ErrorMessage( "Error decompressing incoming message. No zero arg msg constructor?" );
                }
            }
            else
            {
                outMsg = null;
            }

            if ( outMsg != null )
            {
                answerType = outMsg.GetType().FullName;
                byte[] result = outMsg.Compress();

                return result;
            }
            else
            {
                answerType = null;
                return null;
            }
        }
Esempio n. 56
0
        /// <summary>
        /// Method to delete prepay from POS
        /// </summary>
        /// <param name="pumpId">Pump Id</param>
        /// <param name="showMessage">Show message or not</param>
        /// <param name="error">Error</param>
        /// <returns>True or false</returns>
        public bool DeletePrepayFromFc(short pumpId, bool showMessage, out ErrorMessage error)
        {
            error = new ErrorMessage();
            var store  = CacheManager.GetStoreInfo();
            var offSet = store?.OffSet ?? 0;

            if (!Variables.Pump[pumpId].IsPrepay && !Variables.Pump[pumpId].IsHoldPrepay)
            {
                return(false);
            }

            if (!TCPAgent.Instance.IsConnected)
            {
                if (showMessage)
                {
                    error = new ErrorMessage()
                    {
                        MessageStyle = _resourceManager.CreateMessage(offSet, 38, 19, null, CriticalOkMessageType)
                    };
                }
                return(false);
            }

            var response  = "";
            var strRemain = "";

            Variables.IsWaiting = true;

            var    timeIn             = (float)DateAndTime.Timer;
            string tempCommandRenamed = "Rpr" + Strings.Right("0" + Convert.ToString(pumpId), 2);

            TCPAgent.Instance.Send_TCP(ref tempCommandRenamed, true);

            while (!(DateAndTime.Timer - timeIn > Variables.gPumps.CommunicationTimeOut))
            {
                var strBuffer = Convert.ToString(TCPAgent.Instance.NewPortReading);
                WriteToLogFile("TCPAgent.PortReading: " + strBuffer + " from waiting Rpr" + Strings.Right("00" + Convert.ToString(pumpId), 2));
                if (!string.IsNullOrEmpty(strBuffer))
                {
                    modStringPad.SplitResponse(strBuffer, "Rpr" + Strings.Right("00" + Convert.ToString(pumpId), 2), ref response, ref strRemain); //strBuffer<>""
                    if (!string.IsNullOrEmpty(response))                                                                                           //got what we are waiting
                    {
                        TCPAgent.Instance.PortReading = strRemain;                                                                                 //& ";" & TCPAgent.PortReading
                        WriteToLogFile("modify PortReading from Deleting prepay: " + strRemain);
                        break;
                    }
                }
                if (DateAndTime.Timer < timeIn)
                {
                    timeIn = (float)DateAndTime.Timer;
                }
                Variables.Sleep(100);
            }

            if (Strings.Left(response, 8) == "Rpr" + Strings.Right("00" + Convert.ToString(pumpId), 2) + "ERR")
            {
                if (showMessage)
                {
                    error = new ErrorMessage()
                    {
                        MessageStyle = _resourceManager.CreateMessage(offSet, 38, 19, null, CriticalOkMessageType)
                    };
                }
                Variables.IsWaiting = false;
                return(false);
            }

            if (Strings.Left(response, 7) != "Rpr" + Strings.Right("00" + Convert.ToString(pumpId), 2) + "OK") //response is not RprERR or RprOK
            {
                if (showMessage)
                {
                    error = new ErrorMessage()
                    {
                        MessageStyle = _resourceManager.CreateMessage(offSet, 38, 19, null, CriticalOkMessageType)
                    };
                }
                string tempCommandRenamed2 = "ENDPOS";
                TCPAgent.Instance.Send_TCP(ref tempCommandRenamed2, false);
                Variables.IsWaiting = false;
                return(false);
            }
            Variables.IsWaiting = false;
            return(true);
        }
Esempio n. 57
0
 public static void ShowErrorMessage(ErrorMessage errorOptions)
 {
     MessageBox.Show(ErrorMessages[errorOptions], "Error", MessageBoxButtons.OK);
 }
Esempio n. 58
0
        /// <summary>
        /// Method to basket undo
        /// </summary>
        /// <param name="pumpId">Pump Id</param>
        /// <param name="posId">Pos Id</param>
        /// <param name="gradeId">Grade Id</param>
        /// <param name="amount">Amount</param>
        /// <param name="up">Up</param>
        /// <param name="volume">Volume</param>
        /// <param name="stockCode">Stock code</param>
        /// <param name="mop">Mop</param>
        /// <param name="error">Error message</param>
        /// <returns>True or false</returns>
        public bool BasketUndo(short pumpId, short posId, short gradeId, float amount, float up, float volume,
                               string stockCode, byte mop, out ErrorMessage error)
        {
            float basketUndoTimeIn = 0;

            error = new ErrorMessage();
            if (!TCPAgent.Instance.IsConnected)
            {
                var store  = CacheManager.GetStoreInfo();
                var offSet = store?.OffSet ?? 0;
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, (38), 92, null, CriticalOkMessageType)
                };
                return(false);
            }


            if (DateAndTime.Timer - Variables.basketClick < Variables.basket_click_delay && (DateAndTime.Timer - Variables.basketClick) > 0)
            {
                return(false); //3 sec delay
            }

            if ((DateAndTime.Timer - basketUndoTimeIn < 2) && (DateAndTime.Timer - basketUndoTimeIn) > 0)
            {
                return(false);
            }

            if (basketUndoTimeIn > DateAndTime.Timer)
            {
                basketUndoTimeIn = 0; //reset on midnight
            }
            else
            {
                basketUndoTimeIn = (float)DateAndTime.Timer;
            }

            if (Variables.basketClick > DateAndTime.Timer)
            {
                Variables.basketClick = 0;
            }
            else
            {
                Variables.basketClick = (float)DateAndTime.Timer;
            }

            var response  = "";
            var strRemain = "";

            Variables.IsWaiting = true;
            string tempCommandRenamed = "Ist" + Strings.Right("0" + System.Convert.ToString(pumpId), 2) + System.Convert.ToString(mop) + System.Convert.ToString(posId) + Strings.Right("0000000" + System.Convert.ToString(amount * 1000), 8) + Strings.Right("00000000" + System.Convert.ToString(volume * 1000), 8);

            TCPAgent.Instance.Send_TCP(ref tempCommandRenamed, true);


            var timeIN = (float)DateAndTime.Timer;

            while (!(DateAndTime.Timer - timeIN > Variables.gPumps.CommunicationTimeOut))
            {
                var strBuffer = Convert.ToString(TCPAgent.Instance.NewPortReading);
                modStringPad.WriteToLogFile("TCPAgent.PortReading: " + strBuffer + " from waiting Ist" + Strings.Right("00" + System.Convert.ToString(pumpId), 2));
                if (!string.IsNullOrEmpty(strBuffer))
                {
                    modStringPad.SplitResponse(strBuffer, "Ist" + Strings.Right("00" + Convert.ToString(pumpId), 2), ref response, ref strRemain); //strBuffer<>""
                    if (!string.IsNullOrEmpty(response))                                                                                           //got what we are waiting
                    {
                        TCPAgent.Instance.PortReading = strRemain;                                                                                 //& ";" & TCPAgent.PortReading
                        WriteToLogFile("modify PortReading from BasketUndo: " + strRemain);
                        break;
                    }
                }
                if (DateAndTime.Timer < timeIN)
                {
                    timeIN = (float)DateAndTime.Timer;
                }
                Variables.Sleep(100);
            }
            if (Strings.Left(response, 8) == "Ist" + Strings.Right("00" + Convert.ToString(pumpId), 2) + "ERR")
            {
                Variables.IsWaiting = false;
                return(false);
            }

            if (Strings.Left(response, 7) != "Ist" + Strings.Right("00" + System.Convert.ToString(pumpId), 2) + "OK") //response is not IstERR or IstOK
            {
                string tempCommandRenamed2 = "ENDPOS";
                TCPAgent.Instance.Send_TCP(ref tempCommandRenamed2, true);
                Variables.IsWaiting = false;
                return(false);
            }

            Variables.gBasket[pumpId].AmountCurrent  = amount;
            Variables.gBasket[pumpId].VolumeCurrent  = volume;
            Variables.gBasket[pumpId].UPCurrent      = up;
            Variables.gBasket[pumpId].gradeIDCurr    = gradeId;
            Variables.gBasket[pumpId].PosIDCurr      = posId;
            Variables.gBasket[pumpId].CurrentFilled  = true;
            Variables.gBasket[pumpId].currMOP        = mop;
            Variables.gBasket[pumpId].Stock_Code_Cur = stockCode;
            Variables.IsWaiting = false;
            return(true);
        }
Esempio n. 59
0
        private void HandleError(ErrorMessage errorMessage)
        {
            _logger.Warning(errorMessage.LogMessage);

            _shell?.QueueErrorDialog(errorMessage);
        }
Esempio n. 60
0
        /// <summary>
        /// Create a new crash data model object and insert it into the database
        /// </summary>
        /// <param name="description"></param>
        /// <returns></returns>
        private Crash CreateCrash(CrashDescription description)
        {
            var newCrash = new Crash
            {
                Branch            = description.BranchName,
                BaseDir           = description.BaseDir,
                BuildVersion      = description.EngineVersion,
                EngineVersion     = description.BuildVersion,
                ChangeListVersion = description.BuiltFromCL.ToString(),
                CommandLine       = description.CommandLine,
                EngineMode        = description.EngineMode,
                ComputerName      = description.MachineGuid
            };

            //if there's a valid username assign the associated UserNameId else use "anonymous".
            var userName = (!string.IsNullOrEmpty(description.UserName)) ? description.UserName : UserNameAnonymous;
            var user     = _unitOfWork.UserRepository.GetByUserName(userName);

            if (user != null)
            {
                newCrash.UserNameId = user.Id;
                newCrash.UserName   = user.UserName;
            }
            else
            {
                newCrash.User = new User()
                {
                    UserName = description.UserName, UserGroupId = 5
                };
            }

            //If there's a valid EpicAccountId assign that.
            if (!string.IsNullOrEmpty(description.EpicAccountId))
            {
                newCrash.EpicAccountId = description.EpicAccountId;
            }

            newCrash.Description = "";
            if (description.UserDescription != null)
            {
                newCrash.Description = string.Join(Environment.NewLine, description.UserDescription);
            }

            newCrash.EngineMode   = description.EngineMode;
            newCrash.GameName     = description.GameName;
            newCrash.LanguageExt  = description.Language;    //Converted by the crash process.
            newCrash.PlatformName = description.Platform;

            if (description.ErrorMessage != null)
            {
                newCrash.Summary = string.Join("\n", description.ErrorMessage);
            }

            if (description.CallStack != null)
            {
                newCrash.RawCallStack = string.Join("\n", description.CallStack);
            }

            if (description.SourceContext != null)
            {
                newCrash.SourceContext = string.Join("\n", description.SourceContext);
            }

            newCrash.TimeOfCrash = description.TimeofCrash;
            newCrash.Processed   = description.bAllowToBeContacted;

            newCrash.Jira            = "";
            newCrash.FixedChangeList = "";
            newCrash.ProcessFailed   = description.bProcessorFailed;

            // Set the crash type
            newCrash.CrashType = 1;

            //if we have a crash type set the crash type
            if (!string.IsNullOrEmpty(description.CrashType))
            {
                switch (description.CrashType.ToLower())
                {
                case "crash":
                    newCrash.CrashType = 1;
                    break;

                case "assert":
                    newCrash.CrashType = 2;
                    break;

                case "ensure":
                    newCrash.CrashType = 3;
                    break;

                case "":
                case null:
                default:
                    newCrash.CrashType = 1;
                    break;
                }
            }
            else     //else fall back to the old behavior and try to determine type from RawCallStack
            {
                if (newCrash.RawCallStack != null)
                {
                    if (newCrash.RawCallStack.Contains("FDebug::AssertFailed"))
                    {
                        newCrash.CrashType = 2;
                    }
                    else if (newCrash.RawCallStack.Contains("FDebug::Ensure"))
                    {
                        newCrash.CrashType = 3;
                    }
                    else if (newCrash.RawCallStack.Contains("FDebug::OptionallyLogFormattedEnsureMessageReturningFalse"))
                    {
                        newCrash.CrashType = 3;
                    }
                    else if (newCrash.RawCallStack.Contains("NewReportEnsure"))
                    {
                        newCrash.CrashType = 3;
                    }
                }
            }

            // As we're adding it, the status is always new
            newCrash.Status           = "New";
            newCrash.UserActivityHint = description.UserActivityHint;
            try
            {
                BuildPattern(newCrash);
            }
            catch (Exception ex)
            {
                FLogger.Global.WriteException("Error in Create Crash Build Pattern Method");
                throw;
            }

            if (newCrash.CommandLine == null)
            {
                newCrash.CommandLine = "";
            }

            _unitOfWork.Dispose();
            _unitOfWork = new UnitOfWork(new CrashReportEntities());
            var callStackRepository = _unitOfWork.CallstackRepository;

            try
            {
                var crashRepo = _unitOfWork.CrashRepository;
                //if we don't have any callstack data then insert the crash and return
                if (string.IsNullOrEmpty(newCrash.Pattern))
                {
                    crashRepo.Save(newCrash);
                    _unitOfWork.Save();
                    return(newCrash);
                }

                //If this isn't a new pattern then link it to our crash data model
                if (callStackRepository.Any(data => data.Pattern == newCrash.Pattern))
                {
                    var callstackPattern = callStackRepository.First(data => data.Pattern == newCrash.Pattern);
                    newCrash.PatternId = callstackPattern.id;
                }
                else
                {
                    //if this is a new callstack pattern then insert into data model and create a new bugg.
                    var callstackPattern = new CallStackPattern {
                        Pattern = newCrash.Pattern
                    };
                    callStackRepository.Save(callstackPattern);
                    _unitOfWork.Save();
                    newCrash.PatternId = callstackPattern.id;
                }

                //Mask out the line number and File path from our error message.
                var errorMessageString = description.ErrorMessage != null?String.Join("", description.ErrorMessage) : "";

                //Create our masking regular expressions
                var fileRegex = new Regex(@"(\[File:).*?(])"); //Match the filename out the file name
                var lineRegex = new Regex(@"(\[Line:).*?(])"); //Match the line no.

                /**
                 * Regex to match ints of two characters or longer
                 * First term ((?<=\s)|(-)) : Positive look behind, match if preceeded by whitespace or if first character is '-'
                 * Second term (\d{3,}) match three or more decimal chracters in a row.
                 * Third term (?=(\s|$)) positive look ahead match if followed by whitespace or end of line/file.
                 */
                var intRegex = new Regex(@"-?\d{3,}");

                /**
                 * Regular expression for masking out floats
                 */
                var floatRegex = new Regex(@"-?\d+\.\d+");

                /**
                 * Regular expression for masking out hexadecimal numbers
                 */
                var hexRegex = new Regex(@"0x[\da-fA-F]+");

                //mask out terms matches by our regex's
                var trimmedError = fileRegex.Replace(errorMessageString, "");
                trimmedError = lineRegex.Replace(trimmedError, "");
                trimmedError = floatRegex.Replace(trimmedError, "");
                trimmedError = hexRegex.Replace(trimmedError, "");
                trimmedError = intRegex.Replace(trimmedError, "");
                if (trimmedError.Length > 450)
                {
                    trimmedError = trimmedError.Substring(0, 450);//error message is used as an index - trim to max index length
                }
                //Check to see if the masked error message is unique
                ErrorMessage errorMessage = null;
                if (_unitOfWork.ErrorMessageRepository.Any(data => data.Message.ToLower().Contains(trimmedError.ToLower())))
                {
                    errorMessage =
                        _unitOfWork.ErrorMessageRepository.First(data => data.Message.ToLower().Contains(trimmedError.ToLower()));
                }
                else
                {
                    //if it's a new message then add it to the database.
                    errorMessage = new ErrorMessage()
                    {
                        Message = trimmedError
                    };
                    _unitOfWork.ErrorMessageRepository.Save(errorMessage);
                    _unitOfWork.Save();
                }

                //Check for an existing bugg with this pattern and error message / no error message
                if (_unitOfWork.BuggRepository.Any(data =>
                                                   (data.PatternId == newCrash.PatternId) && (data.ErrorMessageId == errorMessage.Id || data.ErrorMessageId == null)))
                {
                    //if a bugg exists for this pattern update the bugg data
                    var bugg = _unitOfWork.BuggRepository.First(data => data.PatternId == newCrash.PatternId);
                    bugg.PatternId = newCrash.PatternId;

                    bugg.CrashType      = newCrash.CrashType;
                    bugg.ErrorMessageId = errorMessage.Id;

                    //also update the bugg data while we're here
                    bugg.TimeOfLastCrash = newCrash.TimeOfCrash;

                    if (String.Compare(newCrash.BuildVersion, bugg.BuildVersion,
                                       StringComparison.Ordinal) != 1)
                    {
                        bugg.BuildVersion = newCrash.BuildVersion;
                    }

                    _unitOfWork.Save();

                    //if a bugg exists update this crash from the bugg
                    //buggs are authoritative in this case
                    newCrash.BuggId          = bugg.Id;
                    newCrash.Jira            = bugg.TTPID;
                    newCrash.FixedChangeList = bugg.FixedChangeList;
                    newCrash.Status          = bugg.Status;
                    newCrash.Buggs.Add(bugg);
                    _unitOfWork.CrashRepository.Save(newCrash);
                    _unitOfWork.Save();
                }
                else
                {
                    //if there's no bugg for this pattern create a new bugg and insert into the data store.
                    var bugg = new Bugg();
                    bugg.TimeOfFirstCrash       = newCrash.TimeOfCrash;
                    bugg.TimeOfLastCrash        = newCrash.TimeOfCrash;
                    bugg.TTPID                  = newCrash.Jira;
                    bugg.Pattern                = newCrash.Pattern;
                    bugg.PatternId              = newCrash.PatternId;
                    bugg.NumberOfCrashes        = 1;
                    bugg.NumberOfUsers          = 1;
                    bugg.NumberOfUniqueMachines = 1;
                    bugg.BuildVersion           = newCrash.BuildVersion;
                    bugg.CrashType              = newCrash.CrashType;
                    bugg.Status                 = newCrash.Status;
                    bugg.FixedChangeList        = newCrash.FixedChangeList;
                    bugg.ErrorMessageId         = errorMessage.Id;
                    newCrash.Bugg               = bugg;
                    newCrash.Buggs.Add(bugg);
                    _unitOfWork.BuggRepository.Save(bugg);
                    _unitOfWork.CrashRepository.Save(newCrash);
                    _unitOfWork.Save();
                }
            }
            catch (DbEntityValidationException dbentEx)
            {
                var messageBuilder = new StringBuilder();
                messageBuilder.AppendLine("Db Entity Validation Exception Exception was:");
                messageBuilder.AppendLine(dbentEx.ToString());

                var innerEx = dbentEx.InnerException;
                while (innerEx != null)
                {
                    messageBuilder.AppendLine("Inner Exception : " + innerEx.Message);
                    innerEx = innerEx.InnerException;
                }

                if (dbentEx.EntityValidationErrors != null)
                {
                    messageBuilder.AppendLine("Validation Errors : ");
                    foreach (var valErr in dbentEx.EntityValidationErrors)
                    {
                        messageBuilder.AppendLine(valErr.ValidationErrors.Select(data => data.ErrorMessage).Aggregate((current, next) => current + "; /n" + next));
                    }
                }
                FLogger.Global.WriteException(messageBuilder.ToString());
                _slackWriter.Write("Create Crash Exception : " + messageBuilder.ToString());
                throw;
            }
            catch (Exception ex)
            {
                var messageBuilder = new StringBuilder();
                messageBuilder.AppendLine("Create Crash Exception : ");
                messageBuilder.AppendLine(ex.Message.ToString());
                var innerEx = ex.InnerException;
                while (innerEx != null)
                {
                    messageBuilder.AppendLine("Inner Exception : " + innerEx.Message);
                    innerEx = innerEx.InnerException;
                }

                FLogger.Global.WriteException("Create Crash Exception : " +
                                              messageBuilder.ToString());
                _slackWriter.Write("Create Crash Exception : " + messageBuilder.ToString());
                throw;
            }

            return(newCrash);
        }