Ejemplo n.º 1
0
        public void UpdateColors(int width, int height)
        {
            colors = new List <Color>();
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    float normalizedX = CustomMethod.Interpolate(0f, 1f, 0f, width - 1, x);
                    float normalizedY = CustomMethod.Interpolate(1f, 0f, 0f, height - 1, y);

                    if (gradientTop != null && gradientBottom != null)
                    {
                        Color colX = gradientTop.Evaluate(normalizedX);
                        Color colY = gradientBottom.Evaluate(normalizedX);

                        Color mixed = Color.Lerp(colX, colY, normalizedY);
                        if (twoDimensional)
                        {
                            colors.Add(mixed);
                        }
                        else
                        {
                            colors.Add(colX);
                        }
                    }
                }
            }
        }
Ejemplo n.º 2
0
        private void GenerateVertex(int l, Quaternion q, float u, int r)
        {
            float normalizedLoopIndex = CustomMethod.Interpolate(0f, 1f, 0, loopAmount - 1, l);
            float normalizedRingIndex = CustomMethod.Interpolate(0f, 1f, 0, RingAmountMultipliedByCircle() - 1, r);

            float currDepth  = Mathf.LerpUnclamped(0, ClampedOuterLoopDepth(), loopPositionRemap.Evaluate(normalizedLoopIndex));
            float addedDepth = Mathf.LerpUnclamped(0, maxLoopDepth, loopDepthPositionRemap.Evaluate(normalizedLoopIndex));

            float indexWidth = Mathf.InverseLerp(0, ClampedOuterLoopDepth(), currDepth);

            float widthMultiplier = Mathf.Lerp(1, widthRemap.Evaluate(normalizedRingIndex), widthRemapInfluence);
            float currentWidth    = Mathf.LerpUnclamped(minRadius, Mathf.LerpUnclamped(minRadius, maxRadius, widthMultiplier), loopHeightPositionRemap.Evaluate(indexWidth));

            float currentTwist = Mathf.LerpUnclamped(0, twist, normalizedLoopIndex);

            Quaternion twistRot = Quaternion.AngleAxis(currentTwist, Vector3.back);

            Vector3 newVert = (q * twistRot) * (Vector3.up * currentWidth) + new Vector3(0, 0, currDepth + depthByU * u + addedDepth);

            float   maxOffset    = 0.5f;
            float   randomOffset = Random.Range(-maxOffset, maxOffset);
            Vector3 debugOffset  = new Vector3(0, 0, randomOffset);

            AddVertex(newVert);

            if (!invertUAndV)
            {
                uv.Add(new Vector2(u, normalizedLoopIndex));
            }

            else
            {
                uv.Add(new Vector2(normalizedLoopIndex, u));
            }
        }
Ejemplo n.º 3
0
        public async Task LFC(CommandContext ctx, DiscordMember username = null)
        {
            await ctx.Message.DeleteAsync();

            await ctx.TriggerTypingAsync();

            string      content = CustomMethod.GetCommandOutput(ctx, "lfc2", null, username);
            DiscordRole pc      = ctx.Guild.GetRole(223867454642716673);
            DiscordRole ps      = ctx.Guild.GetRole(223867009484587008);
            DiscordRole xb      = ctx.Guild.GetRole(223867264246611970);
            bool        check   = false;

            if (username == null)
            {
                username = ctx.Member;
            }
            foreach (var item in username.Roles)
            {
                if ((item == pc || item == ps || item == xb) && !check)
                {
                    content = CustomMethod.GetCommandOutput(ctx, "lfc1", null, username);
                    check   = true;
                }
            }
            await new DiscordMessageBuilder()
            .WithContent(content)
            .WithAllowedMention(new UserMention())
            .SendAsync(ctx.Channel);
        }
Ejemplo n.º 4
0
        private Uri PrepareUri(Uri uri)
        {
            uri = CheckProtocol(uri);

            // before creating the web request,
            // preprocess Body if content is a dictionary and method is GET (set as query)
            IDictionary bodyAsDictionary;

            LanguagePrimitives.TryConvertTo <IDictionary>(Body, out bodyAsDictionary);
            if ((null != bodyAsDictionary) &&
                ((IsStandardMethodSet() && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get)) ||
                 (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "GET")))
            {
                UriBuilder uriBuilder = new UriBuilder(uri);
                if (uriBuilder.Query != null && uriBuilder.Query.Length > 1)
                {
                    uriBuilder.Query = uriBuilder.Query.Substring(1) + "&" + FormatDictionary(bodyAsDictionary);
                }
                else
                {
                    uriBuilder.Query = FormatDictionary(bodyAsDictionary);
                }
                uri = uriBuilder.Uri;
                // set body to null to prevent later FillRequestStream
                Body = null;
            }

            return(uri);
        }
Ejemplo n.º 5
0
        //[Cooldown(1, 5, CooldownBucketType.Guild)]
        public async Task Warning(CommandContext ctx, DiscordUser username, [RemainingText] string reason = "Reason not specified")
        {
            await ctx.Message.DeleteAsync();

            await ctx.TriggerTypingAsync();

            await CustomMethod.WarnUserAsync(username, ctx.Member, ctx.Guild, ctx.Channel, reason, false);
        }
Ejemplo n.º 6
0
        public async Task Background(CommandContext ctx, int?page = null)
        {
            if (page == null || page <= 0)
            {
                page = 1;
            }
            var msgBuilder = new DiscordMessageBuilder()
                             .WithContent(CustomMethod.GetBackgroundList(ctx, (int)page))
                             .WithReply(ctx.Message.Id, true);
            DiscordMessage TopMessage = await ctx.RespondAsync(msgBuilder);

            DiscordEmoji left  = DiscordEmoji.FromName(ctx.Client, ":arrow_left:");
            DiscordEmoji right = DiscordEmoji.FromName(ctx.Client, ":arrow_right:");

            await TopMessage.CreateReactionAsync(left);

            await Task.Delay(300).ContinueWith(t => TopMessage.CreateReactionAsync(right));

            bool end = false;

            do
            {
                var result = TopMessage.WaitForReactionAsync(ctx.User, TimeSpan.FromSeconds(20));
                if (result.Result.TimedOut)
                {
                    end = result.Result.TimedOut;
                }
                else if (result.Result.Result.Emoji == left)
                {
                    await TopMessage.DeleteReactionAsync(result.Result.Result.Emoji, ctx.User);

                    if (page > 1)
                    {
                        page--;
                        await TopMessage.ModifyAsync(CustomMethod.GetBackgroundList(ctx, (int)page));
                    }
                }
                else if (result.Result.Result.Emoji == right)
                {
                    await TopMessage.DeleteReactionAsync(result.Result.Result.Emoji, ctx.User);

                    page++;
                    try
                    {
                        await TopMessage.ModifyAsync(CustomMethod.GetBackgroundList(ctx, (int)page));
                    }
                    catch (Exception)
                    {
                        page--;
                    }
                }
            } while (!end);
            await TopMessage.DeleteAllReactionsAsync();
        }
Ejemplo n.º 7
0
        public async Task GetKicks(CommandContext ctx, DiscordUser User)
        {
            await ctx.Message.DeleteAsync();

            await ctx.TriggerTypingAsync();

            await new DiscordMessageBuilder()
            .WithContent($"{ctx.User.Mention}")
            .WithEmbed(CustomMethod.GetUserWarnings(ctx.Guild, User, true))
            .WithAllowedMention(new UserMention())
            .SendAsync(ctx.Channel);
        }
Ejemplo n.º 8
0
        private void AddMainVertices()
        {
            float angle = 360f / (RingAmountMultipliedByCircle() - 1);
            float mul   = arc / 360f;

            for (int l = 0; l < loopAmount; l++)
            {
                for (int r = 0; r < RingAmountMultipliedByCircle(); r++)
                {
                    float      curveRemapEvaluate = CustomMethod.Interpolate(0f, 1f, 0f, RingAmountMultipliedByCircle() - 1, r);
                    float      curveValue         = ringPositionRemap.Evaluate(curveRemapEvaluate);
                    float      u = CustomMethod.Interpolate(0, 1f, 0, RingAmountMultipliedByCircle() - 1, r);
                    Quaternion q = Quaternion.AngleAxis(spiralAmount * angle * (curveValue * (RingAmountMultipliedByCircle() - 1)) * mul, Vector3.back);
                    GenerateVertex(l, q, u, r);
                }
            }
        }
Ejemplo n.º 9
0
        public async Task MyWarnings(CommandContext ctx)
        {
            await ctx.Message.DeleteAsync();

            await ctx.TriggerTypingAsync();

            try
            {
                await ctx.Member.SendMessageAsync(embed : CustomMethod.GetUserWarnings(ctx.Guild, ctx.User));
            }
            catch
            {
                await new DiscordMessageBuilder()
                .WithContent($"{ctx.Member.Mention}, Could not contact you through DMs.")
                .WithAllowedMention(new UserMention())
                .SendAsync(ctx.Channel);
            }
        }
Ejemplo n.º 10
0
        public async Task ProSettings(CommandContext ctx, DiscordMember username = null)
        {
            await ctx.Message.DeleteAsync();

            await ctx.TriggerTypingAsync();

            string content;

            if (username is null)
            {
                content = CustomMethod.GetCommandOutput(ctx, "prosettings", null, ctx.Member);
            }
            else
            {
                content = CustomMethod.GetCommandOutput(ctx, "prosettings", null, username);
            }
            await new DiscordMessageBuilder()
            .WithContent(content)
            .WithAllowedMention(new UserMention())
            .SendAsync(ctx.Channel);
        }
Ejemplo n.º 11
0
        public async Task TCE(CommandContext ctx, [Description("Specifies the user the bot will mention, use ID or mention the user. If left blank, it will mention you.")] DiscordMember username = null, [Description("Specifies in what language the bot will respond. example, fr-french")] string language = null)
        {
            await ctx.Message.DeleteAsync();

            await ctx.TriggerTypingAsync();

            string content;

            if (username is null)
            {
                content = CustomMethod.GetCommandOutput(ctx, "tce", language, ctx.Member);
            }
            else
            {
                content = CustomMethod.GetCommandOutput(ctx, "tce", language, username);
            }
            await new DiscordMessageBuilder()
            .WithContent(content)
            .WithAllowedMention(new UserMention())
            .SendAsync(ctx.Channel);
        }
Ejemplo n.º 12
0
    public override void StateUpdate()
    {
        base.StateUpdate();
        //!_navMeshAgent.pathPending && _navMeshAgent.remainingDistance < 0.1f && _enemyFieldOfView.HasTargetOnSight)
        if (CustomMethod.AlmostEqual(_enemy.transform.position, m_iniPos, 0.2f))
        {
            Debug.Log("On destination", this);
            //_navMeshAgent.isStopped = true;
            _enemy.transform.position    = m_iniPos;
            _enemy.transform.eulerAngles = m_iniRot;
        }
        else
        {
            _navMeshAgent.destination = m_iniPos;
        }

        if (_enemyFieldOfView.HasTargetOnSight)
        {
            OnStateEnd();
        }
    }
Ejemplo n.º 13
0
        protected virtual void Validate_4_ParameterLayout()
        {
            var requredParameterLayout = GetRequiredParameterLayout().ToList();
            var foundParameterLayout   = CustomMethod.GetParameters();
            var valid = requredParameterLayout.Count == foundParameterLayout.Length;

            for (var i = 0; (i < foundParameterLayout.Length) && valid; i++)
            {
                if (requredParameterLayout[i].ParameterType.IsByRef)
                {
                    if (foundParameterLayout[i].ParameterType.GetElementType() != requredParameterLayout[i].ParameterType.GetElementType())
                    {
                        valid = false;
                    }
                    if ((HookType != MethodHookType.RunAfter) && (foundParameterLayout[i].IsOut != requredParameterLayout[i].IsOut))
                    {
                        valid = false;
                    }
                }
                else if (foundParameterLayout[i].ParameterType != requredParameterLayout[i].ParameterType)
                {
                    if (!foundParameterLayout[i].ParameterType.IsValueType && !requredParameterLayout[i].ParameterType.IsValueType && requredParameterLayout[i].ParameterType.IsSubclassOf(foundParameterLayout[i].ParameterType))
                    {
                        //should be simple ptr stuff & fine to "convert". We can allow this
                    }
                    else
                    {
                        valid = false;
                    }
                }
            }
            if (!valid)
            {
                Func <IEnumerable <CustomParameterInfo>, String> toString = (f) =>
                {
                    return(f.Select(t => t == null ? "NULL" : ((t.IsOut ? "out " : (t.ParameterType.IsByRef ? "ref " : "")) + (t.ParameterType.IsByRef ? t.ParameterType.GetElementType() : t.ParameterType).FullName)).Aggregate((f1, f2) => f1 + ", " + f2));
                };
                throw new ArgumentException("Invalid parameter Layout for method [" + MethodReferenceToString(CustomMethod) + "]! Expected [" + toString(requredParameterLayout) + "], got [" + toString(foundParameterLayout.Select(el => (CustomParameterInfo)el)) + "].");
            }
        }
Ejemplo n.º 14
0
 public static async Task Add_To_Leaderboards(object O, GuildMemberAddEventArgs e)
 {
     _ = Task.Run(() =>
     {
         var global = (from lb in DB.DBLists.Leaderboard.AsParallel()
                       where lb.ID_User == e.Member.Id
                       select lb).FirstOrDefault();
         if (global is null)
         {
             CustomMethod.AddUserToLeaderboard(e.Member);
         }
         var local = (from lb in DB.DBLists.ServerRanks.AsParallel()
                      where lb.User_ID == e.Member.Id
                      where lb.Server_ID == e.Guild.Id
                      select lb).FirstOrDefault();
         if (local is null)
         {
             CustomMethod.AddUserToServerRanks(e.Member, e.Guild);
         }
     });
     await Task.Delay(1);
 }
Ejemplo n.º 15
0
    public void ShootOnTarget(Vector3 p_targetPos)
    {
        if (Time.time - m_lastfired <= 1 / m_weaponData.FireRate)
        {
            return;
        }

        if (OutOfAmmo)
        {
            Reload();
            return;
        }

        m_currentAmmo--;
        m_lastfired = Time.time;
        Vector3 l_recoil        = new Vector3(Recoil(), Recoil(), 0);
        Vector3 l_shotDirection = CustomMethod.GetNormalizedDirection(transform.position, (p_targetPos + l_recoil));
        Ray     l_ray           = new Ray(transform.position, l_shotDirection);

        Physics.Raycast(l_ray, out RaycastHit l_hit, m_weaponData.Range, m_targetLayer, QueryTriggerInteraction.Collide);
        Debug.DrawRay(l_ray.origin, l_ray.direction * m_weaponData.Range, Color.magenta, 3);

        if (l_hit.collider != null)
        {
            IDamagable damagable = l_hit.transform.GetComponent <IDamagable>();

            if (damagable != null)
            {
                damagable.TakeDamage(new DamageInfo(m_weaponData.Damage, l_hit.point, l_hit.normal));
            }
        }

        //FX
        shootSfx?.Play();
        flashFx?.Play();
    }
        internal virtual void FillRequestStream(HttpRequestMessage request)
        {
            if (null == request)
            {
                throw new ArgumentNullException("request");
            }

            // set the content type
            if (ContentType != null)
            {
                WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = ContentType;
                //request
            }
            // ContentType == null
            else if (Method == WebRequestMethod.Post || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "POST"))
            {
                // Win8:545310 Invoke-WebRequest does not properly set MIME type for POST
                string contentType = null;
                WebSession.ContentHeaders.TryGetValue(HttpKnownHeaderNames.ContentType, out contentType);
                if (string.IsNullOrEmpty(contentType))
                {
                    WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = "application/x-www-form-urlencoded";
                }
            }

            // coerce body into a usable form
            if (Body != null)
            {
                object content = Body;

                // make sure we're using the base object of the body, not the PSObject wrapper
                PSObject psBody = Body as PSObject;
                if (psBody != null)
                {
                    content = psBody.BaseObject;
                }

                /* TODO: This needs to be enable after the dependency on mshtml is resolved.
                 * var html = content as HtmlWebResponseObject;
                 * if (html != null)
                 * {
                 *  // use the form if it's the only one present
                 *  if (html.Forms.Count == 1)
                 *  {
                 *      SetRequestContent(request, html.Forms[0].Fields);
                 *  }
                 * }
                 * else if (content is FormObject)
                 */

                if (content is FormObject)
                {
                    FormObject form = content as FormObject;
                    SetRequestContent(request, form.Fields);
                }
                else if (content is IDictionary && request.Method != HttpMethod.Get)
                {
                    IDictionary dictionary = content as IDictionary;
                    SetRequestContent(request, dictionary);
                }
                else if (content is XmlNode)
                {
                    XmlNode xmlNode = content as XmlNode;
                    SetRequestContent(request, xmlNode);
                }
                else if (content is Stream)
                {
                    Stream stream = content as Stream;
                    SetRequestContent(request, stream);
                }
                else if (content is byte[])
                {
                    byte[] bytes = content as byte[];
                    SetRequestContent(request, bytes);
                }
                else if (content is MultipartFormDataContent multipartFormDataContent)
                {
                    WebSession.ContentHeaders.Clear();
                    SetRequestContent(request, multipartFormDataContent);
                }
                else
                {
                    SetRequestContent(request,
                                      (string)LanguagePrimitives.ConvertTo(content, typeof(string), CultureInfo.InvariantCulture));
                }
            }
            else if (InFile != null) // copy InFile data
            {
                try
                {
                    // open the input file
                    SetRequestContent(request, new FileStream(InFile, FileMode.Open));
                }
                catch (UnauthorizedAccessException)
                {
                    string msg = string.Format(CultureInfo.InvariantCulture, WebCmdletStrings.AccessDenied,
                                               _originalFilePath);
                    throw new UnauthorizedAccessException(msg);
                }
            }

            // Add the content headers
            if (request.Content != null)
            {
                foreach (var entry in WebSession.ContentHeaders)
                {
                    request.Content.Headers.Add(entry.Key, entry.Value);
                }
            }
        }
        internal virtual HttpRequestMessage GetRequest(Uri uri, bool stripAuthorization)
        {
            Uri        requestUri = PrepareUri(uri);
            HttpMethod httpMethod = null;

            switch (ParameterSetName)
            {
            case "StandardMethodNoProxy":
                goto case "StandardMethod";

            case "StandardMethod":
                // set the method if the parameter was provided
                httpMethod = GetHttpMethod(Method);
                break;

            case "CustomMethodNoProxy":
                goto case "CustomMethod";

            case "CustomMethod":
                if (!string.IsNullOrEmpty(CustomMethod))
                {
                    // set the method if the parameter was provided
                    httpMethod = new HttpMethod(CustomMethod.ToString().ToUpperInvariant());
                }
                break;
            }

            // create the base WebRequest object
            var request = new HttpRequestMessage(httpMethod, requestUri);

            // pull in session data
            if (WebSession.Headers.Count > 0)
            {
                WebSession.ContentHeaders.Clear();
                foreach (var entry in WebSession.Headers)
                {
                    if (HttpKnownHeaderNames.ContentHeaders.Contains(entry.Key))
                    {
                        WebSession.ContentHeaders.Add(entry.Key, entry.Value);
                    }
                    else
                    {
                        if (stripAuthorization
                            &&
                            String.Equals(entry.Key, HttpKnownHeaderNames.Authorization.ToString(), StringComparison.OrdinalIgnoreCase)
                            )
                        {
                            continue;
                        }

                        if (SkipHeaderValidation)
                        {
                            request.Headers.TryAddWithoutValidation(entry.Key, entry.Value);
                        }
                        else
                        {
                            request.Headers.Add(entry.Key, entry.Value);
                        }
                    }
                }
            }

            // Set 'Transfer-Encoding: chunked' if 'Transfer-Encoding' is specified
            if (WebSession.Headers.ContainsKey(HttpKnownHeaderNames.TransferEncoding))
            {
                request.Headers.TransferEncodingChunked = true;
            }

            // Set 'User-Agent' if WebSession.Headers doesn't already contain it
            string userAgent = null;

            if (WebSession.Headers.TryGetValue(HttpKnownHeaderNames.UserAgent, out userAgent))
            {
                WebSession.UserAgent = userAgent;
            }
            else
            {
                if (SkipHeaderValidation)
                {
                    request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.UserAgent, WebSession.UserAgent);
                }
                else
                {
                    request.Headers.Add(HttpKnownHeaderNames.UserAgent, WebSession.UserAgent);
                }
            }

            // Set 'Keep-Alive' to false. This means set the Connection to 'Close'.
            if (DisableKeepAlive)
            {
                request.Headers.Add(HttpKnownHeaderNames.Connection, "Close");
            }

            // Set 'Transfer-Encoding'
            if (TransferEncoding != null)
            {
                request.Headers.TransferEncodingChunked = true;
                var headerValue = new TransferCodingHeaderValue(TransferEncoding);
                if (!request.Headers.TransferEncoding.Contains(headerValue))
                {
                    request.Headers.TransferEncoding.Add(headerValue);
                }
            }

            // Some web sites (e.g. Twitter) will return exception on POST when Expect100 is sent
            // Default behavior is continue to send body content anyway after a short period
            // Here it send the two part as a whole.
            request.Headers.ExpectContinue = false;

            return(request);
        }
Ejemplo n.º 18
0
 private void OnDrawGizmos()
 {
     m_collider   = GetComponent <BoxCollider>();
     Gizmos.color = CustomMethod.GetColorWithAlpha(m_colliderColor, m_alpha);
     Gizmos.DrawCube(transform.position + m_collider.center, m_collider.size);
 }
Ejemplo n.º 19
0
        public AddProd()
        {
            var     db      = new NorthwindContext();
            Product product = new Product();

            Console.Clear();
            Console.WriteLine("Northwind Products - Add a Product\n");
            do
            {
                try
                {
                    Console.WriteLine("Enter the Category Id for this product:");

                    s = DisplayCat.DispCatSel(); // display the list of categories

                    if (CustomMethod.IsInt(s))
                    {
                        id = Int16.Parse(s);                            // try to parse
                        if (db.Categories.Any(p => p.CategoryId == id)) //validate the ID entered
                        {
                            Console.Clear();
                            Category category = db.Categories.FirstOrDefault(c => c.CategoryId == id);
                            logger.Info($"CategoryId {id} selected");
                            categoryname       = category.CategoryName;
                            product.CategoryId = id;
                            badentry           = false;
                            break;
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("** Incorrect CategoryID selected");
                            logger.Info($"Incorrect CategoryId selected");
                            Console.ResetColor();
                        }
                    }
                }
                catch
                {
                    logger.Info($"incorrect CategoryId selected");
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("** Incorrect CategoryID selected");
                    Console.ResetColor();
                }
            } while (badentry);


            badentry = true;

            Console.WriteLine("\n\nNorthwind Products - Add a Product\n");
            Console.WriteLine($"\tCategoryId: {product.CategoryId} {categoryname}");
            Console.WriteLine("\nEnter the Supplier Id for this product:");
            do
            {
                try
                {
                    s = DisplaySup.DisplaySupSel(); // display the list of Suppliers
                    if (CustomMethod.IsBlank(s))
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("** Must enter something");
                        logger.Info("blank supplier entered");
                        Console.ResetColor();
                    }
                    else
                    {
                        id = Int16.Parse(s);                           // try to parse
                        if (db.Suppliers.Any(p => p.SupplierId == id)) //validate the ID entered
                        {
                            Supplier supplier = db.Suppliers.FirstOrDefault(c => c.SupplierId == id);
                            Console.Clear();
                            suppliername = supplier.CompanyName;
                            logger.Info($"SupplierId {id} selected");
                            product.SupplierId = id;
                            badentry           = false;
                            break;
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("** Incorrect SupplierID selected");
                            logger.Info($"Incorrect SupplierId selected");
                            Console.ResetColor();
                        }
                    }
                }
                catch
                {
                    logger.Info($"incorrect SupplierId selected");
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("** Incorrect SupplierID selected");
                    Console.ResetColor();
                }
            } while (badentry);


            Console.Clear();
            Console.WriteLine("\n\nNorthwind Products - Add a Product\n");
            Console.WriteLine($"\tCategoryId: {product.CategoryId} {categoryname}");
            Console.WriteLine($"\tSupplier Id: {product.SupplierId} {suppliername}");


            do
            {
                Console.WriteLine("\nProduct Name:");  //validate the product name
                s = Console.ReadLine();
                product.ProductName = s;

                if (CustomMethod.IsBlank(s))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("** Must enter something");
                    logger.Info("blank Name entered");
                    Console.ResetColor();
                }
            } while (CustomMethod.IsBlank(s));


            Console.Clear();
            Console.WriteLine("\n\nNorthwind Products - Add a Product\n");
            Console.WriteLine($"Product Name: {product.ProductName}");
            Console.WriteLine($"\tCategoryId: {product.CategoryId} {categoryname}");
            Console.WriteLine($"\tSupplier Id: {product.SupplierId} {suppliername}");

            do
            {
                Console.WriteLine("\nEnter the Quantity Per Unit - Example 24 per box:"); // qty per unit

                s = Console.ReadLine();
                product.QuantityPerUnit = s;
                if (CustomMethod.IsBlank(s))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("** Must enter something");
                    Console.ResetColor();
                    logger.Info("blank Qty Per Unit entered");
                }
            } while (CustomMethod.IsBlank(s));

            Console.Clear();
            Console.WriteLine("\n\nNorthwind Products - Add a Product\n");
            Console.WriteLine($"Product Name: {product.ProductName}");
            Console.WriteLine($"\tCategoryId: {product.CategoryId} {categoryname}");
            Console.WriteLine($"\tSupplier Id: {product.SupplierId} {suppliername}");
            Console.WriteLine($"\tQuantity Per Unit: {product.QuantityPerUnit}");
            do
            {
                Console.WriteLine("\nUnit Price as 0.00:");  // unit price
                s = Console.ReadLine();

                if (CustomMethod.IsDec(s))
                {
                    logger.Info($"Good Price Entered {s}");
                    product.UnitPrice = Convert.ToDecimal(s);
                    logger.Info($"{s} Unit Price");
                }
                else
                {
                    logger.Info($"bad Price Entered {s}");
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Not a Decimal");
                    Console.ResetColor();
                }
            } while (!CustomMethod.IsDec(s));

            Console.Clear();
            Console.WriteLine("\n\nNorthwind Products - Add a Product\n");
            Console.WriteLine($"Product Name: {product.ProductName}");
            Console.WriteLine($"\tCategoryId: {product.CategoryId} {categoryname}");
            Console.WriteLine($"\tSupplier Id: {product.SupplierId} {suppliername}");
            Console.WriteLine($"\tQuantity Per Unit: {product.QuantityPerUnit}");
            Console.WriteLine($"\tUnit Price: {product.UnitPrice}");
            do
            {
                Console.WriteLine("\nEnter the number of Units In Stock:"); // units in stock
                s = Console.ReadLine();

                if (CustomMethod.IsInt(s))
                {
                    logger.Info($"Units In Stock {s}");
                    product.UnitsInStock = Convert.ToInt16(s);
                }
                else
                {
                    logger.Info($"bad Units in Stock Entered {s}");
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("** Not a valid number");
                    Console.ResetColor();
                }
            } while (!CustomMethod.IsInt(s));

            Console.Clear();
            Console.WriteLine("\n\nNorthwind Products - Add a Product\n");
            Console.WriteLine($"Product Name: {product.ProductName}");
            Console.WriteLine($"\tCategoryId: {product.CategoryId} {categoryname}");
            Console.WriteLine($"\tSupplier Id: {product.SupplierId} {suppliername}");
            Console.WriteLine($"\tQuantity Per Unit: {product.QuantityPerUnit}");
            Console.WriteLine($"\tUnit Price: {product.UnitPrice}");
            Console.WriteLine($"\tUnits In Stock: {product.UnitsInStock}");
            do
            {
                Console.WriteLine("\nEnter the number of Units On Order:"); // units on order
                s = Console.ReadLine();
                if (CustomMethod.IsInt(s))
                {
                    logger.Info($"Units On Order {s}");
                    product.UnitsOnOrder = Convert.ToInt16(s);
                }
                else
                {
                    logger.Info($"bad Units On Order Entered {s}");
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("** Not a valid number");
                    Console.ResetColor();
                }
            } while (!CustomMethod.IsInt(s));

            Console.Clear();
            Console.WriteLine("\n\nNorthwind Products - Add a Product\n");
            Console.WriteLine($"Product Name: {product.ProductName}");
            Console.WriteLine($"\tCategoryId: {product.CategoryId} {categoryname}");
            Console.WriteLine($"\tSupplier Id: {product.SupplierId} {suppliername}");
            Console.WriteLine($"\tQuantity Per Unit: {product.QuantityPerUnit}");
            Console.WriteLine($"\tUnit Price: {product.UnitPrice}");
            Console.WriteLine($"\tUnits In Stock: {product.UnitsInStock}");
            Console.WriteLine($"\tUnits On Order: {product.UnitsOnOrder}");
            do
            {
                Console.WriteLine("\nEnter the Reorder Level count:");  // reorder count
                s = Console.ReadLine();

                if (CustomMethod.IsInt(s))
                {
                    logger.Info($"Reorder Level {s}");
                    product.ReorderLevel = Convert.ToInt16(s);
                }
                else
                {
                    logger.Info($"bad Reorder Level {s}");
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("** Not a valid number");
                    Console.ResetColor();
                }
            } while (!CustomMethod.IsInt(s));

            Console.Clear();
            Console.WriteLine("\n\nNorthwind Products - Add a Product\n");
            Console.WriteLine($"Product Name: {product.ProductName}");
            Console.WriteLine($"\tCategoryId: {product.CategoryId} {categoryname}");
            Console.WriteLine($"\tSupplier Id: {product.SupplierId} {suppliername}");
            Console.WriteLine($"\tQuantity Per Unit: {product.QuantityPerUnit}");
            Console.WriteLine($"\tUnit Price: {product.UnitPrice}");
            Console.WriteLine($"\tUnits In Stock: {product.UnitsInStock}");
            Console.WriteLine($"\tUnits On Order: {product.UnitsOnOrder}");
            Console.WriteLine($"\tReOrder Level: {product.ReorderLevel}");


            product.Discontinued = false;
            Console.WriteLine("\nIs the Item Discontinued?  Y or anything else for Active");
            string disc = Console.ReadLine();

            disc = disc.ToLower();
            if (disc == "y")
            {
                product.Discontinued = true;
            }

            ValidationContext       context = new ValidationContext(product, null, null); // what do I want to validate? = product put product in our context
            List <ValidationResult> results = new List <ValidationResult>();

            var isValid = Validator.TryValidateObject(product, context, results, true); // validate product and return it to results = bool

            if (isValid)
            {
                db = new NorthwindContext();
                db.Products.Add(product);
                var erro = db.GetValidationErrors();
                if (erro.Any())
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(erro);
                    Console.ResetColor();
                }

                // check for unique name
                if (db.Products.Any(c => c.ProductName == product.ProductName))
                {
                    // generate validation error
                    isValid = false;
                    Console.ForegroundColor = ConsoleColor.Red;
                    results.Add(new ValidationResult("****Sorry this Product Name exists - Please try again ", new string[] { "ProductName" }));
                    Console.ResetColor();
                }
                else

                {
                    logger.Info("Validation passed");

                    db.SaveChanges();
                    Console.Clear();
                }
            }

            if (!isValid)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("* PRODUCT NOT ADDED *");
                foreach (var result in results)
                {
                    logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}");
                    Console.WriteLine($"ERROR: {result.ErrorMessage}");
                }
                Console.ResetColor();
                Console.ReadLine();
            }
        }
Ejemplo n.º 20
0
        internal virtual WebRequest GetRequest(Uri uri)
        {
            uri = PrepareUri(uri);
            // create the base WebRequest object
            WebRequest request = WebRequest.Create(uri);

            // pull in session data
            if (0 < WebSession.Headers.Count)
            {
                try
                {
                    HttpWebRequest webRequest = request as HttpWebRequest;
                    request.Headers.Clear();
                    foreach (string key in WebSession.Headers.Keys)
                    {
                        bool setHeaderViaProperty = TryMapHeaderToProperty(webRequest, key);

                        if (!setHeaderViaProperty)
                        {
                            request.Headers[key] = WebSession.Headers[key];
                        }
                    }
                }
                catch (NotImplementedException)
                {
                }
            }

            // set the credentials used by this request
            if (WebSession.UseDefaultCredentials)
            {
                // the UseDefaultCredentials flag overrides other supplied credentials
                request.UseDefaultCredentials = true;
            }
            else if (null != WebSession.Credentials)
            {
                request.Credentials = WebSession.Credentials;
            }

            if (null != WebSession.Proxy)
            {
                request.Proxy = WebSession.Proxy;
            }

            switch (ParameterSetName)
            {
            case "StandardMethod":
                if (WebRequestMethod.Default != Method)
                {
                    // set the method if the parameter was provided
                    request.Method = Method.ToString().ToUpperInvariant();
                }
                break;

            case "CustomMethod":
                // set the method if the parameter was provided
                request.Method = CustomMethod.ToUpperInvariant();
                break;
            }

            // pull in http specific properties
            HttpWebRequest httpRequest = request as HttpWebRequest;

            if (null != httpRequest)
            {
                httpRequest.CookieContainer = WebSession.Cookies;
                httpRequest.UserAgent       = WebSession.UserAgent;

                if (null != WebSession.Certificates)
                {
                    httpRequest.ClientCertificates = WebSession.Certificates;
                }

                if (-1 < WebSession.MaximumRedirection)
                {
                    if (WebSession.MaximumRedirection == 0)
                    {
                        httpRequest.AllowAutoRedirect = false;
                    }
                    else
                    {
                        httpRequest.MaximumAutomaticRedirections = WebSession.MaximumRedirection;
                    }
                }

                // check timeout setting (in seconds instead of milliseconds as in HttpWebRequest)
                if (TimeoutSec == 0)
                {
                    // A zero timeout means infinite
                    httpRequest.Timeout = Timeout.Infinite;
                }
                else if (TimeoutSec > 0)
                {
                    // just to make sure
                    if (TimeoutSec > Int32.MaxValue / 1000)
                    {
                        httpRequest.Timeout = Int32.MaxValue;
                    }
                    else
                    {
                        httpRequest.Timeout = TimeoutSec * 1000;
                    }
                }

                // check keep-alive setting
                if (DisableKeepAlive)
                {
                    // default value is true, so only need to set if false.
                    httpRequest.KeepAlive = false;
                }

                if (null != TransferEncoding)
                {
                    httpRequest.SendChunked      = true;
                    httpRequest.TransferEncoding = TransferEncoding;
                }
            }

            return(request);
        }
Ejemplo n.º 21
0
        internal virtual void FillRequestStream(WebRequest request)
        {
            if (null == request)
            {
                throw new ArgumentNullException("request");
            }

            // set the content type
            if (null != ContentType)
            {
                request.ContentType = ContentType;
            }
            // ContentType == null
            else if ((IsStandardMethodSet() && Method == WebRequestMethod.Post) ||
                     (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "POST"))
            {
                // Win8:545310 Invoke-WebRequest does not properly set MIME type for POST
                if (String.IsNullOrEmpty(request.ContentType))
                {
                    request.ContentType = "application/x-www-form-urlencoded";
                }
            }

            // coerce body into a usable form
            if (null != Body)
            {
                object content = Body;

                // make sure we're using the base object of the body, not the PSObject wrapper
                PSObject psBody = Body as PSObject;
                if (null != psBody)
                {
                    content = psBody.BaseObject;
                }

                if (null != content as HtmlWebResponseObject)
                {
                    HtmlWebResponseObject html = content as HtmlWebResponseObject;
                    // use the form it's the only one present
                    if (html.Forms.Count == 1)
                    {
                        SetRequestContent(request, html.Forms[0].Fields);
                    }
                }
                else if (null != content as FormObject)
                {
                    FormObject form = content as FormObject;
                    SetRequestContent(request, form.Fields);
                }
                else if (null != content as IDictionary && request.Method != WebRequestMethods.Http.Get)
                {
                    IDictionary dictionary = content as IDictionary;
                    SetRequestContent(request, dictionary);
                }
                else if (null != content as XmlNode)
                {
                    XmlNode xmlNode = content as XmlNode;
                    SetRequestContent(request, xmlNode);
                }
                else if (null != content as Stream)
                {
                    Stream stream = content as Stream;
                    SetRequestContent(request, stream);
                }
                else if (null != content as byte[])
                {
                    byte[] bytes = content as byte[];
                    SetRequestContent(request, bytes);
                }
                else
                {
                    SetRequestContent(request,
                                      (string)LanguagePrimitives.ConvertTo(content, typeof(string), CultureInfo.InvariantCulture));
                }
            }
            else if (null != InFile) // copy InFile data
            {
                try
                {
                    // open the input file
                    using (FileStream fs = new FileStream(InFile, FileMode.Open))
                    {
                        SetRequestContent(request, fs);
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    string msg = string.Format(CultureInfo.InvariantCulture, WebCmdletStrings.AccessDenied,
                                               _originalFilePath);
                    throw new UnauthorizedAccessException(msg);
                }
            }
            else
            {
                request.ContentLength = 0;
            }
        }
Ejemplo n.º 22
0
        public async Task Summit(CommandContext ctx)
        {
            await ctx.TriggerTypingAsync();

            string PCJson = string.Empty, XBJson = string.Empty, PSJson = string.Empty, StadiaJson = string.Empty;
            string imageLoc = $"{Program.tmpLoc}{ctx.User.Id}-summit.png";

            byte[]   SummitLogo;
            DateTime endtime;

            int platforms = 4;

            using (WebClient wc = new())
            {
                List <TCHubJson.Summit> JSummit = Program.JSummit;
                PCJson = wc.DownloadString($"https://api.thecrew-hub.com/v1/summit/{JSummit[0].ID}/score/pc/profile/a92d844e-9c57-4b8c-a249-108ef42d4500");
                XBJson = wc.DownloadString($"https://api.thecrew-hub.com/v1/summit/{JSummit[0].ID}/score/x1/profile/a92d844e-9c57-4b8c-a249-108ef42d4500");
                PSJson = wc.DownloadString($"https://api.thecrew-hub.com/v1/summit/{JSummit[0].ID}/score/ps4/profile/a92d844e-9c57-4b8c-a249-108ef42d4500");
                try
                {
                    StadiaJson = wc.DownloadString($"https://api.thecrew-hub.com/v1/summit/{JSummit[0].ID}/score/stadia/profile/a92d844e-9c57-4b8c-a249-108ef42d4500");
                }
                catch (Exception)
                {
                    platforms = 3;
                }

                SummitLogo = wc.DownloadData($"https://www.thecrew-hub.com/gen/assets/summits/{JSummit[0].Cover_Small}");

                endtime = CustomMethod.EpochConverter(JSummit[0].End_Date * 1000);
            }
            TCHubJson.Rank[] Events = Array.Empty <TCHubJson.Rank>();
            if (platforms == 4)
            {
                Events = new TCHubJson.Rank[4] {
                    JsonConvert.DeserializeObject <TCHubJson.Rank>(PCJson), JsonConvert.DeserializeObject <TCHubJson.Rank>(PSJson), JsonConvert.DeserializeObject <TCHubJson.Rank>(XBJson), JsonConvert.DeserializeObject <TCHubJson.Rank>(StadiaJson)
                };
            }
            else
            {
                Events = new TCHubJson.Rank[3] {
                    JsonConvert.DeserializeObject <TCHubJson.Rank>(PCJson), JsonConvert.DeserializeObject <TCHubJson.Rank>(PSJson), JsonConvert.DeserializeObject <TCHubJson.Rank>(XBJson)
                };
            }
            string[,] pts = new string[platforms, 4];
            for (int i = 0; i < Events.Length; i++)
            {
                for (int j = 0; j < Events[i].Tier_entries.Length; j++)
                {
                    if (Events[i].Tier_entries[j].Points == 4294967295)
                    {
                        pts[i, j] = "-";
                    }
                    else
                    {
                        pts[i, j] = Events[i].Tier_entries[j].Points.ToString();
                    }
                }
            }
            using (Image <Rgba32> PCImg = Image.Load <Rgba32>("Assets/Summit/PC.jpeg"))
                using (Image <Rgba32> PSImg = Image.Load <Rgba32>("Assets/Summit/PS.jpg"))
                    using (Image <Rgba32> XBImg = Image.Load <Rgba32>("Assets/Summit/XB.png"))
                        using (Image <Rgba32> StadiaImg = Image.Load <Rgba32>("Assets/Summit/STADIA.png"))
                            using (Image <Rgba32> BaseImg = new(300 * platforms, 643))
                            {
                                Image <Rgba32>[] PlatformImg = new Image <Rgba32>[4] {
                                    PCImg, PSImg, XBImg, StadiaImg
                                };
                                Parallel.For(0, Events.Length, (i, state) =>
                                {
                                    using Image <Rgba32> TierImg   = Image.Load <Rgba32>("Assets/Summit/SummitBase.png");
                                    using Image <Rgba32> SummitImg = Image.Load <Rgba32>(SummitLogo);
                                    using Image <Rgba32> FooterImg = new(300, 30);
                                    SummitImg.Mutate(ctx => ctx.Crop(300, SummitImg.Height));
                                    Color TextColour     = Color.WhiteSmoke;
                                    Point SummitLocation = new(0 + (300 * i), 0);
                                    Font Basefont        = Program.Fonts.CreateFont("HurmeGeometricSans3W03-Blk", 30);
                                    Font FooterFont      = Program.Fonts.CreateFont("HurmeGeometricSans3W03-Blk", 15);
                                    FooterImg.Mutate(ctx => ctx
                                                     .Fill(Color.Black)
                                                     .DrawText($"TOTAL PARTICIPANTS: {Events[i].Player_Count}", FooterFont, TextColour, new PointF(10, 10))
                                                     );
                                    BaseImg.Mutate(ctx => ctx
                                                   .DrawImage(SummitImg, SummitLocation, 1)
                                                   .DrawImage(TierImg, SummitLocation, 1)
                                                   .DrawText(pts[i, 3], Basefont, TextColour, new PointF(80 + (300 * i), 365))
                                                   .DrawText(pts[i, 2], Basefont, TextColour, new PointF(80 + (300 * i), 435))
                                                   .DrawText(pts[i, 1], Basefont, TextColour, new PointF(80 + (300 * i), 505))
                                                   .DrawText(pts[i, 0], Basefont, TextColour, new PointF(80 + (300 * i), 575))
                                                   .DrawImage(FooterImg, new Point(0 + (300 * i), 613), 1)
                                                   .DrawImage(PlatformImg[i], new Point(0 + (300 * i), 0), 1)
                                                   );
                                });
Ejemplo n.º 23
0
        public EditProd()
        {
            var db = new NorthwindContext();

            string newname;

            try
            {
                Console.Clear();
                Console.WriteLine();
                Console.WriteLine("NORTHWIND Category & Products - Edit PRODUCT\n");
                Console.WriteLine("Select the Product you want to edit:");
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("\n** Note: Category Id & Supplier Id cannot be edited");
                Console.ResetColor();

                int id = int.Parse(DisplayProd.DisplayProd10()); // display the list of Products It returns the ID of the selection

                Console.Clear();
                Console.WriteLine();
                Console.WriteLine("NORTHWIND Category & Products - Edit PRODUCT\n");
                logger.Info($"ProductID {id} selected to edit");

                // get the record

                var query = from p1 in db.Products
                            from cg in db.Categories
                            from s in db.Suppliers
                            where p1.CategoryId == cg.CategoryId
                            where p1.SupplierId == s.SupplierId
                            where p1.ProductID == id
                            select new { p1.ProductID, p1.ProductName, cg.CategoryId, p1.SupplierId, p1.QuantityPerUnit, p1.UnitPrice, p1.UnitsInStock, p1.UnitsOnOrder, p1.ReorderLevel, s.CompanyName, cg.CategoryName, p1.Discontinued };

                foreach (var item in query)
                {
                    string active = "Active";
                    if (item.Discontinued)
                    {
                        active = "Discontinued";
                    }
                    Console.WriteLine($"You chose: {item.ProductID} {item.ProductName} - {active}");
                    Console.WriteLine($"\t\tCategory Id: {item.CategoryId} {item.CategoryName}");
                    Console.WriteLine($"\t\tSupplier Id: {item.SupplierId} {item.CompanyName}");
                    Console.WriteLine($"\t\tQuantity Per Unit: {item.QuantityPerUnit}");
                    Console.WriteLine($"\t\tUnit Price: {item.UnitPrice}");
                    Console.WriteLine($"\t\tUnits in stock: {item.UnitsInStock}");
                    Console.WriteLine($"\t\tUnits On Order: {item.UnitsOnOrder}");
                    Console.WriteLine($"\t\tReOrder Level: {item.ReorderLevel}\n");
                }
                Product product = db.Products.FirstOrDefault(p => p.ProductID == id); // get the record context - is connected to the database - have to get the context first to update it


                Console.WriteLine("Edit Product Name? Y or press any key to bypass");
                string edit = Console.ReadLine();
                logger.Info($"{edit}");

                if (edit.ToLower() == "y")
                {
                    badentry = true;
                    do
                    {
                        Console.WriteLine("Enter a new Product name");
                        s       = Console.ReadLine();
                        newname = s;     // get the new name
                        if (CustomMethod.IsBlank(s))
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("** Must enter something");
                            logger.Info("blank productname entered");
                            Console.ResetColor();
                        }
                        else
                        {
                            logger.Info($"{newname}");
                            badentry = false;
                            logger.Info("Validation passed");
                            product.ProductName = newname;
                            break;
                        }
                    } while (badentry);
                }
                else
                {
                    product.ProductName = product.ProductName;
                }

                Console.WriteLine("Edit the Quantity Per Unit? Y or press any key to bypass");
                edit = Console.ReadLine();     // new qty per unit
                logger.Info($"{edit}");

                if (edit.ToLower() == "y")
                {
                    badentry = true;
                    do
                    {
                        Console.WriteLine("Enter new  Quantity Per Unit");
                        s = Console.ReadLine();
                        product.QuantityPerUnit = s;
                        if (CustomMethod.IsBlank(s))
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("** Must enter something");
                            Console.ResetColor();
                            logger.Info("blank Qty Per Unit entered");
                        }
                    } while (CustomMethod.IsBlank(s));
                }
                else
                {
                    product.QuantityPerUnit = product.QuantityPerUnit;
                }


                Console.WriteLine("Edit a new Unit Price? Y or press any key to bypass");
                edit = Console.ReadLine(); //  new unit price
                logger.Info($"{edit}");

                if (edit.ToLower() == "y")
                {
                    do
                    {
                        Console.WriteLine("\nUnit Price as 0.00:");
                        s = Console.ReadLine();

                        if (CustomMethod.IsDec(s))
                        {
                            logger.Info($"Good Price Entered {s}");
                            product.UnitPrice = Convert.ToDecimal(s);
                            logger.Info($"{s} Unit Price");
                        }
                        else
                        {
                            logger.Info($"bad Price Entered {s}");
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Not a Decimal");
                            Console.ResetColor();
                        }
                    } while (!CustomMethod.IsDec(s));
                }
                else
                {
                    product.UnitPrice = product.UnitPrice;
                }

                Console.WriteLine("Edit the number of Units In Stock? Y or press any key to bypass");
                edit = Console.ReadLine(); //  new units in stock
                logger.Info($"{edit}");

                if (edit.ToLower() == "y")
                {
                    do
                    {
                        Console.WriteLine("\nEnter the number of Units In Stock:");
                        s = Console.ReadLine();

                        if (CustomMethod.IsInt(s))
                        {
                            logger.Info($"Units In Stock {s}");
                            product.UnitsInStock = Convert.ToInt16(s);
                        }
                        else
                        {
                            logger.Info($"bad Units in Stock Entered {s}");
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("** Not a valid number");
                            Console.ResetColor();
                        }
                    } while (!CustomMethod.IsInt(s));
                }
                else
                {
                    product.UnitsInStock = product.UnitsInStock;
                }

                Console.WriteLine("Edit the number of Units On Order? Y or press any key to bypass");
                edit = Console.ReadLine();     //  new units on order
                logger.Info($"{edit}");

                if (edit.ToLower() == "y")
                {
                    do
                    {
                        Console.WriteLine("\nEnter the number of Units On Order:");
                        s = Console.ReadLine();
                        if (CustomMethod.IsInt(s))
                        {
                            logger.Info($"Units On Order {s}");
                            product.UnitsOnOrder = Convert.ToInt16(s);
                        }
                        else
                        {
                            logger.Info($"bad Units On Order Entered {s}");
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("** Not a valid number");
                            Console.ResetColor();
                        }
                    } while (!CustomMethod.IsInt(s));
                }
                else
                {
                    product.UnitsOnOrder = product.UnitsOnOrder;
                }

                Console.WriteLine("Edit the Reorder Level count? Y or press any key to bypass");
                edit = Console.ReadLine();     //  new reorder level
                logger.Info($"{edit}");

                if (edit.ToLower() == "y")
                {
                    do
                    {
                        Console.WriteLine("\nEnter the Reorder Level count:");
                        s = Console.ReadLine();

                        if (CustomMethod.IsInt(s))
                        {
                            logger.Info($"Reorder Level {s}");
                            product.ReorderLevel = Convert.ToInt16(s);
                        }
                        else
                        {
                            logger.Info($"bad Reorder Level {s}");
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("** Not a valid number");
                            Console.ResetColor();
                        }
                    } while (!CustomMethod.IsInt(s));
                }
                else
                {
                    product.ReorderLevel = product.ReorderLevel;
                }


                Console.WriteLine("Edit Item Discontinued? Y or press any key to bypass");
                edit = Console.ReadLine();     //  new item discontinued
                logger.Info($"{edit}");

                if (edit.ToLower() == "y")
                {
                    Console.WriteLine("\nIs the Item Discontinued?  Y or anything else for Active");
                    string disc = Console.ReadLine();
                    disc = disc.ToLower();
                    if (disc == "y")
                    {
                        product.Discontinued = true;
                    }
                }
                else
                {
                    product.Discontinued = product.Discontinued;
                }
                product.CategoryId = product.CategoryId;
                product.SupplierId = product.SupplierId;


                ValidationContext       context = new ValidationContext(product, null, null); // what do I want to validate? = category put category in our context
                List <ValidationResult> results = new List <ValidationResult>();

                var isValid = Validator.TryValidateObject(product, context, results, true); // validate category and return it to results = bool
                if (!isValid)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("* PRODUCT NOT ADDED *");
                    foreach (var result in results)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}");
                        Console.WriteLine($"ERROR: {result.ErrorMessage}");
                        Console.ResetColor();
                    }
                    Console.ResetColor();
                }

                else
                {
                    db.Entry(product).CurrentValues.SetValues(product);
                }
                db.SaveChanges();
            }
            catch
            {
                Console.ForegroundColor = ConsoleColor.Red;
                logger.Error($"no selection made");
                Console.WriteLine($"Not a valid entry");
                Console.ResetColor();
            }

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
Ejemplo n.º 24
0
 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 => optionsBuilder.UseNpgsql(CustomMethod.GetConnString());
Ejemplo n.º 25
0
        public static async Task Level_Gaining_System(object Client, MessageCreateEventArgs e)
        {
            if (!e.Author.IsBot && e.Guild != null)
            {
                Random r            = new();
                int    FollowersMin = MinimalSmallInterval,
                       FollowersMax = MaximalSmallInterval;
                if (e.Message.Content.Length > BigMSGLenght)
                {
                    FollowersMin = MinimalBigInterval;
                    FollowersMax = MaximalBigInterval;
                }
                else if (e.Message.Content.Length > SmallMSGLenght && e.Message.Content.Length < BigMSGLenght)
                {
                    float diff = MinimalBigInterval - MinimalSmallInterval - 1;
                    diff         /= BigMSGLenght;
                    diff         *= e.Message.Content.Length;
                    FollowersMin += (int)diff;
                    diff          = MaximalBigInterval - MaximalSmallInterval - 1;
                    diff         /= BigMSGLenght;
                    diff         *= e.Message.Content.Length;
                    FollowersMax += (int)diff;
                }
                int        FollowersAdded = r.Next(FollowersMin, FollowersMax);
                int        MoneyAdded     = r.Next(MinimalMoney, MaximalMoney);
                LevelTimer GlobalUser     = GlobalLevelTimer.FirstOrDefault(w => w.User.Id == e.Author.Id);
                if (GlobalUser != null && GlobalUser.Time.AddMinutes(MSGCooldown) <= DateTime.Now)
                {
                    var dbEntry = DB.DBLists.Leaderboard.AsParallel().FirstOrDefault(w => w.ID_User == e.Author.Id);
                    dbEntry.Followers += FollowersAdded;
                    dbEntry.Bucks     += MoneyAdded;
                    if (dbEntry.Level < dbEntry.Followers / (300 * (dbEntry.Level + 1) * 0.5))
                    {
                        dbEntry.Level += 1;
                    }
                    GlobalUser.Time = DateTime.Now;
                    DB.DBLists.UpdateLeaderboard(dbEntry);
                }
                else
                {
                    if (DB.DBLists.Leaderboard.AsParallel().FirstOrDefault(w => w.ID_User == e.Author.Id) == null)
                    {
                        CustomMethod.AddUserToLeaderboard(e.Author);
                    }
                    var dbEntry = DB.DBLists.Leaderboard.AsParallel().FirstOrDefault(w => w.ID_User == e.Author.Id);
                    dbEntry.Followers += FollowersAdded;
                    dbEntry.Bucks     += MoneyAdded;
                    if (dbEntry.Level < dbEntry.Followers / (300 * (dbEntry.Level + 1) * 0.5))
                    {
                        dbEntry.Level += 1;
                    }

                    LevelTimer NewToList = new()
                    {
                        Time = DateTime.Now,
                        User = e.Author
                    };
                    GlobalLevelTimer.Add(NewToList);

                    DB.DBLists.UpdateLeaderboard(dbEntry);
                }
                ServerLevelTimer ServerUser = ServerLevelTimer.FirstOrDefault(w => w.User.Id == e.Author.Id);
                if (ServerUser != null && ServerUser.Time.AddMinutes(MSGCooldown) <= DateTime.Now)
                {
                    var dbEntry = DB.DBLists.ServerRanks.AsParallel().FirstOrDefault(w => w.User_ID == e.Author.Id);
                    dbEntry.Followers += FollowersAdded;
                    ServerUser.Time    = DateTime.Now;
                    DB.DBLists.UpdateServerRanks(dbEntry);
                }
                else
                {
                    if (DB.DBLists.ServerRanks.AsParallel().FirstOrDefault(w => w.User_ID == e.Author.Id && w.Server_ID == e.Guild.Id) == null)
                    {
                        CustomMethod.AddUserToServerRanks(e.Author, e.Guild);
                    }
                    var dbEntry = DB.DBLists.ServerRanks.AsParallel().FirstOrDefault(w => w.User_ID == e.Author.Id && w.Server_ID == e.Guild.Id);
                    dbEntry.Followers += FollowersAdded;

                    ServerLevelTimer NewToList = new()
                    {
                        Time  = DateTime.Now,
                        Guild = e.Guild,
                        User  = e.Author
                    };
                    ServerLevelTimer.Add(NewToList);

                    DB.DBLists.UpdateServerRanks(dbEntry);
                }

                long UserServerFollowers = DB.DBLists.ServerRanks.AsParallel().FirstOrDefault(w => w.User_ID == e.Author.Id && w.Server_ID == e.Guild.Id).Followers;
                var  RankRolesUnder      = DB.DBLists.RankRoles.AsParallel().Where(w => w.Server_ID == e.Guild.Id && w.Server_Rank <= UserServerFollowers).OrderByDescending(w => w.Server_Rank).ToList();
                if (RankRolesUnder.Count != 0 && !(e.Author as DiscordMember).Roles.Any(w => w.Id == RankRolesUnder[0].Role_ID))
                {
                    DiscordMember ServerMember = (e.Author as DiscordMember);
                    await ServerMember.GrantRoleAsync(e.Guild.Roles.Values.FirstOrDefault(w => w.Id == RankRolesUnder[0].Role_ID));

                    if (RankRolesUnder.Count > 1)
                    {
                        await ServerMember.RevokeRoleAsync(e.Guild.Roles.Values.FirstOrDefault(w => w.Id == RankRolesUnder[1].Role_ID));
                    }
                }
            }
        }