Summary description for ErrorHandling
Exemplo n.º 1
0
 private Translation(ResourceManager resourceManager, string key, ErrorHandling errorHandling = ErrorHandling.Inherit)
 {
     this.resourceManager = resourceManager;
     this.key = key;
     this.errorHandling = errorHandling;
     this.cachedTranslation = new CachedTranslation(this);
 }
Exemplo n.º 2
0
        /// <summary>
        /// Translation.GetOrCreate(Properties.Resources.ResourceManager, nameof(Properties.Resources.SomeKey))
        /// </summary>
        /// <param name="resourceManager">
        /// The resourcemanager with the key
        /// </param>
        /// <param name="key">
        /// The key to translate
        /// </param>
        /// <param name="errorHandling">Specifies how errors are handled.</param>
        /// <returns>A <see cref="Translation"/> that notifies when <see cref="Translator.CurrentCulture"/> changes</returns>
        public static Translation GetOrCreate(ResourceManager resourceManager, string key, ErrorHandling errorHandling = ErrorHandling.Inherit)
        {
            Ensure.NotNull(resourceManager, nameof(resourceManager));
            Ensure.NotNull(key, nameof(key));

            var rmk = new ResourceManagerAndKey(resourceManager, key, errorHandling);
            return Cache.GetOrAdd(rmk, x => new Translation(x.ResourceManager, x.Key, errorHandling));
        }
        protected override void RefreshData()
        {
            Action completeRefreshAction = new Action(delegate {
                selectedUsers = FetchSelectedUsers();
                Content.Refresh();
            });

            Content.ExecuteActionAsync(completeRefreshAction, new Action <Exception>((Exception ex) => ErrorHandling.ShowErrorDialog(this, "Refresh failed.", ex)));
        }
Exemplo n.º 4
0
        private static bool CheckSingleConstraint(CSemanticChecker checker, ErrorHandling errHandling, Symbol symErr, TypeParameterType var, CType arg, TypeArray typeArgsCls, TypeArray typeArgsMeth, CheckConstraintsFlags flags)
        {
            bool fReportErrors = 0 == (flags & CheckConstraintsFlags.NoErrors);

            if (arg.IsOpenTypePlaceholderType())
            {
                return(true);
            }

            if (arg.IsErrorType())
            {
                // Error should have been reported previously.
                return(false);
            }

            if (checker.CheckBogus(arg))
            {
                if (fReportErrors)
                {
                    errHandling.ErrorRef(ErrorCode.ERR_BogusType, arg);
                }

                return(false);
            }

            if (arg.IsPointerType())
            {
                if (fReportErrors)
                {
                    errHandling.Error(ErrorCode.ERR_BadTypeArgument, arg);
                }

                return(false);
            }

            if (arg.isStaticClass())
            {
                if (fReportErrors)
                {
                    checker.ReportStaticClassError(null, arg, ErrorCode.ERR_GenericArgIsStaticClass);
                }

                return(false);
            }

            bool fError = false;

            if (var.HasRefConstraint() && !arg.IsRefType())
            {
                if (fReportErrors)
                {
                    errHandling.ErrorRef(ErrorCode.ERR_RefConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg);
                }

                fError = true;
            }

            TypeArray bnds     = checker.GetSymbolLoader().GetTypeManager().SubstTypeArray(var.GetBounds(), typeArgsCls, typeArgsMeth);
            int       itypeMin = 0;

            if (var.HasValConstraint())
            {
                // If we have a type variable that is constrained to a value type, then we
                // want to check if its a nullable type, so that we can report the
                // constraint error below. In order to do this however, we need to check
                // that either the type arg is not a value type, or it is a nullable type.
                //
                // To check whether or not its a nullable type, we need to get the resolved
                // bound from the type argument and check against that.

                bool bIsValueType = arg.IsValType();
                bool bIsNullable  = arg.IsNullableType();
                if (bIsValueType && arg.IsTypeParameterType())
                {
                    TypeArray pArgBnds = arg.AsTypeParameterType().GetBounds();
                    if (pArgBnds.Count > 0)
                    {
                        bIsNullable = pArgBnds[0].IsNullableType();
                    }
                }

                if (!bIsValueType || bIsNullable)
                {
                    if (fReportErrors)
                    {
                        errHandling.ErrorRef(ErrorCode.ERR_ValConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg);
                    }

                    fError = true;
                }

                // Since FValCon() is set it is redundant to check System.ValueType as well.
                if (bnds.Count != 0 && bnds[0].isPredefType(PredefinedType.PT_VALUE))
                {
                    itypeMin = 1;
                }
            }

            for (int j = itypeMin; j < bnds.Count; j++)
            {
                CType typeBnd = bnds[j];
                if (!SatisfiesBound(checker, arg, typeBnd))
                {
                    if (fReportErrors)
                    {
                        // The bound isn't satisfied because of a constraint type. Explain to the user why not.
                        // There are 4 main cases, based on the type of the supplied type argument:
                        //  - reference type, or type parameter known to be a reference type
                        //  - nullable type, from which there is a boxing conversion to the constraint type(see below for details)
                        //  - type variable
                        //  - value type
                        // These cases are broken out because: a) The sets of conversions which can be used
                        // for constraint satisfaction is different based on the type argument supplied,
                        // and b) Nullable is one funky type, and user's can use all the help they can get
                        // when using it.
                        ErrorCode error;
                        if (arg.IsRefType())
                        {
                            // A reference type can only satisfy bounds to types
                            // to which they have an implicit reference conversion
                            error = ErrorCode.ERR_GenericConstraintNotSatisfiedRefType;
                        }
                        else if (arg.IsNullableType() && checker.GetSymbolLoader().HasBaseConversion(arg.AsNullableType().GetUnderlyingType(), typeBnd))    // This is inlining FBoxingConv
                        {
                            // nullable types do not satisfy bounds to every type that they are boxable to
                            // They only satisfy bounds of object and ValueType
                            if (typeBnd.isPredefType(PredefinedType.PT_ENUM) || arg.AsNullableType().GetUnderlyingType() == typeBnd)
                            {
                                // Nullable types don't satisfy bounds of EnumType, or the underlying type of the enum
                                // even though the conversion from Nullable to these types is a boxing conversion
                                // This is a rare case, because these bounds can never be directly stated ...
                                // These bounds can only occur when one type paramter is constrained to a second type parameter
                                // and the second type parameter is instantiated with Enum or the underlying type of the first type
                                // parameter
                                error = ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum;
                            }
                            else
                            {
                                // Nullable types don't satisfy the bounds of any interface type
                                // even when there is a boxing conversion from the Nullable type to
                                // the interface type. This will be a relatively common scenario
                                // so we cal it out separately from the previous case.
                                Debug.Assert(typeBnd.isInterfaceType());
                                error = ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface;
                            }
                        }
                        else if (arg.IsTypeParameterType())
                        {
                            // Type variables can satisfy bounds through boxing and type variable conversions
                            Debug.Assert(!arg.IsRefType());
                            error = ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar;
                        }
                        else
                        {
                            // Value types can only satisfy bounds through boxing conversions.
                            // Note that the exceptional case of Nullable types and boxing is handled above.
                            error = ErrorCode.ERR_GenericConstraintNotSatisfiedValType;
                        }
                        errHandling.Error(error, new ErrArgRef(symErr), new ErrArg(typeBnd, ErrArgFlags.Unique), var, new ErrArgRef(arg, ErrArgFlags.Unique));
                    }
                    fError = true;
                }
            }

            // Check the newable constraint.
            if (!var.HasNewConstraint() || arg.IsValType())
            {
                return(!fError);
            }

            if (arg.isClassType())
            {
                AggregateSymbol agg = arg.AsAggregateType().getAggregate();

                // Due to late binding nature of IDE created symbols, the AggregateSymbol might not
                // have all the information necessary yet, if it is not fully bound.
                // by calling LookupAggMember, it will ensure that we will update all the
                // information necessary at least for the given method.
                checker.GetSymbolLoader().LookupAggMember(NameManager.GetPredefinedName(PredefinedName.PN_CTOR), agg, symbmask_t.MASK_ALL);

                if (agg.HasPubNoArgCtor() && !agg.IsAbstract())
                {
                    return(!fError);
                }
            }
            else if (arg.IsTypeParameterType() && arg.AsTypeParameterType().HasNewConstraint())
            {
                return(!fError);
            }

            if (fReportErrors)
            {
                errHandling.ErrorRef(ErrorCode.ERR_NewConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg);
            }

            return(false);
        }
Exemplo n.º 5
0
 public ImportEngine(ErrorHandling errorHandling)
 {
     _errorHandling = errorHandling;
 }
Exemplo n.º 6
0
 /// <summary>Call like this: Translate.Key(nameof(Resources.Saved_file__0_)).</summary>
 /// <param name="key">A key in Properties.Resources</param>
 /// <param name="errorHandling">How to handle translation errors like missing key or culture.</param>
 /// <returns>A translation for the key.</returns>
 public static string Key(string key, ErrorHandling errorHandling = ErrorHandling.ReturnErrorInfoPreserveNeutral)
 {
     return(TranslationFor(key, errorHandling).Translated);
 }
Exemplo n.º 7
0
        private string ParseBinding <T>(string binding, string comment, string filePath, IEnumerable <T> entries1, IEnumerable <T> entries2, bool allowAutoId = true, ushort maxId = ushort.MaxValue, List <string> usedIds = null) where T : IInstallable
        {
            if (IsBinding(binding))
            {
                string originalBinding = binding;
                string Path            = String.Empty;
                int    ID           = -1;
                int    defaultValue = 0;

                List <BindingValue> bindings = ProcessBinding(binding, comment, originalBinding);
                bindings = ValidateBindings(bindings, comment, originalBinding);

                ErrorHandling errorHandler = ErrorHandling.Stop;
                string        formating    = "0";
                int           increment    = 0;

                foreach (var b in bindings)
                {
                    switch (b.Function)
                    {
                    case Function.Format:
                        formating = b.GetArgument1();
                        break;

                    case Function.SetAlias:
                        Aliases.Add(new AliasValue()
                        {
                            ID = ID + increment, Alias = b.GetArgument1()
                        });
                        break;

                    case Function.AliasLink:
                        ID = GetAliasId(b.GetArgument1(), comment);
                        break;

                    case Function.SkillID1:
                    {
                        CusSkillType skillType = GetSkillType(b.GetArgument2());
                        ID = GetSkillId(CusIdType.ID1, skillType, b.GetArgument1());
                        break;
                    }

                    case Function.SkillID2:
                    {
                        CusSkillType skillType = GetSkillType(b.GetArgument2());
                        ID = GetSkillId(CusIdType.ID2, skillType, b.GetArgument1());
                        break;
                    }

                    case Function.CharaID:
                        ID = GetCharaId(b.GetArgument1());
                        break;

                    case Function.AutoID:
                        if (!allowAutoId)
                        {
                            throw new Exception(String.Format("The AutoID binding function is not available for this value. ({0})", comment));
                        }

                        int minIndex = (!String.IsNullOrWhiteSpace(b.GetArgument1())) ? int.Parse(b.GetArgument1()) : 0;
                        int maxIndex = (!String.IsNullOrWhiteSpace(b.GetArgument2())) ? int.Parse(b.GetArgument2()) : maxId;
                        if (maxIndex > maxId)
                        {
                            maxIndex = maxId;                       //If maxIndex (declared in binding) is greater than maxId (declared on Property), then set maxIndex to maxId (which is the highest possible value)
                        }
                        int nextID = GetUnusedIndex(entries1, entries2, minIndex, maxIndex, usedIds);

                        if (nextID == NullTokenInt && errorHandler == ErrorHandling.Stop)
                        {
                            GeneralInfo.SpecialFailState = GeneralInfo.SpecialFailStates.AutoIdBindingFailed;
                            throw new Exception(String.Format("An ID could not be allocated in {2}. Install failed. \n\nBinding: {1}\nProperty: {0}", comment, binding, filePath));
                        }

                        ID = nextID;
                        break;

                    case Function.Error:
                        errorHandler = b.GetErrorHandlingType();
                        break;

                    case Function.DefaultValue:
                        defaultValue = int.Parse(b.GetArgument1());
                        break;

                    case Function.X2MSkillID1:
                    {
                        CusSkillType skillType = GetSkillType(b.GetArgument2());
                        int          id1       = _X2MHelper.GetX2MSkillID1(b.GetArgument1(), skillType);

                        if (id1 == NullTokenInt && errorHandler == ErrorHandling.Stop)
                        {
                            GeneralInfo.SpecialFailState = GeneralInfo.SpecialFailStates.X2MNotFound;
                            throw new Exception(String.Format("Required X2M skill not found. Install failed. \nBinding: {1}\n({0})", comment, binding, filePath));
                        }

                        ID = id1;
                        break;
                    }

                    case Function.X2MSkillID2:
                    {
                        CusSkillType skillType = GetSkillType(b.GetArgument2());
                        int          id2       = _X2MHelper.GetX2MSkillID2(b.GetArgument1(), skillType);

                        if (id2 == NullTokenInt && errorHandler == ErrorHandling.Stop)
                        {
                            GeneralInfo.SpecialFailState = GeneralInfo.SpecialFailStates.X2MNotFound;
                            throw new Exception(String.Format("Required X2M skill not found. Install failed. \nBinding: {1}\n({0})", comment, binding, filePath));
                        }

                        ID = id2;
                        break;
                    }

                    case Function.AutoPartSet:
                    {
                        if (!allowAutoId)
                        {
                            throw new Exception(String.Format("The AutoPartSet binding function is not available for this value. ({0})", comment));
                        }
                        int min    = (b.HasArgument(1)) ? int.Parse(b.GetArgument1()) : 0;
                        int max    = (b.HasArgument(2)) ? int.Parse(b.GetArgument2()) : 999;
                        int nextId = GetFreePartSet(min, max);

                        if (nextId == NullTokenInt && errorHandler == ErrorHandling.Stop)
                        {
                            GeneralInfo.SpecialFailState = GeneralInfo.SpecialFailStates.AutoIdBindingFailed;
                            throw new Exception(String.Format("A PartSet ID could not be allocated in {2}. Install failed. \n\nBinding: {1}\nProperty: {0}", comment, binding, filePath));
                        }

                        ID = nextId;
                    }
                    break;

                    case Function.Increment:
                        if (!b.HasArgument())
                        {
                            throw new Exception($"No argument found on Increment binding!");
                        }

                        if (!int.TryParse(b.GetArgument1(), out increment))
                        {
                            throw new Exception($"Error while parsing the argument on Increment binding. (Binding: {binding})");
                        }

                        break;

                    case Function.X2MSkillPath:

                    {
                        CusSkillType skillType    = GetSkillType(b.GetArgument2());
                        string       x2mSkillPath = _X2MHelper.GetX2MSkillPath(b.GetArgument1(), skillType);

                        if (x2mSkillPath == NullTokenStr && errorHandler == ErrorHandling.Stop)
                        {
                            GeneralInfo.SpecialFailState = GeneralInfo.SpecialFailStates.X2MNotFound;
                            throw new Exception(String.Format("Required X2M skill not found. Install failed. \nBinding: {1}\n({0})", comment, binding, filePath));
                        }

                        Path = x2mSkillPath;
                        break;
                    }
                    }
                }

                //Generic error handling code
                if (ID == NullTokenInt && errorHandler == ErrorHandling.Stop)
                {
                    GeneralInfo.SpecialFailState = GeneralInfo.SpecialFailStates.IdBindingFailed;
                    throw new Exception(String.Format("An ID could not be assigned according to the binding. Install failed. \nBinding: {1}\n({0})", comment, binding));
                }
                else if (ID == NullTokenInt && errorHandler == ErrorHandling.UseDefaultValue)
                {
                    ID = defaultValue;
                }
                // Path wasn't used
                if (Path == String.Empty)
                {
                    return(ApplyFormatting(ID + increment, formating));
                }
                else  //a special case for returning a Path to use in installPath
                {
                    return(Path);
                }
            }
            else
            {
                //Not a binding.
                return(binding);
            }
        }
Exemplo n.º 8
0
        //Add button action
        private void AddButton_Click(object sender, EventArgs e)
        {
            string firstName   = NameText.Text;
            string lastName    = SurnameText.Text;
            string information = InformationText.Text;
            string text        = "photo_url";

            using (var w = new WebClient())
            {
                string clientID = "d4a165a802843b0";
                w.Headers.Add("Authorization", "Client-ID " + clientID);
                var values = new NameValueCollection
                {
                    { "image", Convert.ToBase64String(File.ReadAllBytes(@"Image1.jpg")) }
                };

                byte[] response = w.UploadValues("https://api.imgur.com/3/upload.xml", values);
                var    xx       = XDocument.Load(new MemoryStream(response)).ToString();
                // MessageBox.Show(xx);
            }

            if (errorcode1 == 0 || errorcode2 == 0 || string.IsNullOrWhiteSpace(firstName) || string.IsNullOrWhiteSpace(lastName) || string.IsNullOrWhiteSpace(information))
            {
                ErrorHandling.Show_Inserting_Error();
            }
            else
            {
                DatabaseInfo data = LazyData.Value;
                //data.Myevent += delegate (object ) { }
                var  connection = data.GetConfigInfo();
                User user       = new User(firstName, lastName, information);


                WebService.WebService service = new WebService.WebService();
                //service.InsertRow(user, connection);
                data.InsertRow(user, connection);// Inesrt row to table
                var Users = new List <User> {
                };
                //service.GetDataFromDatabase(Users, connection);
                data.GetDataFromDatabase(Users, connection);// Read information to Collectionion
                UsersInfo userPhoto   = new UsersInfo(firstName, lastName, text);
                var       UsersPhotos = new List <UsersInfo> {
                };
                data.GetDataFromDatabase(Users, connection);        // Read photo information to Collection
                var OrderedUsers = Users.OrderBy(p => p.FirstName); // Linq ordering by name ascending
                //var JoinedUsers = data.GroupJoinCollections(Users, UsersPhotos);
                var JoinedUsers = from p in OrderedUsers
                                  join c in UsersPhotos
                                  on p.FirstName equals c.FirstName
                                  select new
                {
                    PersonName    = p.FirstName,
                    PersonSurname = c.LastName,
                    PersonInfo    = p.Information,
                    PersonPhoto   = c.Text
                };


                NameText.Text        = String.Empty;
                SurnameText.Text     = String.Empty;
                InformationText.Text = String.Empty;
                ImageView.Image      = null;
                icon1.Image          = null;
                icon2.Image          = null;
            }
        }
Exemplo n.º 9
0
        public bool CreateOrUpdate(PlayerDashboardExt model, ref string Msg, Controller ctrl)
        {
            bool status = true;

            if (model.PlayerDashboardID == 0)
            {
                try
                {
                    string RandomPassword = System.Web.Security.Membership.GeneratePassword(6, 1);
                    model.DashboardPassword = SecurityUtils.EncryptText(RandomPassword);

                    //TODO: Map to DB Object
                    var dbmodel = Map(model);
                    //TODO: Save DB Changes and Set the Return Primary Key ID
                    db.PlayerDashboard.Add(dbmodel);
                    db.SaveChanges();
                    //TOD: Add to Audit Log
                    AuditLog(ctrl, AuditAction.Create, model, null);
                }
                catch (Exception ex)
                {
                    Msg    = ErrorHandling.HandleException(ex);
                    status = false;
                }
            }
            else
            {
                try
                {
                    var dbmodel = db.PlayerDashboard.Include("Players").FirstOrDefault(p => p.PlayerDashboardID == model.PlayerDashboardID);

                    var proceedToSave = true;
                    //Validate Dashboard URL
                    ValidateDashboardURL(dbmodel.DashboardURL, model.DashboardURL, ref Msg, ref status);

                    if (!string.IsNullOrEmpty(model.DashboardPassword))
                    {
                        if (SecurityUtils.DecryptCypher(dbmodel.DashboardPassword).Equals(model.DashboardPassword))
                        {
                            status = false;
                            Msg    = "New Password shouldn't be same as your previous Password";
                        }
                    }
                    else
                    {
                        model.DashboardPassword = SecurityUtils.DecryptCypher(dbmodel.DashboardPassword);
                    }

                    proceedToSave = status;

                    if (proceedToSave)
                    {
                        var ForAuditLog = Map(dbmodel);
                        //TODO: Map to DB Object
                        MapUpdate(ref dbmodel, model);
                        //TODO: Update DB Changes
                        db.SaveChanges();

                        //TOD: Add to Audit Log
                        AuditLog(ctrl, AuditAction.Update, ForAuditLog, model);
                    }
                }
                catch (Exception ex)
                {
                    Msg    = ErrorHandling.HandleException(ex);
                    status = false;
                }
            }

            return(status);
        }
 public StatementTransactionPart(ImportConfiguration config)
 {
     errorHandling = config.ErrorHandling;
 }
        //Red/Amber Flag Alert Emails


        private MandrillError SendMessage(dynamic sendParams, SystemSettingsExt sys)
        {
            if (sys.EmailsEnabled)
            {
                sendParams.key = "LMPoi1kWRMJJQMWCHFsJIQ";             //"Z46-URL8pJppuh8Hv5Ff3A";

                sendParams.message.from_email = sys.AdminEmailAddress; // "*****@*****.**";
                sendParams.message.from_name  = "MANvFAT Football";

                if (sys.SendTempEmail)
                {
                    sendParams.message.to[0].email = sys.TempEmailAddress;
                    sendParams.message.to[0].name  = "MVFF Test Email";
                }

                ILog _log = log4net.LogManager.GetLogger("Mandrill/SendMessage");

                string url = MandrillBaseUrl + "/messages/send-template.json";

                var http = new HttpClient
                {
                    Request = { Accept = HttpContentTypes.ApplicationJson }
                };

                EasyHttp.Http.HttpResponse response;
                try
                {
                    response = http.Post(url, sendParams, HttpContentTypes.ApplicationJson);
                }
                catch (WebException ex)
                {
                    ErrorHandling.HandleException(ex);
                    _log.ErrorFormat("Error: WebException - {0}", ex.Message);
                    return(MandrillError.WebException);
                }

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    _log.InfoFormat("Response = {0} - {1}", response.StatusCode, response.StatusDescription);
                    _log.Info(response.RawText);
                    SecurityUtils.AddAuditLog("Mandrill Email Error", "Rejected: " + response.RawText);
                    return(MandrillError.HttpNotOk);
                }

                dynamic rv          = response.DynamicBody;
                string  msgResponse = string.Format("email: {0}, status: {1}", rv[0].email, rv[0].status);
                _log.InfoFormat(msgResponse);

                SecurityUtils.AddAuditLog("Mandrill Email Info", "Info: " + msgResponse);

                string send_status = rv[0].status;
                if (send_status == "sent" || send_status == "queued")
                {
                    //SecurityUtils.AddAuditLog("Mandrill Email Success", "send_status = " + send_status);
                    return(MandrillError.OK);
                }
                // otherwise, it should be "rejected" or "invalid"
                if (send_status == "invalid")
                {
                    return(MandrillError.Invalid);
                }
                if (send_status == "rejected")
                {
                    return(MandrillError.Rejected);
                }

                // unexpected...
                return(MandrillError.Unknown);
            }
            else
            {
                SecurityUtils.AddAuditLog("Mandrill Email Failed", "Emails are Disabled from System Settings");
                return(MandrillError.Unknown);
            }
        }
Exemplo n.º 12
0
 /// <inheritdoc />
 public string Translate(CultureInfo culture, ErrorHandling errorHandlingStrategy = ErrorHandling.Inherit)
 {
     return(Translator.Translate(this.resourceManager, this.Key, culture, errorHandlingStrategy));
 }
Exemplo n.º 13
0
        /// <summary>
        /// Populates the PO and Reqisition status dictionaries which are used in the <see cref="SetMunisStatuses"/> method.
        /// </summary>
        /// <remarks>
        /// This is done to avoid querying the database too frequently. We only update the values from the database at more critical moments.
        /// </remarks>
        private async void GetMunisStatuses()
        {
            try
            {
                // Only allow one instance to run at a time.
                if (munisStatusRefreshing)
                {
                    return;
                }

                munisStatusRefreshing = true;

                poStatuses.Clear();
                reqStatuses.Clear();

                var dataSource = (DataTable)SibiResultGrid.DataSource;

                if (dataSource == null)
                {
                    return;
                }

                foreach (DataRow row in dataSource.Rows)
                {
                    if (row[SibiRequestCols.PO] != null)
                    {
                        var poVal = row[SibiRequestCols.PO].ToString();
                        int poInt = 0;

                        if (int.TryParse(poVal, out poInt))
                        {
                            var poStatus = await MunisFunctions.GetPOStatusFromPO(poInt);

                            if (!poStatuses.ContainsKey(poInt))
                            {
                                poStatuses.Add(poInt, poStatus);
                            }
                        }
                    }

                    if (row[SibiRequestCols.RequisitionNumber] != null)
                    {
                        var reqVal     = row[SibiRequestCols.RequisitionNumber].ToString();
                        var fiscalYear = ((DateTime)row[SibiRequestCols.NeedBy]).Year;
                        int reqInt     = 0;

                        if (int.TryParse(reqVal, out reqInt))
                        {
                            var reqStatus = await MunisFunctions.GetReqStatusFromReqNum(reqVal, fiscalYear);

                            var reqKey = reqInt.ToString() + fiscalYear.ToString();
                            if (!reqStatuses.ContainsKey(reqKey))
                            {
                                reqStatuses.Add(reqKey, reqStatus);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorHandling.ErrHandle(ex, System.Reflection.MethodBase.GetCurrentMethod());
            }
            finally
            {
                munisStatusRefreshing = false;
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Translation.GetOrCreate(Properties.Resources.ResourceManager, nameof(Properties.Resources.SomeKey))
        /// If <paramref name="resourceManager"/> contains the resource <paramref name="key"/> an <see cref="Translation"/> is returned.
        /// If not a static translation is returned if error handling is not throw.
        /// </summary>
        /// <param name="resourceManager">
        /// The <see cref="ResourceManager"/> with the key.
        /// </param>
        /// <param name="key">
        /// The key to translate.
        /// </param>
        /// <param name="errorHandlingStrategy">Specifies how errors are handled.</param>
        /// <returns>
        /// A <see cref="Translation"/> that notifies when <see cref="Translator.Culture"/> changes.
        /// </returns>
        public static ITranslation GetOrCreate(ResourceManager resourceManager, string key, ErrorHandling errorHandlingStrategy = ErrorHandling.Inherit)
        {
            Ensure.NotNull(resourceManager, nameof(resourceManager));
            Ensure.NotNull(key, nameof(key));

            errorHandlingStrategy = errorHandlingStrategy.Coerce();
            var rmk = new ResourceManagerAndKey(resourceManager, key, errorHandlingStrategy);

            return(Cache.GetOrAdd(rmk, x => CreateTranslation(x.ResourceManager, x.Key, errorHandlingStrategy)));
        }
Exemplo n.º 15
0
        private static ITranslation CreateTranslation(ResourceManager resourceManager, string key, ErrorHandling errorHandling)
        {
            if (resourceManager.HasKey(key))
            {
                return(new Translation(resourceManager, key, errorHandling));
            }

            if (errorHandling == ErrorHandling.Throw)
            {
                throw new ArgumentOutOfRangeException(nameof(key), $"The resourcemanager: {resourceManager.BaseName} does not have the key: {key}");
            }

            return(new StaticTranslation(string.Format(Properties.Resources.MissingKeyFormat, key), key, errorHandling));
        }
Exemplo n.º 16
0
        // TODO: check for nodes if they've even been found
        public override bool ParseInfo()
        {
            var strStatus = node.SelectSingleNode("//div[@class='match_logos']/div[@class='score']/div").InnerText;

            if (strStatus == "offen")
            {
                Status = AnalyzerConstants.MatchStatus.NotPlayed;
                return(true);
            }

            // fetch team names
            var teamNameNodes = node.SelectNodes("//div[@class='match_names']/div[@class='team']/a");

            TeamNames.Add(AnalyzerConstants.TeamSide.A, teamNameNodes[0].InnerText.Trim());
            TeamNames.Add(AnalyzerConstants.TeamSide.B, teamNameNodes[1].InnerText.Trim());

            // fetch map score
            var teamScoreNodes = node.SelectNodes("//div[@class='match_logos']/div[@class='score']/span");

            Score.Add(AnalyzerConstants.TeamSide.A, Convert.ToInt32(teamScoreNodes[0].InnerText));
            Score.Add(AnalyzerConstants.TeamSide.B, Convert.ToInt32(teamScoreNodes[1].InnerText));

            // was the match actually played or is this a nasty defwin?
            var resultsNode = node.SelectSingleNode("//div[@id='content']/h2[2]");

            if (resultsNode.InnerText != "Ergebnisse")
            {
                Status = AnalyzerConstants.MatchStatus.DefWin;
                return(true);
            }

            Status = AnalyzerConstants.MatchStatus.Played;

            // get round score per map
            var nodeFirstMapScore = node.SelectSingleNode("//div[@id='content']/text()[preceding-sibling::br]");
            var firstMapScoreStr  = nodeFirstMapScore.InnerText.Trim().Split(':');

            if (firstMapScoreStr.Count() != 3)
            {
                ErrorHandling.Log($"Unexpected Error: Could not find map score for match { url }");
                return(false);
            }

            // first map
            var firstMapScores = new Dictionary <AnalyzerConstants.TeamSide, int>();
            var firstMapName   = firstMapScoreStr[0];
            var firstMapScoreA = Convert.ToInt32(firstMapScoreStr[1].Trim());
            var firstMapScoreB = Convert.ToInt32(firstMapScoreStr[2].Trim());

            firstMapScores.Add(AnalyzerConstants.TeamSide.A, firstMapScoreA);
            firstMapScores.Add(AnalyzerConstants.TeamSide.B, firstMapScoreB);
            Maps.Add(new Map(firstMapName, firstMapScores));

            // second map
            var secondMapScores   = new Dictionary <AnalyzerConstants.TeamSide, int>();
            var secondMapScoreStr = nodeFirstMapScore.NextSibling.NextSibling.InnerText.Trim().Split(':');
            var secondMapName     = secondMapScoreStr[0];
            var secondMapScoreA   = Convert.ToInt32(secondMapScoreStr[1].Trim());
            var secondMapScoreB   = Convert.ToInt32(secondMapScoreStr[2].Trim());

            secondMapScores.Add(AnalyzerConstants.TeamSide.A, secondMapScoreA);
            secondMapScores.Add(AnalyzerConstants.TeamSide.B, secondMapScoreB);
            Maps.Add(new Map(secondMapName, secondMapScores));

            // if map score is not available anymore, but round scores are availabe
            if (Score.All(s => s.Value == 0))
            {
                // Team A
                Score[AnalyzerConstants.TeamSide.A]  = firstMapScoreA > firstMapScoreB ? 1 : 0;
                Score[AnalyzerConstants.TeamSide.A] += secondMapScoreA > secondMapScoreB ? 1 : 0;

                // Team B
                Score[AnalyzerConstants.TeamSide.B]  = firstMapScoreB > firstMapScoreA ? 1 : 0;
                Score[AnalyzerConstants.TeamSide.B] += secondMapScoreB > secondMapScoreA ? 1 : 0;
            }

            // get vote data from match log
            var logNode       = node.SelectSingleNode("//table[@id='match_log']");
            var trNodes       = logNode.SelectNodes("tr");
            var voteDataFound = false;

            foreach (var tr in trNodes)
            {
                if (voteDataFound)
                {
                    break;
                }

                var cols = tr.SelectNodes("td");
                if (cols == null || cols.Count == 0)
                {
                    continue;
                }

                var aktion = cols[2].InnerText; // 3rd column: "Aktion"
                if (aktion != "mapvote_ended")
                {
                    continue;
                }


                var      voteData    = cols[3].InnerText.Split(',');
                var      voteDateStr = cols[0].SelectSingleNode("span").GetAttributeValue("title", "");
                DateTime voteDate    = DateTime.MinValue;
                if (!string.IsNullOrEmpty(voteDateStr))
                {
                    voteDate = DateTime.Parse(voteDateStr);
                }

                foreach (var sVote in voteData)
                {
                    if (sVote == "timeouted")
                    {
                        Status = AnalyzerConstants.MatchStatus.DefWin;
                        break;
                    }
                    var RegExMatch       = System.Text.RegularExpressions.Regex.Match(sVote.Trim(), AnalyzerConstants.MapvotePattern);
                    var validateLogEntry = RegExMatch.Success && RegExMatch.Groups.Count > 1; // First group is always the whole string

                    if (!validateLogEntry)
                    {
                        ErrorHandling.Log($"Could not read mapvote entry: \"{ sVote }\"");
                        continue;
                    }

                    // get captured groups
                    var reSide = RegExMatch.Groups[1].Value;
                    var reType = RegExMatch.Groups[2].Value;
                    var reMap  = RegExMatch.Groups[3].Value;

                    // interpret groups
                    AnalyzerConstants.TeamSide side = AnalyzerConstants.TeamSide.Unknown;
                    if (reSide == "T1")
                    {
                        side = AnalyzerConstants.TeamSide.A;
                    }
                    else if (reSide == "T2")
                    {
                        side = AnalyzerConstants.TeamSide.B;
                    }
                    else
                    {
                        ErrorHandling.Log($"Could not read voting team: \"{ reSide }\"");
                    }

                    AnalyzerConstants.VoteType type = AnalyzerConstants.VoteType.Unknown;
                    if (reType == "bans")
                    {
                        type = AnalyzerConstants.VoteType.Ban;
                    }
                    else if (reType == "picks")
                    {
                        type = AnalyzerConstants.VoteType.Pick;
                    }
                    else
                    {
                        ErrorHandling.Log($"Could not read voting type: \"{ reType }\"");
                    }

                    var map = new Map(reMap);
                    if (type == AnalyzerConstants.VoteType.Pick)
                    {
                        map = Maps.Where(m => m.Name == map.Name).First();
                    }

                    // create vote instance
                    Vote vote;
                    if (voteDate != DateTime.MinValue)
                    {
                        vote = new Vote(side, type, map, voteDate);
                    }
                    else
                    {
                        vote = new Vote(side, type, map);
                    }
                    Votes.Add(vote);
                }

                voteDataFound = true;
            }

            if (!voteDataFound)
            {
                ErrorHandling.Log($"Could not find vote data for presumably played match { url }. This may happen if the match has no match log entries anymore.");
                return(false);
            }

            return(true);
        }
Exemplo n.º 17
0
        private async void Connect()
        {
            try
            {
                ConnectCommand.Executable = false;

                if (string.IsNullOrWhiteSpace(ConsensusServerNetworkAddress))
                {
                    MessageBox.Show("Network address is required");
                    return;
                }
                if (string.IsNullOrWhiteSpace(ConsensusServerRpcUsername))
                {
                    MessageBox.Show("RPC username is required");
                    return;
                }
                if (ConsensusServerRpcPassword.Length == 0)
                {
                    MessageBox.Show("RPC password may not be empty");
                    return;
                }
                if (!File.Exists(ConsensusServerCertificateFile))
                {
                    MessageBox.Show("Certificate file not found");
                    return;
                }

                var rpcOptions = new ConsensusServerRpcOptions(ConsensusServerNetworkAddress,
                                                               ConsensusServerRpcUsername, ConsensusServerRpcPassword, ConsensusServerCertificateFile);
                try
                {
                    await App.Current.Synchronizer.WalletRpcClient.StartConsensusRpc(rpcOptions);
                }
                catch (Exception ex) when(ErrorHandling.IsTransient(ex) || ErrorHandling.IsClientError(ex))
                {
                    MessageBox.Show($"Unable to start {ConsensusServerRpcOptions.ApplicationName} RPC.\n\nCheck connection settings and try again.", "Error");
                    return;
                }

                await Task.Run(() =>
                {
                    // save defaults to a file so that the user doesn't have to type this information again
                    var ini = new IniData();
                    ini.Sections.AddSection("Application Options");
                    ini["Application Options"]["rpcuser"]   = ConsensusServerRpcUsername;
                    ini["Application Options"]["rpcpass"]   = ConsensusServerRpcPassword;
                    ini["Application Options"]["rpclisten"] = ConsensusServerNetworkAddress;
                    var appDataDir = Portability.LocalAppData(Environment.OSVersion.Platform,
                                                              AssemblyResources.Organization, AssemblyResources.ProductName);
                    var parser = new FileIniDataParser();
                    parser.WriteFile(Path.Combine(appDataDir, "defaults.ini"), ini);
                });

                var walletExists = await App.Current.Synchronizer.WalletRpcClient.WalletExistsAsync();

                if (!walletExists)
                {
                    _wizard.CurrentDialog = new CreateOrImportSeedDialog(Wizard);
                }
                else
                {
                    // TODO: Determine whether the public encryption is enabled and a prompt for the
                    // public passphrase prompt is needed before the wallet can be opened.  If it
                    // does not, then the wallet can be opened directly here instead of creating
                    // another dialog.
                    _wizard.CurrentDialog = new PromptPublicPassphraseDialog(Wizard);

                    //await _walletClient.OpenWallet("public");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
            finally
            {
                ConnectCommand.Executable = true;
            }
        }
Exemplo n.º 18
0
 /// <inheritdoc />
 public string Translate(CultureInfo culture, ErrorHandling errorHandlingStrategy = ErrorHandling.Inherit)
 {
     return Translator.Translate(this.resourceManager, this.key, culture, errorHandlingStrategy);
 }
Exemplo n.º 19
0
        private async void Connect()
        {
            try
            {
                ConnectCommand.Executable = false;

                if (string.IsNullOrWhiteSpace(ConsensusServerNetworkAddress))
                {
                    MessageBox.Show("Network address is required");
                    return;
                }
                if (string.IsNullOrWhiteSpace(ConsensusServerRpcUsername))
                {
                    MessageBox.Show("RPC username is required");
                    return;
                }
                if (ConsensusServerRpcPassword.Length == 0)
                {
                    MessageBox.Show("RPC password may not be empty");
                    return;
                }
                if (!File.Exists(ConsensusServerCertificateFile))
                {
                    MessageBox.Show("Certificate file not found");
                    return;
                }

                var rpcOptions = new ConsensusServerRpcOptions(ConsensusServerNetworkAddress,
                                                               ConsensusServerRpcUsername, ConsensusServerRpcPassword, ConsensusServerCertificateFile);
                try
                {
                    await App.Current.WalletRpcClient.StartConsensusRpc(rpcOptions);
                }
                catch (Exception ex) when(ErrorHandling.IsTransient(ex) || ErrorHandling.IsClientError(ex))
                {
                    MessageBox.Show($"Unable to start {ConsensusServerRpcOptions.ApplicationName} RPC.\n\nCheck connection settings and try again.", "Error");
                    MessageBox.Show(ex.Message);
                    return;
                }

                var walletExists = await App.Current.WalletRpcClient.WalletExistsAsync();

                if (!walletExists)
                {
                    _wizard.CurrentDialog = new CreateOrImportSeedDialog(Wizard);
                }
                else
                {
                    // TODO: Determine whether the public encryption is enabled and a prompt for the
                    // public passphrase prompt is needed before the wallet can be opened.  If it
                    // does not, then the wallet can be opened directly here instead of creating
                    // another dialog.
                    _wizard.CurrentDialog = new PromptPublicPassphraseDialog(Wizard);

                    //await _walletClient.OpenWallet("public");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
            finally
            {
                ConnectCommand.Executable = true;
            }
        }
Exemplo n.º 20
0
        /******************************************************************************
        *   Reports errors. Only call this if FError() is true.
        ******************************************************************************/
        public Exception ReportErrors()
        {
            Debug.Assert(FError());

            // Report error.
            // NOTE: If the definition of FError changes, this code will need to change.
            Debug.Assert(!_swtFirst || _swtAmbig);

            if (_swtFirst)
            {
                // Ambiguous lookup.
                return(ErrorHandling.Error(ErrorCode.ERR_AmbigMember, _swtFirst, _swtAmbig));
            }

            if (_swtInaccess)
            {
                return(!_swtInaccess.Sym.isUserCallable() && ((_flags & MemLookFlags.UserCallable) != 0)
                    ? ErrorHandling.Error(ErrorCode.ERR_CantCallSpecialMethod, _swtInaccess)
                    : CSemanticChecker.ReportAccessError(_swtInaccess, _symWhere, _typeQual));
            }

            if ((_flags & MemLookFlags.Ctor) != 0)
            {
                Debug.Assert(_typeSrc is AggregateType);
                return(_arity > 0
                    ? ErrorHandling.Error(ErrorCode.ERR_BadCtorArgCount, ((AggregateType)_typeSrc).OwningAggregate, _arity)
                    : ErrorHandling.Error(ErrorCode.ERR_NoConstructors, ((AggregateType)_typeSrc).OwningAggregate));
            }

            if ((_flags & MemLookFlags.Operator) != 0)
            {
                return(ErrorHandling.Error(ErrorCode.ERR_NoSuchMember, _typeSrc, _name));
            }

            if ((_flags & MemLookFlags.Indexer) != 0)
            {
                return(ErrorHandling.Error(ErrorCode.ERR_BadIndexLHS, _typeSrc));
            }

            if (_swtBad)
            {
                return(ErrorHandling.Error((_flags & MemLookFlags.MustBeInvocable) != 0 ? ErrorCode.ERR_NonInvocableMemberCalled : ErrorCode.ERR_CantCallSpecialMethod, _swtBad));
            }

            if (_swtBogus)
            {
                return(ReportBogus(_swtBogus));
            }

            if (_swtBadArity)
            {
                Debug.Assert(_arity != 0);
                Debug.Assert(!(_swtBadArity.Sym is AggregateSymbol));
                if (_swtBadArity.Sym is MethodSymbol badMeth)
                {
                    int cvar = badMeth.typeVars.Count;
                    return(ErrorHandling.Error(cvar > 0 ? ErrorCode.ERR_BadArity : ErrorCode.ERR_HasNoTypeVars, _swtBadArity, new ErrArgSymKind(_swtBadArity.Sym), cvar));
                }

                return(ErrorHandling.Error(ErrorCode.ERR_TypeArgsNotAllowed, _swtBadArity, new ErrArgSymKind(_swtBadArity.Sym)));
            }

            return(ErrorHandling.Error(ErrorCode.ERR_NoSuchMember, _typeSrc, _name));
        }
Exemplo n.º 21
0
 public void ErrorOccurred(int elementID, String errorMessage)
 {
     StopAll();
     if (ErrorHandling != null)
     {
         Ares.Data.IElement element = null;
         if (elementID != -1)
         {
             element = Ares.Data.DataModule.ElementRepository.GetElement(elementID);
         }
         if (ErrorHandling.Control.InvokeRequired)
         {
             ErrorHandling.Control.BeginInvoke(new System.Windows.Forms.MethodInvoker(() =>
                                                                                      ErrorHandling.ErrorHandlingMethod(element, errorMessage)));
         }
         else
         {
             ErrorHandling.ErrorHandlingMethod(element, errorMessage);
         }
     }
 }
Exemplo n.º 22
0
        /// <summary>
        /// Export Reactions for client delivery
        /// </summary>
        /// <param name="RefIDsList"></param>
        /// <param name="shipmentYear"></param>
        /// <param name="outputPath"></param>
        /// <param name="mdlStartNo"></param>
        /// <param name="deliveryDtls"></param>
        /// <param name="delivSovCats"></param>
        /// <returns></returns>
        public static bool ExportReactionsForClientDelivery(List <int> RefIDsList, string shipmentYear, string outputPath, int mdlStartNo, out Delivery deliveryDtls, out List <DeliverySolvCats> delivSovCatsList)
        {
            bool     blStatus    = false;
            Delivery objDelivery = null;
            List <DeliverySolvCats> lstDeliverySovCats = null;

            try
            {
                int           mdlNo            = mdlStartNo;//70000000;
                List <string> lstUniqSolvInchi = new List <string>();

                //Define Delivery class
                objDelivery = new Delivery();
                objDelivery.DeliveryDate     = DateTime.Now;
                objDelivery.MDLStartNo       = mdlStartNo;
                objDelivery.DeliveryRefCount = RefIDsList.Count;

                List <int> lstDelRefs        = new List <int>();
                List <int> lstDelRefMDLStNo  = new List <int>();
                List <int> lstDelRefMDLEndNo = new List <int>();
                int        deliveredRxnCnt   = 0;

                lstDeliverySovCats = new List <DeliverySolvCats>();

                foreach (int shipRefID in RefIDsList)
                {
                    DataSet   dsRxns      = ReactionCurationDB.GetReactionsForExportOnDocID(shipRefID);
                    DataTable dtRxnRefs   = null;
                    DataTable dtCrossRefs = null;

                    //Automated Export
                    DataSet dsRxn_CrossRefs = ReactionCurationDB.GetRxnAndCrossReferencesOnShipmentRefID(shipRefID);
                    if (dsRxn_CrossRefs != null)
                    {
                        if (dsRxn_CrossRefs.Tables.Count == 2)
                        {
                            dtCrossRefs = dsRxn_CrossRefs.Tables[0];
                            dtRxnRefs   = dsRxn_CrossRefs.Tables[1];
                        }
                    }

                    if (dsRxns != null)
                    {
                        if (dsRxns.Tables.Count == 8)
                        {
                            DataTable dtDocMaster = dsRxns.Tables[0];
                            DataTable dtReactions = dsRxns.Tables[1];
                            //Manual Export
                            //DataTable dtRxnRefs = dsRxns.Tables[2];
                            //DataTable dtCrossRefs = dsRxns.Tables[3];
                            DataTable dtRxnSteps     = dsRxns.Tables[4];
                            DataTable dtConditions   = dsRxns.Tables[5];
                            DataTable dtParticipants = dsRxns.Tables[6];
                            DataTable dtProducts     = dsRxns.Tables[7];

                            // FullArticleInfo articleInfo =  GetArticleInfoFromTable(dtDocMaster);

                            FullArticleInfo articleInfo = GetFullArticleDetailsOnShipmentRefID(Convert.ToInt32(dtDocMaster.Rows[0]["SHIPMENT_REF_ID"].ToString()));

                            string shipementRefName        = dtDocMaster.Rows[0]["REFERENCE_NAME"].ToString();
                            List <ReactionInfo> lstRxnInfo = new List <ReactionInfo>();
                            int reactionID = 0;

                            //Add Reference Name and MDL Start No
                            lstDelRefs.Add(shipRefID);
                            lstDelRefMDLStNo.Add(mdlNo);

                            //Unique ID for reaction (serial number); format: RXCInnnnnnnn;n=numerical range for backfiles is 70000001...89999999.
                            //Feedback on 28th Oct 2014
                            //General: Please assign MDLnumbers according to the year, i.e. issues from 1981 should have MDLnumbers RXCI81nnnnnn, to avoid duplicates

                            foreach (DataRow drow in dtReactions.Rows)
                            {
                                reactionID = Convert.ToInt32(drow["REACTION_ID"]);

                                ReactionInfo rxnInfo = new ReactionInfo();
                                rxnInfo.ShipmentRefID  = shipRefID;
                                rxnInfo.ReactionID     = reactionID;
                                rxnInfo.SysNo          = dtDocMaster.Rows[0]["SYS_NO"].ToString();
                                rxnInfo.SysText        = dtDocMaster.Rows[0]["SYS_TEXT"].ToString();
                                rxnInfo.RxnMDLNo       = "RXCI" + shipmentYear + mdlNo.ToString("000000");//RXCI81nnnnnn
                                rxnInfo.ReactionScheme = drow["REACTION_SCHEME"];
                                rxnInfo.ReactionSNo    = Convert.ToInt32(drow["REACTION_SNO"]);
                                rxnInfo.RxnComments    = drow["RXN_COMMENTS"].ToString();
                                rxnInfo.RxnRef         = GetRxnRefInfoFromTableOnReactionID(dtRxnRefs, reactionID);
                                rxnInfo.RxnCrossRef    = GetCrossRefInfoFromTableOnReactionID(dtCrossRefs, reactionID);
                                rxnInfo.RxnProducts    = GetProductsFromTableOnReactionID(dtProducts, reactionID);
                                rxnInfo.RxnSteps       = GetStepsInfoFromTableOnReactionID(dtRxnSteps, dtParticipants, dtConditions, reactionID);

                                //Add to list
                                lstRxnInfo.Add(rxnInfo);

                                //increment MDL Numer
                                mdlNo++;

                                //Count delivery Rxns
                                deliveredRxnCnt++;
                            }

                            //Add Reference MDL End No
                            lstDelRefMDLEndNo.Add(mdlNo);

                            if (lstRxnInfo != null)
                            {
                                DeliverySolvCats refSovCats = new DeliverySolvCats();
                                if (ReactionExport.ExportToRDFile(lstRxnInfo, articleInfo, shipementRefName, outputPath, ref lstUniqSolvInchi, ref refSovCats))
                                {
                                    blStatus = true;

                                    if (refSovCats.RefNewSolvents != null)
                                    {
                                        refSovCats.ShipmentRefID = shipRefID;

                                        //Add Refs and SolvCats to List
                                        lstDeliverySovCats.Add(refSovCats);
                                    }
                                }
                            }
                        }
                    }
                }

                //Delivery references and Mdl Nos
                objDelivery.DeliveryRefsList  = lstDelRefs;
                objDelivery.RefMdlStartNoList = lstDelRefMDLStNo;
                objDelivery.RefMdlEndNoList   = lstDelRefMDLEndNo;
                objDelivery.DeliveryRxnCount  = deliveredRxnCnt;
                objDelivery.MDLEndNo          = (mdlStartNo + deliveredRxnCnt) - 1;
            }
            catch (Exception ex)
            {
                ErrorHandling.WriteErrorLog(ex.ToString());
            }
            deliveryDtls     = objDelivery;
            delivSovCatsList = lstDeliverySovCats;
            return(blStatus);
        }
Exemplo n.º 23
0
 public override object[] Reduce(Enviroment env, ErrorHandling errorHandling)
 {
     return(new object[] {});
 }
Exemplo n.º 24
0
        private static List <CrossRefInfo> GetCrossRefInfoFromTableOnReactionID(DataTable crossRefData, int reactionID)
        {
            List <CrossRefInfo> lstCrossRef = null;

            try
            {
                if (crossRefData != null)
                {
                    EnumerableRowCollection <DataRow> rows = from row in crossRefData.AsEnumerable()
                                                             where row.Field <Int64>("REACTION_ID") == reactionID
                                                             select row;

                    lstCrossRef = new List <CrossRefInfo>();
                    //int crossRefIndx = 0;
                    foreach (DataRow drow in rows)
                    {
                        //crossRefIndx++;

                        //Manual Export - Code commented on 22nd Nov 2014
                        //CrossRefInfo crossRef = new CrossRefInfo();
                        //crossRef.ReactionID = reactionID;
                        //crossRef.CrossRefID = Convert.ToInt32(drow["CR_ID"]);
                        ////crossRef.CrossRefNo = crossRefIndx;
                        //crossRef.PrevReactionNo = !string.IsNullOrEmpty(drow["PRE_RXN_SNO"].ToString()) ? Convert.ToInt32(drow["PRE_RXN_SNO"]) : 0;
                        //crossRef.SuccReactionNo = !string.IsNullOrEmpty(drow["SUCC_RXN_SNO"].ToString()) ? Convert.ToInt32(drow["SUCC_RXN_SNO"]) : 0;
                        //lstCrossRef.Add(crossRef);

                        //Automated Export
                        string[] saPreceeding = drow["PRECEEDING"].ToString().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                        if (saPreceeding != null)
                        {
                            foreach (string prerxn in saPreceeding)
                            {
                                if (!string.IsNullOrEmpty(prerxn.Trim()))
                                {
                                    CrossRefInfo crossRef = new CrossRefInfo();
                                    crossRef.ReactionID     = reactionID;
                                    crossRef.PrevReactionNo = prerxn.Trim();
                                    //crossRef.CrossRefType = "PRE";
                                    lstCrossRef.Add(crossRef);
                                }
                            }
                        }
                        string[] saSucceeding = drow["SUCCEEDING"].ToString().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                        if (saSucceeding != null)
                        {
                            foreach (string succrxn in saSucceeding)
                            {
                                if (!string.IsNullOrEmpty(succrxn.Trim()))
                                {
                                    CrossRefInfo crossRef = new CrossRefInfo();
                                    crossRef.ReactionID     = reactionID;
                                    crossRef.SuccReactionNo = succrxn.Trim();
                                    //crossRef.CrossRefType = "SUC";
                                    lstCrossRef.Add(crossRef);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorHandling.WriteErrorLog(ex.ToString());
            }
            return(lstCrossRef);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Primary method - processes commands from server
        /// </summary>
        /// <param name="command">command name</param>
        /// <param name="args">command arguments</param>
        private void DispatchServerCommand(string command, string[] args)
        {
            try {
                switch (command)
                {
                case "TASServer": // happens after connecting to server
                    serverVersion = args[0];
                    int.TryParse(args[1], out serverUdpHolePunchingPort);
                    isConnected = true;
                    if (Connected != null)
                    {
                        Connected(this, new TasEventArgs());
                    }
                    break;

                case "ACCEPTED": // Login accepted
                    username   = args[0];
                    isLoggedIn = true;
                    if (LoginAccepted != null)
                    {
                        LoginAccepted(this, new TasEventArgs());
                    }
                    break;

                case "DENIED": // login denied
                    isLoggedIn = false;
                    if (LoginDenied != null)
                    {
                        LoginDenied(this, new TasEventArgs(Utils.Glue(args)));
                    }
                    break;

                case "JOIN": // channel joined
                    if (!joinedChannels.ContainsKey(args[0]))
                    {
                        joinedChannels.Add(args[0], Channel.Create(args[0]));
                    }
                    if (ChannelJoined != null)
                    {
                        ChannelJoined(this, new TasEventArgs(args));
                    }
                    break;

                case "JOINFAILED": // channel join failed
                    if (ChannelJoinFailed != null)
                    {
                        ChannelJoinFailed(this, new TasEventArgs(Utils.Glue(args)));
                    }
                    break;

                case "CHANNEL": // iterating channels
                {
                    ExistingChannel c = new ExistingChannel();
                    c.name = args[0];
                    int.TryParse(args[1], out c.userCount);
                    if (args.Length >= 3)
                    {
                        c.topic = Utils.Glue(args, 2);
                    }
                    existingChannels.Add(c.name, c);
                }
                break;

                case "ENDOFCHANNELS": // end of channel list iteration
                    isChanScanning = false;
                    if (ChannelListDone != null)
                    {
                        ChannelListDone(this, new TasEventArgs());
                    }
                    break;

                case "ADDUSER": // new user joined ta server
                {
                    User u = User.Create(args[0]);
                    u.country = args[1];
                    int.TryParse(args[2], out u.cpu);
                    //IPAddress.TryParse(args[3], out u.ip);
                    existingUsers.Add(u.name, u);
                    if (UserAdded != null)
                    {
                        UserAdded(this, new TasEventArgs(args));
                    }
                }
                break;

                case "REMOVEUSER": // user left ta server
                    existingUsers.Remove(args[0]);
                    if (UserRemoved != null)
                    {
                        UserRemoved(this, new TasEventArgs(args));
                    }
                    break;

                case "MOTD": // server motd
                    if (Said != null && args.Length > 0)
                    {
                        Said(this, new TasSayEventArgs(TasSayEventArgs.Origins.Server, TasSayEventArgs.Places.Motd, "", "", Utils.Glue(args, 0), false));
                    }
                    break;

                case "SERVERMSG": // server message
                    if (Said != null)
                    {
                        Said(this, new TasSayEventArgs(TasSayEventArgs.Origins.Server, TasSayEventArgs.Places.Normal, "", "", Utils.Glue(args, 0), false));
                    }
                    break;

                case "SERVERMSGBOX": // server messagebox
                    if (Said != null)
                    {
                        Said(this, new TasSayEventArgs(TasSayEventArgs.Origins.Server, TasSayEventArgs.Places.MessageBox, "", "", Utils.Glue(args, 0), false));
                    }
                    break;

                case "CHANNELMESSAGE": // server broadcast to channel
                    if (Said != null)
                    {
                        Said(this, new TasSayEventArgs(TasSayEventArgs.Origins.Server, TasSayEventArgs.Places.Channel, args[0], "", Utils.Glue(args, 1), false));
                    }
                    break;

                case "SAID": // someone said something in channel
                    if (Said != null)
                    {
                        Said(this, new TasSayEventArgs(TasSayEventArgs.Origins.Player, TasSayEventArgs.Places.Channel, args[0], args[1], Utils.Glue(args, 2), false));
                    }
                    break;

                case "SAIDEX": // someone said something with emote in channel
                    if (Said != null)
                    {
                        Said(this, new TasSayEventArgs(TasSayEventArgs.Origins.Player, TasSayEventArgs.Places.Channel, args[0], args[1], Utils.Glue(args, 2), true));
                    }
                    break;

                case "SAYPRIVATE": // sent back from sever when user sends private message
                    if (Said != null)
                    {
                        Said(this, new TasSayEventArgs(TasSayEventArgs.Origins.Player, TasSayEventArgs.Places.Normal, args[0], username, Utils.Glue(args, 1), false));       // channel = char partner name
                    }
                    break;

                case "SAIDPRIVATE": // someone said something to me
                    if (Said != null)
                    {
                        Said(this, new TasSayEventArgs(TasSayEventArgs.Origins.Player, TasSayEventArgs.Places.Normal, args[0], args[0], Utils.Glue(args, 1), false));
                    }
                    break;

                case "SAIDBATTLE": // someone said something in battle
                    if (Said != null)
                    {
                        Said(this, new TasSayEventArgs(TasSayEventArgs.Origins.Player, TasSayEventArgs.Places.Battle, "", args[0], Utils.Glue(args, 1), false));
                    }
                    break;

                case "SAIDBATTLEEX": // someone said in battle with emote
                    if (Said != null)
                    {
                        Said(this, new TasSayEventArgs(TasSayEventArgs.Origins.Player, TasSayEventArgs.Places.Battle, "", args[0], Utils.Glue(args, 1), true));
                    }
                    break;

                case "BROADCAST": // server sends urgent broadcast
                    if (Said != null)
                    {
                        Said(this, new TasSayEventArgs(TasSayEventArgs.Origins.Server, TasSayEventArgs.Places.Broadcast, "", "", Utils.Glue(args, 0), false));
                    }
                    break;

                case "REDIRECT": // server sends backup IP
                    // removed due to bugs
                    break;

                case "CLIENTSTATUS": // client's status changed
                {
                    int status = 0;
                    int.TryParse(args[1], out status);
                    User u = existingUsers[args[0]];
                    u.FromInt(status);

                    if (u.name == UserName && (u.isInGame == true && existingUsers[args[0]].isInGame == false))
                    {
                        existingUsers[args[0]] = u;
                        if (MyStatusChangedToInGame != null)
                        {
                            MyStatusChangedToInGame(this, new TasEventArgs());
                        }
                    }

                    existingUsers[args[0]] = u;
                    if (UserStatusChanged != null)
                    {
                        UserStatusChanged(this, new TasEventArgs(args));
                    }
                }
                break;

                case "CLIENTS": // client list sent after channel join
                    string[] usrs = Utils.Glue(args, 1).Split(' ');
                    foreach (string s in usrs)
                    {
                        joinedChannels[args[0]].channelUsers.Add(s);
                    }
                    if (ChannelUserAdded != null)
                    {
                        ChannelUserAdded(this, new TasEventArgs(args[0]));
                    }
                    break;

                case "JOINED": // user joined one of my channels
                    joinedChannels[args[0]].channelUsers.Add(args[1]);
                    if (ChannelUserAdded != null)
                    {
                        ChannelUserAdded(this, new TasEventArgs(args[0]));
                    }
                    break;

                case "LEFT": // user left one of my channels
                    joinedChannels[args[0]].channelUsers.Remove(args[1]);
                    if (ChannelUserRemoved != null)
                    {
                        ChannelUserRemoved(this, new TasEventArgs(args[0], args[1], Utils.Glue(args, 2)));
                    }
                    break;

                case "CHANNELTOPIC": // channel topic update (after joining a channel)
                {
                    Channel c = joinedChannels[args[0]];
                    c.topicSetBy   = args[1];
                    c.topicSetDate = ConvertMilisecondTime(args[2]);
                    c.topic        = Utils.Glue(args, 3);
                    if (ChannelTopicChanged != null)
                    {
                        ChannelTopicChanged(this, new TasEventArgs(args[0]));
                    }
                }
                break;

                case "OPENBATTLEFAILED": // opening new battle has failed
                    if (BattleOpenFailed != null)
                    {
                        BattleOpenFailed(this, new TasEventArgs(Utils.Glue(args)));
                    }
                    break;

                case "OPENBATTLE": // openbattle ok
                {
                    battleID = int.Parse(args[0]);
                    UserBattleStatus self = new UserBattleStatus(username);
                    self.IsSpectator = true;
                    battle.Users.Add(self); // add self
                    if (BattleOpened != null)
                    {
                        BattleOpened(this, new TasEventArgs(args[0]));
                    }
                }
                break;

                case "REQUESTBATTLESTATUS":                           // server asks us to update our status
                    con.SendCommand(0, "MYBATTLESTATUS", 1 << 22, 0); // tell server that we are synchronized  spectators
                    break;

                case "JOINEDBATTLE": // user joined the battle
                    if (battle != null && int.Parse(args[0]) == battleID)
                    {
                        battle.Users.Add(new UserBattleStatus(args[1]));
                        if (BattleUserJoined != null)
                        {
                            BattleUserJoined(this, new TasEventArgs(args[1]));
                        }
                    }
                    break;

                case "LEFTBATTLE": // user left the battle
                    if (battle != null && int.Parse(args[0]) == battleID)
                    {
                        battle.RemoveUser(args[1]);
                        UpdateSpectators();
                        if (BattleUserLeft != null)
                        {
                            BattleUserLeft(this, new TasEventArgs(args[1]));
                        }
                        if (args[1] == username)
                        {
                            battle   = null;
                            battleID = 0;
                            if (BattleClosed != null)
                            {
                                BattleClosed(this, new TasEventArgs());
                            }
                        }
                    }
                    break;

                case "CLIENTBATTLESTATUS": // player battle status has changed
                    if (battle != null)
                    {
                        int uindex = battle.GetUserIndex(args[0]);
                        if (uindex != -1)
                        {
                            UserBattleStatus bs = battle.Users[uindex];
                            bs.SetFrom(int.Parse(args[1]), int.Parse(args[2]));
                            battle.Users[uindex] = bs;
                            UpdateSpectators();
                            if (BattleUserStatusChanged != null)
                            {
                                BattleUserStatusChanged(this, new TasEventArgs(args[0]));
                            }
                        }
                    }
                    break;

                case "UPDATEBATTLEINFO": // update external battle info (lock and map)
                    if (battle != null && int.Parse(args[0]) == battleID)
                    {
                        string mapname = Utils.Glue(args, 4);
                        if (battle.Map.Name != mapname)
                        {
                            if (mapToChangeTo != null && mapToChangeTo.Name == mapname) // if we changed to known requested map, use it
                            {
                                battle.Map = mapToChangeTo;
                            }
                            else
                            {
                                battle.Map = Program.main.Spring.UnitSync.MapList[mapname]; //otherwise find this map using unitsync
                            }
                            if (BattleMapChanged != null)
                            {
                                BattleMapChanged(this, new TasEventArgs(mapname));
                            }
                        }

                        if (battle.IsLocked != int.Parse(args[2]) > 0)
                        {
                            battle.IsLocked = int.Parse(args[2]) > 0;
                            if (BattleLockChanged != null)
                            {
                                BattleLockChanged(this, new TasEventArgs(args[2]));
                            }
                        }
                    }
                    break;

                case "UPDATEBATTLEDETAILS": // updates internal battle details
                    if (battle != null)
                    {
                        BattleDetails bd = new BattleDetails();
                        bd.StartingMetal    = int.Parse(args[0]);
                        bd.StartingEnergy   = int.Parse(args[1]);
                        bd.MaxUnits         = int.Parse(args[2]);
                        bd.StartPos         = (BattleStartPos)int.Parse(args[3]);
                        bd.EndCondition     = (BattleEndCondition)int.Parse(args[4]);
                        bd.LimitDgun        = int.Parse(args[5]);
                        bd.DiminishingMM    = int.Parse(args[6]);
                        bd.GhostedBuildings = int.Parse(args[7]);
                        battle.Details      = bd;
                        if (BattleDetailsChanged != null)
                        {
                            BattleDetailsChanged(this, new TasEventArgs(args));
                        }
                    }
                    break;

                case "BATTLEOPENED": {
                    if (BattleFound != null)
                    {
                        BattleFound(this, new TasEventArgs(args));
                    }
                    break;
                }

                case "CLIENTIPPORT":
                    if (battle != null)
                    {
                        int idx = battle.GetUserIndex(args[0]);
                        if (idx != -1)
                        {
                            UserBattleStatus bs = battle.Users[idx];
                            bs.ip             = IPAddress.Parse(args[1]);
                            bs.port           = int.Parse(args[2]);
                            battle.Users[idx] = bs;
                            if (BattleUserIpRecieved != null)
                            {
                                BattleUserIpRecieved(this, new TasEventArgs(args));
                            }
                        }
                    }
                    break;

                case "UDPSOURCEPORT":
                    udpPunchingTimer.Stop();
                    if (startingAfterUdpPunch)
                    {
                        startingAfterUdpPunch = false;
                        if (battle != null)
                        {
                            // send UDP packets to client (2x to be sure)
                            foreach (UserBattleStatus ubs in battle.Users)
                            {
                                if (ubs.ip != IPAddress.None && ubs.port != 0)
                                {
                                    SendUdpPacket(lastUdpSourcePort, ubs.ip, ubs.port);
                                }
                            }
                            foreach (UserBattleStatus ubs in battle.Users)
                            {
                                if (ubs.ip != IPAddress.None && ubs.port != 0)
                                {
                                    SendUdpPacket(lastUdpSourcePort, ubs.ip, ubs.port);
                                }
                            }

                            battle.HostPort = lastUdpSourcePort; // update source port for hosting and start it
                            ChangeMyStatus(false, true);
                        }
                    }
                    break;
                }
            } catch (Exception e) {
                if (!ErrorHandling.HandleException(e, "Exception while dispatching " + command))
                {
                    throw e;
                }
            };
        }
Exemplo n.º 26
0
 public void ThrowException()
 {
     Assert.Throws <Exception>(() => ErrorHandling.HandleErrorByThrowingException());
 }
Exemplo n.º 27
0
 /// <summary>Call like this: Translate.Key(nameof(Resources.Saved_file__0_)).</summary>
 /// <param name="key">A key in Properties.Resources</param>
 /// <param name="errorHandling">How to handle translation errors like missing key or culture.</param>
 /// <returns>A translation for the key.</returns>
 public static ITranslation TranslationFor(string key, ErrorHandling errorHandling = ErrorHandling.ReturnErrorInfoPreserveNeutral)
 {
     return(Gu.Localization.Translation.GetOrCreate(Resources.ResourceManager, key, errorHandling));
 }
Exemplo n.º 28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StaticTranslation"/> class.
 /// Note that <see cref="Translated"/> does not change when <see cref="Translator.CurrentCulture"/> changed.
 /// </summary>
 /// <param name="translated">
 /// The text will be used as <see cref="Translated"/> and returned for every culture.
 /// </param>
 /// <param name="key">Dunno if there will ever be a use case for setting key on this.</param>
 /// <param name="errorHandling">Dunno if there will ever be a use case for setting <see cref="ErrorHandling"/> on this.</param>
 public StaticTranslation(string translated, string key, ErrorHandling errorHandling = ErrorHandling.Inherit)
 {
     this.Translated    = translated;
     this.Key           = key;
     this.ErrorHandling = errorHandling;
 }
Exemplo n.º 29
0
 public BranchController()
 {
     sess = new Session_CRM();
     err  = new ErrorHandling();
 }
Exemplo n.º 30
0
 /// <summary>Returns <see cref="Translated"/> for all inputs.</summary>
 /// <param name="culture">The culture is ignored.</param>
 /// <param name="errorHandlingStrategy">The errorhandling is ignored.</param>
 /// <returns>Returns <see cref="Translated"/>.</returns>
 public string Translate(CultureInfo culture, ErrorHandling errorHandlingStrategy = ErrorHandling.Inherit)
 {
     return(this.Translated);
 }
Exemplo n.º 31
0
        // Check the constraints of any type arguments in the given Type.
        public static bool CheckConstraints(CSemanticChecker checker, ErrorHandling errHandling, CType type, CheckConstraintsFlags flags)
        {
            type = type.GetNakedType(false);

            if (type.IsNullableType())
            {
                CType typeT = type.AsNullableType().GetAts(checker.GetErrorContext());
                if (typeT != null)
                {
                    type = typeT;
                }
                else
                {
                    type = type.GetNakedType(true);
                }
            }

            if (!type.IsAggregateType())
            {
                return(true);
            }

            AggregateType ats = type.AsAggregateType();

            if (ats.GetTypeArgsAll().Count == 0)
            {
                // Common case: there are no type vars, so there are no constraints.
                ats.fConstraintsChecked = true;
                ats.fConstraintError    = false;
                return(true);
            }

            if (ats.fConstraintsChecked)
            {
                // Already checked.
                if (!ats.fConstraintError || (flags & CheckConstraintsFlags.NoDupErrors) != 0)
                {
                    // No errors or no need to report errors again.
                    return(!ats.fConstraintError);
                }
            }

            TypeArray typeVars     = ats.getAggregate().GetTypeVars();
            TypeArray typeArgsThis = ats.GetTypeArgsThis();
            TypeArray typeArgsAll  = ats.GetTypeArgsAll();

            Debug.Assert(typeVars.Count == typeArgsThis.Count);

            if (!ats.fConstraintsChecked)
            {
                ats.fConstraintsChecked = true;
                ats.fConstraintError    = false;
            }

            // Check the outer type first. If CheckConstraintsFlags.Outer is not specified and the
            // outer type has already been checked then don't bother checking it.
            if (ats.outerType != null && ((flags & CheckConstraintsFlags.Outer) != 0 || !ats.outerType.fConstraintsChecked))
            {
                CheckConstraints(checker, errHandling, ats.outerType, flags);
                ats.fConstraintError |= ats.outerType.fConstraintError;
            }

            if (typeVars.Count > 0)
            {
                ats.fConstraintError |= !CheckConstraintsCore(checker, errHandling, ats.getAggregate(), typeVars, typeArgsThis, typeArgsAll, null, (flags & CheckConstraintsFlags.NoErrors));
            }

            // Now check type args themselves.
            for (int i = 0; i < typeArgsThis.Count; i++)
            {
                CType arg = typeArgsThis[i].GetNakedType(true);
                if (arg.IsAggregateType() && !arg.AsAggregateType().fConstraintsChecked)
                {
                    CheckConstraints(checker, errHandling, arg.AsAggregateType(), flags | CheckConstraintsFlags.Outer);
                    if (arg.AsAggregateType().fConstraintError)
                    {
                        ats.fConstraintError = true;
                    }
                }
            }
            return(!ats.fConstraintError);
        }
Exemplo n.º 32
0
 public CNullable(SymbolLoader symbolLoader, ErrorHandling errorContext, ExprFactory exprFactory)
 {
     _pSymbolLoader = symbolLoader;
     _pErrorContext = errorContext;
     _exprFactory   = exprFactory;
 }
Exemplo n.º 33
0
 public ImportEngine(ErrorHandling errorHandling) {
     _errorHandling = errorHandling;
 }
Exemplo n.º 34
0
        public static async void RenderImage(SocketUser user, ISocketMessageChannel channel)
        {
            // Send a loading message while the status screen gets made
            RestUserMessage loader = await channel.SendMessageAsync("", false, LoadingMessage().Build());

            // Place the bulk of the function in a try-catch block in case something fails and an error message needs to be sent
            try
            {
                //Grab the user's account information
                var account = UserInfoClasses.GetAccount(user);

                //Establish variables to write on the template
                string username = "";

                //If the username is over 12 characters, replace the last parts with an ellipsis
                if (user.Username.Length > 12)
                {
                    username = $"{username.Substring(0, 12)}...";
                }
                else
                {
                    username = $"{user.Username}";
                }

                //Establish other variables of the user's data
                string level             = $"{account.Level}";
                int    total_exp         = account.Total_Exp;
                string profile_picture   = user.GetAvatarUrl();
                string pmedals           = $"{account.P_Medals}";
                string proficiency_title = LevelSystem.SocialStats.ProficiencyRankTitle(account.Proficiency_Rank);
                string diligence_title   = LevelSystem.SocialStats.DiligenceRankTitle(account.Diligence_Rank);
                string expression_title  = LevelSystem.SocialStats.ExpressionRankTitle(account.Expression_Rank);

                //Determine the Next Exp value
                int next_exp = 0;
                if (account.Level != 99)
                {
                    next_exp = Core.LevelSystem.Leveling.CalculateExp(account.Level + 1) - account.Total_Exp;
                }

                //If the user doesn't have a profile picture, use a default one
                if (profile_picture == null)
                {
                    profile_picture = "https://i.imgur.com/T0AjCLh.png";
                }

                // Create a base bitmap to render all the elements on
                Bitmap p3_template = new Bitmap(1920, 1080);

                //Copy the P3 status template to a bitmap
                Bitmap base_layer = (Bitmap)System.Drawing.Image.FromFile($@"{AssetDirectoryConfig.assetDirectory.assetFolderPath}//Profile//StatusScreens//Decor//Decor_P3P_1//p3p_template.png");

                //Copy the EXP bar to a bitmap
                Bitmap exp_bar = (Bitmap)System.Drawing.Image.FromFile($@"{AssetDirectoryConfig.assetDirectory.assetFolderPath}//Profile//StatusScreens//Decor//Decor_P3P_1//exp_bar.png");

                //Copy the rank bar to a bitmap
                Bitmap rank_bar = RankBarBitmap();

                //Use a graphics object to edit the bitmap
                using (Graphics graphics = Graphics.FromImage(p3_template))
                {
                    //Set text rendering to have antialiasing
                    graphics.TextRenderingHint = TextRenderingHint.AntiAlias;

                    // Create color and brush
                    System.Drawing.Color dark_red         = System.Drawing.Color.FromArgb(107, 1, 10);
                    System.Drawing.Color light_pink       = System.Drawing.Color.FromArgb(221, 29, 93);
                    SolidBrush           dark_red_brush   = new SolidBrush(dark_red);
                    SolidBrush           light_pink_brush = new SolidBrush(light_pink);

                    // Draw the first bitmap layer to the template
                    graphics.DrawImage(base_layer, 0, 0, base_layer.Width, base_layer.Height);

                    // Draw the rank titles to the bitmap.
                    using (Font p4g_font = new Font("P4G", 37))
                    {
                        graphics.DrawString(proficiency_title, p4g_font, System.Drawing.Brushes.White, new Point(348, 141));
                        graphics.DrawString(diligence_title, p4g_font, System.Drawing.Brushes.White, new Point(348, 280));
                        graphics.DrawString(expression_title, p4g_font, System.Drawing.Brushes.White, new Point(348, 411));
                    }

                    //Draw PLV text
                    using (Font street = new Font("Street Corner Extend", 25))
                    {
                        graphics.DrawString("PLV", street, dark_red_brush, new Point(190, 613));
                    }

                    //Draw level number
                    using (Font street = new Font("Street Corner Extend", 32))
                    {
                        graphics.DrawString(level, street, dark_red_brush, new Point(307, 613));
                    }

                    //Draw username
                    using (Font p4g_font = new Font("P4G", 34))
                    {
                        graphics.DrawString(username, p4g_font, dark_red_brush, new Point(492, 610));
                    }

                    //Draw "Total EXP" & "Next EXP" text, plus total EXP value
                    using (Font street = new Font("Street Corner Extend", 28))
                    {
                        graphics.DrawString("TOTAL EXP", street, dark_red_brush, new Point(237, 817));
                        graphics.DrawString("NEXT EXP", street, dark_red_brush, new Point(190, 681));

                        Rectangle    box1         = new Rectangle(550, 817, 362, 46);
                        StringFormat stringFormat = new StringFormat();
                        stringFormat.Alignment     = StringAlignment.Far;
                        stringFormat.LineAlignment = StringAlignment.Far;
                        graphics.DrawString($"{total_exp}", street, dark_red_brush, box1, stringFormat);
                    }

                    //Draw P-Medal value
                    using (Font street = new Font("Street Corner Extend", 31))
                    {
                        Rectangle    box1         = new Rectangle(817, 743, 190, 42);
                        StringFormat stringFormat = new StringFormat();
                        stringFormat.Alignment     = StringAlignment.Center;
                        stringFormat.LineAlignment = StringAlignment.Center;
                        graphics.DrawString(pmedals, street, light_pink_brush, box1, stringFormat);
                    }

                    //Draw ranks for Proficiency
                    for (int i = 0; i < account.Proficiency_Rank; i++)
                    {
                        graphics.DrawImage(rank_bar, 355 + (94 * i), 123, 87, 14);
                    }

                    //Draw ranks for Diligence
                    for (int i = 0; i < account.Diligence_Rank; i++)
                    {
                        graphics.DrawImage(rank_bar, 355 + (94 * i), 261, 87, 14);
                    }

                    //Draw ranks for Expression
                    for (int i = 0; i < account.Expression_Rank; i++)
                    {
                        graphics.DrawImage(rank_bar, 355 + (94 * i), 393, 87, 14);
                    }

                    // Draw a bitmap where the proper Next EXP progress bar overlaps with the exp_bar decorative image
                    graphics.DrawImage(KeepPixelOverlap(RenderProgressBar(user), exp_bar), 0, 0, 1920, 1080);

                    //Use a web client to download the user's profile picture and draw it to the template
                    using (var wc = new WebClient())
                    {
                        using (var imgStream = new MemoryStream(wc.DownloadData(profile_picture)))
                        {
                            using (var objImage = System.Drawing.Image.FromStream(imgStream))
                            {
                                graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
                                graphics.DrawImage(objImage, 1239, 240, 600, 600);
                            }
                        }
                    }

                    // If the user has ever reset their level, render a prestige counter to the template
                    if (account.Level_Resets > 0)
                    {
                        graphics.DrawImage(RenderPrestigeCounter(account.Level_Resets), 0, 0, 1920, 1080);
                    }
                }

                //Save the bitmap to a data stream
                MemoryStream memoryStream = new MemoryStream();
                p3_template.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
                memoryStream.Seek(0, SeekOrigin.Begin);

                //Send the image
                await channel.SendFileAsync(memoryStream, $"status_{user.Id}_{DateTime.UtcNow}.png");

                //Delete the loading message
                await loader.DeleteAsync();
            }
            catch (Exception ex)
            {
                _ = ErrorHandling.Scene_Upload_Failed(user, channel);
                Console.WriteLine(ex);

                //Delete the loading message
                await loader.DeleteAsync();

                return;
            }
        }