예제 #1
0
        public void GetReceiptTransactions(RestClient RestClient, Receipt Receipt)
        {
            Console.WriteLine("Getting Transaction");
            RestRequest request = new RestRequest();

            request.Resource = string.Format("receipts/{0}/transactions", Receipt.receipt_id);
            IRestResponse response = RestClient.Execute(request);
            JObject       o        = JObject.Parse(response.Content);
            Transaction   transaction;

            foreach (var t in o["results"])
            {
                transaction = JsonConvert.DeserializeObject <Transaction>(t.ToString());

                foreach (var v in transaction.variations)
                {
                    v.formatted_name  = FormattingHelpers.FixEncoding(v.formatted_name);
                    v.formatted_value = FormattingHelpers.FixEncoding(v.formatted_value);
                }

                Receipt.transactions.Add(transaction);
            }
        }
예제 #2
0
        private void OnEventsAdded(Playbook playbook, List <AbstractEvent> abstractEvents)
        {
            var events = abstractEvents.OfType <LogEvent>().ToList();

            if (events.Count == 0)
            {
                return;
            }

            foreach (var evt in events)
            {
                var text = evt.Text;
                if (evt.Arguments != null)
                {
                    foreach (var arg in evt.Arguments)
                    {
                        text = arg.Key.StartsWith("{spacing", StringComparison.OrdinalIgnoreCase)
                            ? text.Replace(arg.Key, "", StringComparison.InvariantCultureIgnoreCase)
                            : text.Replace(arg.Key, FormattingHelpers.ToDisplayValue(arg.Value), StringComparison.InvariantCultureIgnoreCase);
                    }
                }

                var item = new LogModel()
                {
                    Timestamp = new DateTime(evt.Timestamp),
                    Playbook  = playbook,
                    Event     = evt,
                    Process   = evt.ProcessInvocationUID != null
                        ? playbook.DiagContext.WholePlaybook.ProcessList[evt.ProcessInvocationUID.Value]
                        : null,
                    Text = text,
                };

                _updater.AddItem(item);
            }
        }
        private static bool TryFormatUInt64D(ulong value, byte precision, Span<byte> buffer, out int bytesWritten)
        {
            if (value <= long.MaxValue)
                return TryFormatInt64D((long)value, precision, buffer, out bytesWritten);

            // Remove a single digit from the number. This will get it below long.MaxValue
            // Then we call the faster long version and follow-up with writing the last
            // digit. This ends up being faster by a factor of 2 than to just do the entire
            // operation using the unsigned versions.
            value = FormattingHelpers.DivMod(value, 10, out ulong lastDigit);

            if (precision != StandardFormat.NoPrecision && precision > 0)
                precision -= 1;

            if (!TryFormatInt64D((long)value, precision, buffer, out bytesWritten))
                return false;

            if (buffer.Length - 1 < bytesWritten)
            {
                bytesWritten = 0;
                return false;
            }

            ref byte utf8Bytes = ref buffer.DangerousGetPinnableReference();
        public static IList <string> GetGameData(IEnumerable <Mod> mods)
        {
            var list = new List <string>();

            var modsList = mods.OrderBy(m => m.Name)
                           .SafeSelect(m => FormattingHelpers.SanitizeMarkdown(m.DisplayName) + " " + m.Version.ToString())
                           .ToArray();
            bool   isDay     = Main.dayTime;
            double timeOfDay = Main.time;
            int    halfDays  = WorldHelpers.WorldStateHelpers.GetElapsedHalfDays();
            string worldSize = WorldHelpers.WorldHelpers.GetSize().ToString();

            string[] worldProg   = InfoHelpers.GetWorldProgress().ToArray();
            int      activeItems = ItemHelpers.ItemHelpers.GetActive().Count;
            int      activeNpcs  = NPCHelpers.NPCHelpers.GetActive().Count;
            //string[] playerInfos = InfoHelpers.GetCurrentPlayerInfo().ToArray();
            //string[] playerEquips = InfoHelpers.GetCurrentPlayerEquipment().ToArray();
            int    activePlayers   = Main.ActivePlayersCount;
            string netmode         = Main.netMode == 0 ? "single-player" : "multiplayer";
            bool   autopause       = Main.autoPause;
            bool   autosave        = Main.autoSave;
            int    lighting        = Lighting.lightMode;
            int    lightingThreads = Lighting.LightingThreads;
            int    frameSkipMode   = Main.FrameSkipMode;
            bool   isMaximized     = Main.screenMaximized;
            int    windowWid       = Main.screenWidth;
            int    windowHei       = Main.screenHeight;
            int    qualityStyle    = Main.qaStyle;
            bool   bgOn            = Main.BackgroundEnabled;
            bool   childSafe       = !ChildSafety.Disabled;
            float  gameZoom        = Main.GameZoomTarget;
            float  uiZoom          = Main.UIScale;

            list.Add(InfoHelpers.RenderMarkdownModTable(modsList));
            list.Add(InfoHelpers.RenderMarkdownPlayersTable());

            for (int i = 0; i < Main.player.Length; i++)
            {
                Player plr = Main.player[i];
                if (plr == null || !plr.active)
                {
                    continue;
                }

                list.Add(InfoHelpers.RenderMarkdownPlayerEquipsTable(plr));
            }

            list.Add("Is day: " + isDay + ", Time of day/night: " + timeOfDay + ", Elapsed half days: " + halfDays);                //+ ", Total time (seconds): " + Main._drawInterfaceGameTime.TotalGameTime.Seconds;
            list.Add("World name: " + FormattingHelpers.SanitizeMarkdown(Main.worldName) + ", world size: " + worldSize);
            list.Add("World progress: " + (worldProg.Length > 0 ? string.Join(", ", worldProg) : "none"));
            list.Add("Items on ground: " + activeItems + ", Npcs active: " + activeNpcs);
            //list.Add( "Player info: " + string.Join( ", ", playerInfos ) );
            //list.Add( "Player equips: " + (playerEquips.Length > 0 ? string.Join(", ", playerEquips) : "none" ) );
            list.Add("Player count: " + activePlayers + " (" + netmode + ")");
            list.Add("Autopause: " + autopause);
            list.Add("Autosave: " + autosave);
            list.Add("Lighting mode: " + lighting);
            list.Add("Lighting threads: " + lightingThreads);
            list.Add("Frame skip mode: " + frameSkipMode);
            list.Add("Is screen maximized: " + isMaximized);
            list.Add("Screen resolution: " + windowWid + " " + windowHei);
            list.Add("Quality style: " + qualityStyle);
            list.Add("Background on: " + bgOn);
            list.Add("Child safety: " + childSafe);
            list.Add("Game zoom: " + gameZoom);
            list.Add("UI zoom: " + uiZoom);

            return(list);
        }
예제 #5
0
        //
        // 'G' format for DateTime.
        //
        //    0123456789012345678
        //    ---------------------------------
        //    05/25/2017 10:30:15
        //
        //  Also handles the default ToString() format for DateTimeOffset
        //
        //    01234567890123456789012345
        //    --------------------------
        //    05/25/2017 10:30:15 -08:00
        //
        private static bool TryFormatDateTimeG(DateTime value, TimeSpan offset, Span<byte> destination, out int bytesWritten)
        {
            const int MinimumBytesNeeded = 19;

            int bytesRequired = MinimumBytesNeeded;

            if (offset != Utf8Constants.NullUtcOffset)
            {
                bytesRequired += 7; // Space['+'|'-']hh:mm
            }

            if (destination.Length < bytesRequired)
            {
                bytesWritten = 0;
                return false;
            }

            bytesWritten = bytesRequired;

            // Hoist most of the bounds checks on buffer.
            { var unused = destination[MinimumBytesNeeded - 1]; }

            value.GetDate(out int year, out int month, out int day);
            value.GetTime(out int hour, out int minute, out int second);

            FormattingHelpers.WriteTwoDecimalDigits((uint)month, destination, 0);
            destination[2] = Utf8Constants.Slash;

            FormattingHelpers.WriteTwoDecimalDigits((uint)day, destination, 3);
            destination[5] = Utf8Constants.Slash;

            FormattingHelpers.WriteFourDecimalDigits((uint)year, destination, 6);
            destination[10] = Utf8Constants.Space;

            FormattingHelpers.WriteTwoDecimalDigits((uint)hour, destination, 11);
            destination[13] = Utf8Constants.Colon;

            FormattingHelpers.WriteTwoDecimalDigits((uint)minute, destination, 14);
            destination[16] = Utf8Constants.Colon;

            FormattingHelpers.WriteTwoDecimalDigits((uint)second, destination, 17);

            if (offset != Utf8Constants.NullUtcOffset)
            {
                int offsetTotalMinutes = (int)(offset.Ticks / TimeSpan.TicksPerMinute);
                byte sign;

                if (offsetTotalMinutes < 0)
                {
                    sign = Utf8Constants.Minus;
                    offsetTotalMinutes = -offsetTotalMinutes;
                }
                else
                {
                    sign = Utf8Constants.Plus;
                }

                int offsetHours = Math.DivRem(offsetTotalMinutes, 60, out int offsetMinutes);

                // Writing the value backward allows the JIT to optimize by
                // performing a single bounds check against buffer.

                FormattingHelpers.WriteTwoDecimalDigits((uint)offsetMinutes, destination, 24);
                destination[23] = Utf8Constants.Colon;
                FormattingHelpers.WriteTwoDecimalDigits((uint)offsetHours, destination, 21);
                destination[20] = sign;
                destination[19] = Utf8Constants.Space;
            }

            return true;
        }
예제 #6
0
        private static bool TryFormatStandard(TimeSpan value, StandardFormat format, string?decimalSeparator, Span <char> destination, out int charsWritten)
        {
            Debug.Assert(format == StandardFormat.C || format == StandardFormat.G || format == StandardFormat.g);

            // First, calculate how large an output buffer is needed to hold the entire output.
            int requiredOutputLength = 8; // start with "hh:mm:ss" and adjust as necessary

            uint  fraction;
            ulong totalSecondsRemaining;

            {
                // Turn this into a non-negative TimeSpan if possible.
                long ticks = value.Ticks;
                if (ticks < 0)
                {
                    requiredOutputLength = 9; // requiredOutputLength + 1 for the leading '-' sign
                    ticks = -ticks;
                    if (ticks < 0)
                    {
                        Debug.Assert(ticks == long.MinValue /* -9223372036854775808 */);

                        // We computed these ahead of time; they're straight from the decimal representation of Int64.MinValue.
                        fraction = 4775808;
                        totalSecondsRemaining = 922337203685;
                        goto AfterComputeFraction;
                    }
                }

                ulong fraction64;
                (totalSecondsRemaining, fraction64) = Math.DivRem((ulong)ticks, TimeSpan.TicksPerSecond);
                fraction = (uint)fraction64;
            }

AfterComputeFraction:
            // Only write out the fraction if it's non-zero, and in that
            // case write out the entire fraction (all digits).
            Debug.Assert(fraction < 10_000_000);
            int fractionDigits = 0;

            switch (format)
            {
            case StandardFormat.C:
                // "c": Write out a fraction only if it's non-zero, and write out all 7 digits of it.
                if (fraction != 0)
                {
                    fractionDigits        = DateTimeFormat.MaxSecondsFractionDigits;
                    requiredOutputLength += fractionDigits + 1;     // digits plus leading decimal separator
                }
                break;

            case StandardFormat.G:
                // "G": Write out a fraction regardless of whether it's 0, and write out all 7 digits of it.
                fractionDigits        = DateTimeFormat.MaxSecondsFractionDigits;
                requiredOutputLength += fractionDigits + 1;     // digits plus leading decimal separator
                break;

            default:
                // "g": Write out a fraction only if it's non-zero, and write out only the most significant digits.
                Debug.Assert(format == StandardFormat.g);
                if (fraction != 0)
                {
                    fractionDigits        = DateTimeFormat.MaxSecondsFractionDigits - FormattingHelpers.CountDecimalTrailingZeros(fraction, out fraction);
                    requiredOutputLength += fractionDigits + 1;     // digits plus leading decimal separator
                }
                break;
            }

            ulong totalMinutesRemaining = 0, seconds = 0;

            if (totalSecondsRemaining > 0)
            {
                // Only compute minutes if the TimeSpan has an absolute value of >= 1 minute.
                (totalMinutesRemaining, seconds) = Math.DivRem(totalSecondsRemaining, 60 /* seconds per minute */);
                Debug.Assert(seconds < 60);
            }

            ulong totalHoursRemaining = 0, minutes = 0;

            if (totalMinutesRemaining > 0)
            {
                // Only compute hours if the TimeSpan has an absolute value of >= 1 hour.
                (totalHoursRemaining, minutes) = Math.DivRem(totalMinutesRemaining, 60 /* minutes per hour */);
                Debug.Assert(minutes < 60);
            }

            // At this point, we can switch over to 32-bit DivRem since the data has shrunk far enough.
            Debug.Assert(totalHoursRemaining <= uint.MaxValue);

            uint days = 0, hours = 0;

            if (totalHoursRemaining > 0)
            {
                // Only compute days if the TimeSpan has an absolute value of >= 1 day.
                (days, hours) = Math.DivRem((uint)totalHoursRemaining, 24 /* hours per day */);
                Debug.Assert(hours < 24);
            }

            int hourDigits = 2;

            if (format == StandardFormat.g && hours < 10)
            {
                // "g": Only writing a one-digit hour, rather than expected two-digit hour
                hourDigits = 1;
                requiredOutputLength--;
            }

            int dayDigits = 0;

            if (days > 0)
            {
                dayDigits = FormattingHelpers.CountDigits(days);
                Debug.Assert(dayDigits <= 8);
                requiredOutputLength += dayDigits + 1; // for the leading "d."
            }
            else if (format == StandardFormat.G)
            {
                // "G": has a leading "0:" if days is 0
                requiredOutputLength += 2;
                dayDigits             = 1;
            }

            if (destination.Length < requiredOutputLength)
            {
                charsWritten = 0;
                return(false);
            }

            // Write leading '-' if necessary
            int idx = 0;

            if (value.Ticks < 0)
            {
                destination[idx++] = '-';
            }

            // Write day and separator, if necessary
            if (dayDigits != 0)
            {
                WriteDigits(days, destination.Slice(idx, dayDigits));
                idx += dayDigits;
                destination[idx++] = format == StandardFormat.C ? '.' : ':';
            }

            // Write "[h]h:mm:ss
            Debug.Assert(hourDigits == 1 || hourDigits == 2);
            if (hourDigits == 2)
            {
                WriteTwoDigits(hours, destination.Slice(idx));
                idx += 2;
            }
            else
            {
                destination[idx++] = (char)('0' + hours);
            }
            destination[idx++] = ':';
            WriteTwoDigits((uint)minutes, destination.Slice(idx));
            idx += 2;
            destination[idx++] = ':';
            WriteTwoDigits((uint)seconds, destination.Slice(idx));
            idx += 2;

            // Write fraction and separator, if necessary
            if (fractionDigits != 0)
            {
                Debug.Assert(format == StandardFormat.C || decimalSeparator != null);
                if (format == StandardFormat.C)
                {
                    destination[idx++] = '.';
                }
                else if (decimalSeparator !.Length == 1)
                {
                    destination[idx++] = decimalSeparator[0];
                }
                else
                {
                    decimalSeparator.AsSpan().CopyTo(destination);
                    idx += decimalSeparator.Length;
                }
                WriteDigits(fraction, destination.Slice(idx, fractionDigits));
                idx += fractionDigits;
            }
예제 #7
0
        //
        // 'G' format for DateTime.
        //
        //    0123456789012345678
        //    ---------------------------------
        //    05/25/2017 10:30:15
        //
        //  Also handles the default ToString() format for DateTimeOffset
        //
        //    01234567890123456789012345
        //    --------------------------
        //    05/25/2017 10:30:15 -08:00
        //
        private static bool TryFormatDateTimeG(DateTime value, TimeSpan offset, Span <byte> destination, out int bytesWritten)
        {
            const int MinimumBytesNeeded = 19;

            int bytesRequired = MinimumBytesNeeded;

            if (offset != Utf8Constants.s_nullUtcOffset)
            {
                bytesRequired += 7; // Space['+'|'-']hh:mm
            }

            if (destination.Length < bytesRequired)
            {
                bytesWritten = 0;
                return(false);
            }

            bytesWritten = bytesRequired;

            // Hoist most of the bounds checks on buffer.
            { var unused = destination[MinimumBytesNeeded - 1]; }

            // TODO: Introduce an API which can parse DateTime instances efficiently, pulling out
            // all their properties (Month, Day, etc.) in one shot. This would help avoid the
            // duplicate work that implicitly results from calling these properties individually.

            FormattingHelpers.WriteTwoDecimalDigits((uint)value.Month, destination, 0);
            destination[2] = Utf8Constants.Slash;

            FormattingHelpers.WriteTwoDecimalDigits((uint)value.Day, destination, 3);
            destination[5] = Utf8Constants.Slash;

            FormattingHelpers.WriteFourDecimalDigits((uint)value.Year, destination, 6);
            destination[10] = Utf8Constants.Space;

            FormattingHelpers.WriteTwoDecimalDigits((uint)value.Hour, destination, 11);
            destination[13] = Utf8Constants.Colon;

            FormattingHelpers.WriteTwoDecimalDigits((uint)value.Minute, destination, 14);
            destination[16] = Utf8Constants.Colon;

            FormattingHelpers.WriteTwoDecimalDigits((uint)value.Second, destination, 17);

            if (offset != Utf8Constants.s_nullUtcOffset)
            {
                byte sign;

                if (offset < default(TimeSpan) /* a "const" version of TimeSpan.Zero */)
                {
                    sign   = Utf8Constants.Minus;
                    offset = TimeSpan.FromTicks(-offset.Ticks);
                }
                else
                {
                    sign = Utf8Constants.Plus;
                }

                // Writing the value backward allows the JIT to optimize by
                // performing a single bounds check against buffer.

                FormattingHelpers.WriteTwoDecimalDigits((uint)offset.Minutes, destination, 24);
                destination[23] = Utf8Constants.Colon;
                FormattingHelpers.WriteTwoDecimalDigits((uint)offset.Hours, destination, 21);
                destination[20] = sign;
                destination[19] = Utf8Constants.Space;
            }

            return(true);
        }
예제 #8
0
            private static string GenerateKey(string methodName, Type[] parameterTypes)
            {
                string parameterList = FormattingHelpers.FormatTypeList(parameterTypes);

                return(methodName + "(" + parameterList + ")");
            }
        //
        // Roundtrippable format. One of
        //
        //   012345678901234567890123456789012
        //   ---------------------------------
        //   2017-06-12T05:30:45.7680000-07:00
        //   2017-06-12T05:30:45.7680000Z           (Z is short for "+00:00" but also distinguishes DateTimeKind.Utc from DateTimeKind.Local)
        //   2017-06-12T05:30:45.7680000            (interpreted as local time wrt to current time zone)
        //
        private static bool TryFormatDateTimeO(DateTime value, TimeSpan offset, Span <byte> destination, out int bytesWritten)
        {
            const int MinimumBytesNeeded = 27;

            int          bytesRequired = MinimumBytesNeeded;
            DateTimeKind kind          = DateTimeKind.Local;

            if (offset == Utf8Constants.NullUtcOffset)
            {
                kind = value.Kind;
                if (kind == DateTimeKind.Local)
                {
                    offset         = TimeZoneInfo.Local.GetUtcOffset(value);
                    bytesRequired += 6;
                }
                else if (kind == DateTimeKind.Utc)
                {
                    bytesRequired += 1;
                }
            }
            else
            {
                bytesRequired += 6;
            }

            if (destination.Length < bytesRequired)
            {
                bytesWritten = 0;
                return(false);
            }

            bytesWritten = bytesRequired;

            // Hoist most of the bounds checks on buffer.
            { var unused = destination[MinimumBytesNeeded - 1]; }

            FormattingHelpers.WriteFourDecimalDigits((uint)value.Year, destination, 0);
            destination[4] = Utf8Constants.Minus;

            FormattingHelpers.WriteTwoDecimalDigits((uint)value.Month, destination, 5);
            destination[7] = Utf8Constants.Minus;

            FormattingHelpers.WriteTwoDecimalDigits((uint)value.Day, destination, 8);
            destination[10] = TimeMarker;

            FormattingHelpers.WriteTwoDecimalDigits((uint)value.Hour, destination, 11);
            destination[13] = Utf8Constants.Colon;

            FormattingHelpers.WriteTwoDecimalDigits((uint)value.Minute, destination, 14);
            destination[16] = Utf8Constants.Colon;

            FormattingHelpers.WriteTwoDecimalDigits((uint)value.Second, destination, 17);
            destination[19] = Utf8Constants.Period;

            FormattingHelpers.WriteDigits((uint)((ulong)value.Ticks % (ulong)TimeSpan.TicksPerSecond), destination.Slice(20, 7));

            if (kind == DateTimeKind.Local)
            {
                byte sign;

                if (offset < default(TimeSpan) /* a "const" version of TimeSpan.Zero */)
                {
                    sign   = Utf8Constants.Minus;
                    offset = TimeSpan.FromTicks(-offset.Ticks);
                }
                else
                {
                    sign = Utf8Constants.Plus;
                }

                // Writing the value backward allows the JIT to optimize by
                // performing a single bounds check against buffer.

                FormattingHelpers.WriteTwoDecimalDigits((uint)offset.Minutes, destination, 31);
                destination[30] = Utf8Constants.Colon;
                FormattingHelpers.WriteTwoDecimalDigits((uint)offset.Hours, destination, 28);
                destination[27] = sign;
            }
            else if (kind == DateTimeKind.Utc)
            {
                destination[27] = UtcMarker;
            }

            return(true);
        }
예제 #10
0
        public SessionIoCommandListControl(Control container, DiagnosticsStateManager diagnosticsStateManager, DiagSession session)
        {
            Container = container;
            Session   = session;

            _updater = new ControlUpdater <IoCommandModel>(null, container)
            {
                ItemFilter = ItemFilter,
            };

            _updater.CreateSearchBox(10, 10);

            ShowDbTransactionKind = new CheckBox()
            {
                Parent     = container,
                Bounds     = new Rectangle(_updater.SearchBox.Right + 20, _updater.SearchBox.Top, 130, _updater.SearchBox.Height),
                Text       = "DB transactions",
                CheckAlign = ContentAlignment.MiddleLeft,
            };

            ShowDbTransactionKind.CheckedChanged += (s, a) => _updater.RefreshItems(true);

            ShowDbConnectionKind = new CheckBox()
            {
                Parent     = container,
                Bounds     = new Rectangle(ShowDbTransactionKind.Right + 20, ShowDbTransactionKind.Top, 130, ShowDbTransactionKind.Height),
                Text       = "DB connections",
                CheckAlign = ContentAlignment.MiddleLeft,
            };

            ShowDbConnectionKind.CheckedChanged += (s, a) => _updater.RefreshItems(true);

            HideVeryFast = new CheckBox()
            {
                Parent     = container,
                Bounds     = new Rectangle(ShowDbConnectionKind.Right + 20, ShowDbTransactionKind.Top, 130, ShowDbTransactionKind.Height),
                Text       = "Hide very fast",
                CheckAlign = ContentAlignment.MiddleLeft,
                Checked    = true,
            };

            HideVeryFast.CheckedChanged += (s, a) => _updater.RefreshItems(true);

            _updater.ListView.Anchor        = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom;
            _updater.ListView.Bounds        = new Rectangle(Container.ClientRectangle.Left, Container.ClientRectangle.Top + 40, Container.ClientRectangle.Width, Container.ClientRectangle.Height - 40);
            _updater.ListView.ItemActivate += ListView_ItemActivate;

            _updater.ListView.Columns.Add(new OLVColumn()
            {
                Text         = "ID",
                AspectGetter = x => (x as IoCommandModel)?.StartEvent.Uid,
            });
            _updater.ListView.Columns.Add(new OLVColumn()
            {
                Text                    = "Timestamp",
                AspectGetter            = x => (x as IoCommandModel)?.Timestamp,
                AspectToStringConverter = x => ((DateTime)x).ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture),
            });
            _updater.ListView.Columns.Add(new OLVColumn()
            {
                Text         = "Context",
                AspectGetter = x => (x as IoCommandModel)?.Playbook.DiagContext.Name,
            });
            _updater.ListView.Columns.Add(new OLVColumn()
            {
                Text         = "Process",
                AspectGetter = x => (x as IoCommandModel)?.Process.Name,
            });
            _updater.ListView.Columns.Add(new OLVColumn()
            {
                Text         = "Kind",
                AspectGetter = x => (x as IoCommandModel)?.Process.KindToString(),
            });
            _updater.ListView.Columns.Add(new OLVColumn()
            {
                Text         = "Type",
                AspectGetter = x => (x as IoCommandModel)?.Process.Type,
            });
            _updater.ListView.Columns.Add(new OLVColumn()
            {
                Text         = "Topic",
                AspectGetter = x => (x as IoCommandModel)?.Process.Topic,
            });
            _updater.ListView.Columns.Add(new OLVColumn()
            {
                Text         = "Transaction",
                AspectGetter = x => (x as IoCommandModel)?.StartEvent.TransactionId,
            });
            _updater.ListView.Columns.Add(new OLVColumn()
            {
                Text         = "Command kind",
                AspectGetter = x => (x as IoCommandModel)?.StartEvent.Kind.ToString(),
            });
            _updater.ListView.Columns.Add(new OLVColumn()
            {
                Text         = "Location",
                AspectGetter = x => (x as IoCommandModel)?.StartEvent.Location,
            });
            _updater.ListView.Columns.Add(new OLVColumn()
            {
                Text         = "Path",
                AspectGetter = x => (x as IoCommandModel)?.StartEvent.Path,
            });
            _updater.ListView.Columns.Add(new OLVColumn()
            {
                Text            = "Timeout",
                AspectGetter    = x => (x as IoCommandModel)?.StartEvent.TimeoutSeconds,
                TextAlign       = HorizontalAlignment.Right,
                HeaderTextAlign = HorizontalAlignment.Right,
            });
            _updater.ListView.Columns.Add(new OLVColumn()
            {
                Text                    = "Elapsed",
                AspectGetter            = x => (x as IoCommandModel)?.Elapsed,
                AspectToStringConverter = x => x is TimeSpan ts ? FormattingHelpers.RightAlignedTimeSpanToString(ts) : null,
                TextAlign               = HorizontalAlignment.Right,
                HeaderTextAlign         = HorizontalAlignment.Right,
            });
예제 #11
0
        //
        // Roundtrippable format. One of
        //
        //   012345678901234567890123456789012
        //   ---------------------------------
        //   2017-06-12T05:30:45.7680000-07:00
        //   2017-06-12T05:30:45.7680000Z           (Z is short for "+00:00" but also distinguishes DateTimeKind.Utc from DateTimeKind.Local)
        //   2017-06-12T05:30:45.7680000            (interpreted as local time wrt to current time zone)
        //
        private static bool TryFormatDateTimeO(DateTime value, TimeSpan offset, Span <byte> destination, out int bytesWritten)
        {
            const int MinimumBytesNeeded = 27;

            int          bytesRequired = MinimumBytesNeeded;
            DateTimeKind kind          = DateTimeKind.Local;

            if (offset == Utf8Constants.NullUtcOffset)
            {
                kind = value.Kind;
                if (kind == DateTimeKind.Local)
                {
                    offset         = TimeZoneInfo.Local.GetUtcOffset(value);
                    bytesRequired += 6;
                }
                else if (kind == DateTimeKind.Utc)
                {
                    bytesRequired++;
                }
            }
            else
            {
                bytesRequired += 6;
            }

            if (destination.Length < bytesRequired)
            {
                bytesWritten = 0;
                return(false);
            }

            bytesWritten = bytesRequired;

            // Hoist most of the bounds checks on buffer.
            { _ = destination[MinimumBytesNeeded - 1]; }

            value.GetDate(out int year, out int month, out int day);
            value.GetTimePrecise(out int hour, out int minute, out int second, out int ticks);

            FormattingHelpers.WriteFourDecimalDigits((uint)year, destination, 0);
            destination[4] = Utf8Constants.Minus;

            FormattingHelpers.WriteTwoDecimalDigits((uint)month, destination, 5);
            destination[7] = Utf8Constants.Minus;

            FormattingHelpers.WriteTwoDecimalDigits((uint)day, destination, 8);
            destination[10] = TimeMarker;

            FormattingHelpers.WriteTwoDecimalDigits((uint)hour, destination, 11);
            destination[13] = Utf8Constants.Colon;

            FormattingHelpers.WriteTwoDecimalDigits((uint)minute, destination, 14);
            destination[16] = Utf8Constants.Colon;

            FormattingHelpers.WriteTwoDecimalDigits((uint)second, destination, 17);
            destination[19] = Utf8Constants.Period;

            FormattingHelpers.WriteDigits((uint)ticks, destination.Slice(20, 7));

            if (kind == DateTimeKind.Local)
            {
                int  offsetTotalMinutes = (int)(offset.Ticks / TimeSpan.TicksPerMinute);
                byte sign;

                if (offsetTotalMinutes < 0)
                {
                    sign = Utf8Constants.Minus;
                    offsetTotalMinutes = -offsetTotalMinutes;
                }
                else
                {
                    sign = Utf8Constants.Plus;
                }

                int offsetHours = Math.DivRem(offsetTotalMinutes, 60, out int offsetMinutes);

                // Writing the value backward allows the JIT to optimize by
                // performing a single bounds check against buffer.

                FormattingHelpers.WriteTwoDecimalDigits((uint)offsetMinutes, destination, 31);
                destination[30] = Utf8Constants.Colon;
                FormattingHelpers.WriteTwoDecimalDigits((uint)offsetHours, destination, 28);
                destination[27] = sign;
            }
            else if (kind == DateTimeKind.Utc)
            {
                destination[27] = UtcMarker;
            }

            return(true);
        }
예제 #12
0
        private static bool TryFormatC(TimeSpan value, Span <char> destination, out int charsWritten)
        {
            // First, calculate how large an output buffer is needed to hold the entire output.
            int requiredOutputLength = 8; // start with "hh:mm:ss" and adjust as necessary

            uint  fraction;
            ulong totalSecondsRemaining;

            {
                // Turn this into a non-negative TimeSpan if possible.
                long ticks = value.Ticks;
                if (ticks < 0)
                {
                    requiredOutputLength = 9; // requiredOutputLength + 1 for the leading '-' sign
                    ticks = -ticks;
                    if (ticks < 0)
                    {
                        Debug.Assert(ticks == long.MinValue /* -9223372036854775808 */);

                        // We computed these ahead of time; they're straight from the decimal representation of Int64.MinValue.
                        fraction = 4775808;
                        totalSecondsRemaining = 922337203685;
                        goto AfterComputeFraction;
                    }
                }

                totalSecondsRemaining = Math.DivRem((ulong)ticks, TimeSpan.TicksPerSecond, out ulong fraction64);
                fraction = (uint)fraction64;
            }

AfterComputeFraction:
            // Only write out the fraction if it's non-zero, and in that
            // case write out the entire fraction (all digits).
            int fractionDigits = 0;

            if (fraction != 0)
            {
                Debug.Assert(fraction < 10_000_000);
                fractionDigits        = DateTimeFormat.MaxSecondsFractionDigits;
                requiredOutputLength += fractionDigits + 1; // If we're going to write out a fraction, also need to write the leading decimal.
            }

            ulong totalMinutesRemaining = 0, seconds = 0;

            if (totalSecondsRemaining > 0)
            {
                // Only compute minutes if the TimeSpan has an absolute value of >= 1 minute.
                totalMinutesRemaining = Math.DivRem(totalSecondsRemaining, 60 /* seconds per minute */, out seconds);
                Debug.Assert(seconds < 60);
            }

            ulong totalHoursRemaining = 0, minutes = 0;

            if (totalMinutesRemaining > 0)
            {
                // Only compute hours if the TimeSpan has an absolute value of >= 1 hour.
                totalHoursRemaining = Math.DivRem(totalMinutesRemaining, 60 /* minutes per hour */, out minutes);
                Debug.Assert(minutes < 60);
            }

            // At this point, we can switch over to 32-bit DivRem since the data has shrunk far enough.
            Debug.Assert(totalHoursRemaining <= uint.MaxValue);

            uint days = 0, hours = 0;

            if (totalHoursRemaining > 0)
            {
                // Only compute days if the TimeSpan has an absolute value of >= 1 day.
                days = Math.DivRem((uint)totalHoursRemaining, 24 /* hours per day */, out hours);
                Debug.Assert(hours < 24);
            }

            int dayDigits = 0;

            if (days > 0)
            {
                dayDigits = FormattingHelpers.CountDigits(days);
                Debug.Assert(dayDigits <= 8);
                requiredOutputLength += dayDigits + 1; // for the leading "d."
            }

            if (destination.Length < requiredOutputLength)
            {
                charsWritten = 0;
                return(false);
            }

            // Write leading '-' if necessary
            int idx = 0;

            if (value.Ticks < 0)
            {
                destination[idx++] = '-';
            }

            // Write day and separator, if necessary
            if (dayDigits != 0)
            {
                WriteDigits(days, destination.Slice(idx, dayDigits));
                idx += dayDigits;
                destination[idx++] = '.';
            }

            // Write "hh:mm:ss"
            WriteTwoDigits(hours, destination.Slice(idx));
            idx += 2;
            destination[idx++] = ':';
            WriteTwoDigits((uint)minutes, destination.Slice(idx));
            idx += 2;
            destination[idx++] = ':';
            WriteTwoDigits((uint)seconds, destination.Slice(idx));
            idx += 2;

            // Write fraction and separator, if necessary
            if (fractionDigits != 0)
            {
                destination[idx++] = '.';
                WriteDigits(fraction, destination.Slice(idx, fractionDigits));
                idx += fractionDigits;
            }

            Debug.Assert(idx == requiredOutputLength);
            charsWritten = requiredOutputLength;
            return(true);
        }
예제 #13
0
        public static string RenderMarkdownPlayerEquipsTable(Player player)
        {
            IDictionary <string, string> playerEquips = InfoHelpers.GetPlayerEquipment(player);
            int cols = playerEquips.Count;

            string playerLabel = "**Player " + FormattingHelpers.SanitizeMarkdown(player.name) + "'s (" + player.whoAmI + ") equipment:**";

            string equipsLabels = cols > 0 ? string.Join(" | ", playerEquips.Keys) : "-";
            string header       = "| " + equipsLabels + " |";

            string subheader = "|";

            if (cols > 0)
            {
                for (int i = 0; i < cols; i++)
                {
                    subheader += " :--- |";
                }
            }
            else
            {
                subheader += " :--- |";
            }

            string equips     = string.Join(" | ", playerEquips.Values.SafeSelect(e => FormattingHelpers.SanitizeMarkdown(e)));
            string equipsCols = cols > 0 ? equips : "-";
            string columns    = "| " + equipsCols + " |";

            return(playerLabel + "\n \n" + header + "\n" + subheader + "\n" + columns);
        }
예제 #14
0
        public static List <ExtractionModel> CreateExtractionFromReceipt(InternalClient GClient, bool allReceipts)
        {
            //Creation New Rest Client
            var client = new RestClient();

            client.BaseUrl       = AppKeys.GetBaseUri();
            client.Authenticator = OAuth1Authenticator.ForProtectedResource(AppKeys.GetApiKey(), AppKeys.GetSharedSecretKey(), GClient.AccessToken, GClient.AccessSecretKey);

            //The shop servce is where we pull receipts because functionally
            //The call is related to the shop object and te shop id
            ShopService    shopservice = new ShopService();
            List <Receipt> receipts;

            //This is just in case for some reason we want every transaction from a shop
            if (allReceipts)
            {
                receipts = shopservice.GetShopReceipts(client, GClient.EtsyShopIDs.FirstOrDefault());
            }
            else
            {
                receipts = shopservice.GetOpenShopReceipts(client, GClient.EtsyShopIDs.FirstOrDefault());
            }

            //Get the country list from etsy in advance so it doesn't
            //Have to be called per receipt request
            var countries = CountryService.GetCountryMapping(client);

            List <ExtractionModel> extractions = new List <ExtractionModel>();

            //make sure we actually pulled back client data
            if (GClient != null)
            {
                //iteract through receipts
                foreach (Receipt r in receipts)
                {
                    //iterrate through transactions of receipts
                    foreach (var t in r.transactions)
                    {
                        string country = countries[int.Parse(r.country_id)];

                        ExtractionModel em = new ExtractionModel();
                        em.company_id             = GClient.clientID;
                        em.Order_ID               = r.receipt_id;
                        em.date_purchased         = FormattingHelpers.FromEpochUnixTime(t.creation_tsz).ToString("g");
                        em.customer_email_address = r.buyer_email;
                        var FirstnameLastname = FormattingHelpers.FirstNameLastNameFormatter(r.name);
                        em.first_name = FirstnameLastname.Item1;
                        em.last_name  = FirstnameLastname.Item2;

                        em.delivery_address_1 = r.first_line;
                        em.delivery_address_2 = r.second_line;
                        em.delivery_city      = r.city;
                        em.delivery_state     = r.state;
                        em.delivery_zipCode   = r.zip;
                        em.country            = country;

                        //This is for the variation that is assuming
                        //it follows the format "Color - Design"
                        string[] color_design = t.variations.Where(x => x.formatted_name == "Color").FirstOrDefault().formatted_value.Split('-');

                        //If there is not a "-" then it automatically
                        //is the wrong format
                        if (color_design.Length > 1)
                        {
                            //This is making sure that the Design actually is associated
                            //with the client
                            //TODO: Eventually check that the design is actually available in the color
                            //that is provided.
                            if (GClient.ClientDesigns.Where(x => x.design_number.Trim() == color_design[1].Trim()).Any())
                            {
                                em.color         = color_design[0].Trim();
                                em.design_number = FormattingHelpers.DesignNumberFormatCheck(color_design[1].Trim());
                            }
                            else
                            {
                                em.color         = color_design[0].Trim();
                                em.design_number = string.Format("{0} Is Not a Correct Design Id", color_design[1]);
                            }
                        }
                        else
                        {
                            em.color         = color_design[0].Trim();
                            em.design_number = "Color_Design Incorrect Format";
                        }
                        em.design_description = "TBD";
                        em.print_location     = "TBD";


                        //This is for the variation that is assuming
                        //it follows the format "Style - Size"
                        string[] size_style = t.variations.Where(x => x.formatted_name == "Size").FirstOrDefault().formatted_value.Split('-');

                        if (size_style.Length > 1)
                        {
                            string etsystyle = size_style[1].Trim();
                            em.size = size_style[0].Trim();

                            //Check to see if the style from the variation
                            //has a mapping otherwise we can't know what
                            //prodct style its suposed to be
                            var style = GClient.ClientStyles.Where(x => x.etsy_style_descripion == etsystyle).FirstOrDefault();
                            if (style != null)
                            {
                                em.style_number      = style.style_number;
                                em.style_description = style.style_description;
                            }
                            else
                            {
                                em.style_number      = "ESTY STYLE '" + etsystyle + "' NOT FOUND";
                                em.style_description = "ESTY STYLE '" + etsystyle + "' NOT FOUND";
                            }
                        }
                        else
                        {
                            em.style_number      = size_style[0].Trim();
                            em.style_description = "Size_Style Incorrect Format";
                        }

                        em.product_quantity = t.quantity;
                        em.gift_message     = r.message_from_buyer;
                        em.Insured_Order    = "No";
                        em.shipping_method  = CountryService.GetCountryShippingMethodByCountry(country).Shipping_Method;
                        em.order_status     = "2";

                        extractions.Add(em);
                    }
                }
            }
            return(extractions);
        }