public void CustomTypeToString()
 {
     var sb = new StringFormatter();
     sb.Append(new Age(56));
     sb.Append(new Age(14, inMonths: true));
     Assert.Equal(sb.ToString(), "56y14m");
 }
        public void CompositeFormattingEscapingMissingStartBracket()
        {
            var pool = new ManagedBufferPool<byte>(1024);
            var formatter = new StringFormatter(pool);

            Assert.Throws<Exception>(() => formatter.Format("{0}}", 1));
        }
        public void FormatGuid()
        {
            var guid = Guid.NewGuid();
            var sb = new StringFormatter();

            sb.Append(guid);
            Assert.Equal(guid.ToString(), sb.ToString());
            sb.Clear();

            sb.Append(guid, 'D');
            Assert.Equal(guid.ToString("D"), sb.ToString());
            sb.Clear();

            sb.Append(guid, 'N');
            Assert.Equal(guid.ToString("N"), sb.ToString());
            sb.Clear();

            sb.Append(guid, 'B');
            Assert.Equal(guid.ToString("B"), sb.ToString());
            sb.Clear();

            sb.Append(guid, 'P');
            Assert.Equal(guid.ToString("P"), sb.ToString());
            sb.Clear();
        }
        public void CompositeFormattingFormatStrings()
        {
            var formatter = new StringFormatter(pool);
            formatter.Format("Hello{0:x}{1:X}{2:G}", 10, 255, 3);

            Assert.Equal("HelloaFF3", formatter.ToString());
        }
Example #5
0
        public void CustomCulture()
        {
            var sb = new StringFormatter();
            sb.Encoding = EncodingProvider.CreateEncoding("pl-PL");

            sb.Append(-10000, TextFormat.Parse('N'));
            Assert.Equal("-10\u00A0000,00", sb.ToString()); // \u00A0 is a space group separator
        }
        public void CompositeFormattingEscaping()
        {
            var format = "}}a {0} b {0} c {{{0}}} d {{e}} {{";
            var formatter = new StringFormatter(pool);
            formatter.Format(format, 1);

            Assert.Equal(string.Format(CultureInfo.InvariantCulture, format, 1), formatter.ToString());
        }
Example #7
0
        public void CustomCulture()
        {
            var sb = new StringFormatter(ArrayPool<byte>.Shared);
            sb.FormattingData = FormattingDataProvider.CreateFormattingData("pl-PL");

            sb.Append(-10000, Format.Parse('N'));
            Assert.Equal("-10\u00A0000,00", sb.ToString()); // \u00A0 is a space group separator
        }
        public void CompositeFormattingFormatStrings()
        {
            var pool = new ManagedBufferPool<byte>(1024);
            var formatter = new StringFormatter(pool);
            formatter.Format("Hello{0:x}{1:X}{2:G}", 10, 255, 3);

            Assert.Equal("HelloaFF3", formatter.ToString());
        }
Example #9
0
        public void CustomCulture()
        {
            var sb = new StringFormatter();
            sb.Encoding = Culture5;

            sb.Append(-1234567890);
            Assert.Equal("_?BBBBBCCCCCDDDDDEEEEEFFFFFGGGGGHHHHHIIIIIJJJJJAAAAA", sb.ToString());
        }
        public void FormatDateTimeG()
        {
            var time = DateTime.UtcNow;
            var sb = new StringFormatter();

            sb.Append(time, 'G');
            Assert.Equal(time.ToString("G"), sb.ToString());
            sb.Clear();
        }
 public void CompositeFormattingBasics()
 {
     var time = DateTime.UtcNow;
     using (var formatter = new StringFormatter(pool))
     {
         formatter.Format("{2} - Error {0}. File {1} not found.", 404, "index.html", time);
         Assert.Equal(time.ToString("G") + " - Error 404. File index.html not found.", formatter.ToString());
     }
 }
        public void FormatTimeSpan()
        {
            var time = new TimeSpan(1000, 23, 40, 30, 12345);
            var sb = new StringFormatter();

            sb.Append(time);
            Assert.Equal(time.ToString("", CultureInfo.InvariantCulture), sb.ToString());
            sb.Clear();
        }
        public void CompositeFormattingBasics()
        {
            var time = DateTime.UtcNow;
            var pool = new ManagedBufferPool<byte>(1024);
            var formatter = new StringFormatter(pool);
            formatter.Format("{2} - Error {0}. File {1} not found.", 404, "index.html", time);

            Assert.Equal(time.ToString("G") + " - Error 404. File index.html not found.", formatter.ToString());
        }
 public void CheckTimeSpan(TimeSpan value, string format)
 {
     var parsed = Format.Parse(format);
     var formatter = new StringFormatter(pool);
     formatter.Append(value, parsed);
     var result = formatter.ToString();
     var clrResult = value.ToString(format, CultureInfo.InvariantCulture);
     Assert.Equal(clrResult, result);
 }
 public void CompositeFormattingBasics()
 {
     var time = new DateTime(2016, 2, 9, 4, 1, 59, DateTimeKind.Utc);
     using (var formatter = new StringFormatter(pool))
     {
         formatter.Format("{2:G} - Error {0}. File {1} not found.", 404, "index.html", time);
         Assert.Equal("2/9/2016 4:01:59 AM - Error 404. File index.html not found.", formatter.ToString());
     }
 }
 public void BasicStringFormatter()
 {
     var sb = new StringFormatter();
     sb.Append("hi");
     sb.Append(1);
     sb.Append("hello");
     sb.Append((sbyte)-20);
     Assert.Equal("hi1hello-20", sb.ToString());
 }
        public void FormatDateTimeOffsetR()
        {
            var time = DateTimeOffset.UtcNow;
            var sb = new StringFormatter(pool);

            sb.Append(time, 'R');
            Assert.Equal(time.ToString("R"), sb.ToString());
            sb.Clear();
        }
Example #18
0
        public void CustomCulture()
        {
            var pool = new ManagedBufferPool<byte>(1024);
            var sb = new StringFormatter(pool);
            sb.FormattingData = FormattingDataProvider.CreateFormattingData("pl-PL");

            sb.Append(-10000, Format.Parse('N'));
            Assert.Equal("-10\u00A0000,00", sb.ToString()); // \u00A0 is a space group separator
        }
        public void FormatDateTimeO()
        {
            var time = DateTime.UtcNow;
            var sb = new StringFormatter();

            sb.Append(time, 'O');
            Assert.Equal(time.ToString("O", CultureInfo.InvariantCulture), sb.ToString());
            sb.Clear();
        }
Example #20
0
        public void StringFormatter_CanFormatByteArgument()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument((Byte)123);
            formatter.Format("this is a Byte value: {0}", buffer);

            TheResultingString(buffer).ShouldBe("this is a Byte value: 123");
        }
Example #21
0
        public void StringFormatter_CanFormatCharArgument()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument('Z');
            formatter.Format("this is a Char value: {0}", buffer);

            TheResultingString(buffer).ShouldBe("this is a Char value: Z");
        }
Example #22
0
        public void StringFormatter_CanFormatDoubleArgumentWithDecimalsCommand()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument(123.456789);
            formatter.Format("this is a Double value: {0:decimals:2}", buffer);

            TheResultingString(buffer).ShouldBe("this is a Double value: 123.46");
        }
Example #23
0
        public void StringFormatter_CanFormatInt32Argument()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument(12345);
            formatter.Format("this is an Int32 value: {0}", buffer);

            TheResultingString(buffer).ShouldBe("this is an Int32 value: 12345");
        }
        public void StringFormatter_CanFormatStringArgument()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument("world");
            formatter.Format("hello {0}", buffer);

            TheResultingString(buffer).ShouldBe("hello world");
        }
            /// <inheritdoc/>
            public override void HandleCommandLocalizedString(StringFormatter formatter,
                StringBuilder output, StringSegment command, StringFormatterCommandArguments arguments, LocalizedString value)
            {
                if (value == null)
                    throw new FormatException(NucleusStrings.FmtCmdInvalidForGeneratedStrings.Format("variant"));

                var variantName = arguments.GetArgument(0).Text;
                var variant = value.GetVariant(ref variantName);

                output.Append(variant);
            }
        public void StringFormatter_CanFormatSingleArgument()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument(123.45f);
            formatter.Format("this is a Single value: {0}", buffer);

            TheResultingString(buffer).ShouldBe("this is a Single value: 123.45000");
        }
Example #27
0
        public void StringFormatter_CanFormatBooleanArgument()
        {
            var formatter = new StringFormatter();
            var buffer    = new StringBuilder();

            formatter.Reset();
            formatter.AddArgument(true);
            formatter.AddArgument(false);
            formatter.Format("this is {0} and this is {1}", buffer);

            TheResultingString(buffer).ShouldBe("this is True and this is False");
        }
        private void CheckByte(byte value, string format, string expected)
        {
            var formatter = new StringFormatter(pool);
            var parsed = Format.Parse(format);
            formatter.Clear();
            formatter.Append(value, parsed);
            var result = formatter.ToString();
            Assert.Equal(expected, result);

            var clrResult = value.ToString(format, CultureInfo.InvariantCulture);
            Assert.Equal(clrResult, result);
        }
            /// <inheritdoc/>
            public override void HandleCommandLocalizedString(StringFormatter formatter,
                StringBuilder output, StringSegment command, StringFormatterCommandArguments arguments, LocalizedString value)
            {
                var targetArgumentArg = arguments.GetArgument(0);
                var targetArgumentIndex = targetArgumentArg.GetValueAsInt32();
                var targetMatchRuleArg = arguments.GetNextArgument(ref targetArgumentArg);
                var targetMatchRule = targetMatchRuleArg.Text;

                // Make sure our target is a localized string variant.
                var target = formatter.GetArgument(targetArgumentIndex);
                if (target.Reference == null || !(target.Reference is LocalizedStringVariant))
                    throw new FormatException(NucleusStrings.FmtCmdInvalidForArgument.Format("match", target.Reference?.GetType()));

                // Run the specified match evaluator.
                var match = Localization.MatchVariant(value, (LocalizedStringVariant)target.Reference, targetMatchRule);
                output.Append(match ?? "???");
            }
Example #30
0
 private void InvariantFormatIntHex()
 {
     timer.Restart();
     for (int itteration = 0; itteration < itterationsInvariant; itteration++)
     {
         StringFormatter sb = new StringFormatter(numbersToWrite, pool);
         for (int i = 0; i < numbersToWrite; i++)
         {
             sb.Append(((int)(i % 10)), Format.Parsed.HexUppercase);
         }
         var text = sb.ToString();
         if (text.Length != numbersToWrite)
         {
             throw new Exception("test failed");
         }
     }
     PrintTime();
 }
        /// <summary>
        /// Gets the value of the property as a String, throws UnsetPropertyException if the value is null
        /// </summary>
        /// <returns>Value of the property as string</returns>
        public override string GetString()
        {
            Nullable <int> obj = this.GetValue();

            if (obj.HasValue == false)
            {
                return(String.Empty);
            }

            // Get integer value as string:
            string value = StringFormatter.IntegerStringFormatter(obj, this.Length);

            // Validating length:
            if (value.Length != Length)
            {
                throw new LenghtMismatchException(this.Name + " : \"" + value + "\" is " + value.Length + " long while it should be " + Length + " long.");
            }
            return(value);
        }
Example #32
0
        /// <summary>
        /// Clear folder with logs
        /// </summary>
        public static void ClearLogsFolder()
        {
            var logsFolder = StringFormatter.GetLogsFolderPath();

            try
            {
                LogProvider.Log.Info($"Clearing '{logsFolder}'");

                var logsDirectory = new DirectoryInfo(logsFolder);

                if (!logsDirectory.Exists)
                {
                    return;
                }

                foreach (var logPatternKeyValue in logsPatterns)
                {
                    var logFilesToDelete = logsDirectory.GetFiles(logPatternKeyValue.Key)
                                           .GroupBy(x => x.LastWriteTime.Date)
                                           .Select(x => new { Day = x.Key, Files = x.ToArray() })
                                           .OrderByDescending(x => x.Day)
                                           .Skip(logPatternKeyValue.Value)
                                           .SelectMany(x => x.Files)
                                           .ToArray();

                    logFilesToDelete.ForEach(x =>
                    {
                        try
                        {
                            x.Delete();
                        }
                        catch (Exception ex)
                        {
                            LogProvider.Log.Error(nameof(LogCleaner), $"Failed to delete log file: {x.FullName}", ex);
                        }
                    });
                }
            }
            catch (Exception e)
            {
                LogProvider.Log.Error(nameof(LogCleaner), $"Failed to clear log folder: {logsFolder}", e);
            }
        }
Example #33
0
        private IEnumerable <Dictionary <InterKey, List <InterValue> > > doMap(InputTextCunk chunk, int thread_num = 0)
        {
            Stopwatch watch         = new Stopwatch();
            var       input_records = chunk.Records;
            var       char_count    = chunk.CharCount;

            watch.Restart();
            var             dics   = new ConcurrentBag <Dictionary <InterKey, List <InterValue> > >();
            ParallelOptions option = new ParallelOptions();

            if (thread_num != 0)
            {
                option.MaxDegreeOfParallelism = thread_num;
            }

            Parallel.ForEach(Partitioner.Create(0, input_records.Count), option, (range) =>
            {
                var dic     = new Dictionary <InterKey, List <InterValue> >();
                var context = new MapContext <InterKey, InterValue>(dic);
                for (int i = range.Item1; i < range.Item2; i++)
                {
                    mapFunc.Invoke(input_records[i], context);
                }
                dics.Add(dic);
                Interlocked.Add(ref mapperInfo.MapEmits, context.EmitCount);
            });
            watch.Stop();

            mapperInfo.ProcessedRecords += input_records.Count;
            mapperInfo.ProcessedChars   += char_count;

            if (watch.Elapsed > maxWorkPeriod)
            {
                maxChunkSize = Math.Min(maxChunkSize / 2, maxCharsToMap);
            }
            if (watch.Elapsed < minWorkPeriod)
            {
                maxChunkSize = Math.Min(maxChunkSize * 2, maxCharsToMap);
            }

            logger.Debug("Mapped a chunk with {0} chars in {1}", StringFormatter.DigitGrouped(char_count), watch.Elapsed);
            return(dics);
        }
        public StringFormatter FormatPp(PPTuple?pp = null)
        {
            var formatter = StringFormatter.GetPPFormatter();
            var tuple     = pp ?? Pp;

            var ctx = s_exprCtx.Value;
            var ppExpressionDict = s_ppAstDict.Value;

            lock (_mtx)
            {
                UpdateContextVariablesFromPpTuple(ctx, tuple);
                UpdateContextVariablesFromHitCountTuple(ctx, HitCount);
            }

            foreach (var arg in formatter)
            {
                if (!ppExpressionDict.TryGetValue(arg, out var root))
                {
                    var parser = new ExpressionParser();
                    try
                    {
                        root = parser.Parse(arg.ExprString);
                    }
                    catch (ExprssionTokenException e)
                    {
                        Sync.Tools.IO.CurrentIO.WriteColor($"[RTPP:Expression]{e.Message}", ConsoleColor.Yellow);
                    }

                    ppExpressionDict[arg] = root;
                }

                try
                {
                    formatter.Fill(arg, ctx.ExecAst(root));
                }
                catch (ExpressionException e)
                {
                    Sync.Tools.IO.CurrentIO.WriteColor($"[RTPP:Expression]{e.Message}", ConsoleColor.Yellow);
                }
            }

            return(formatter);
        }
Example #35
0
        public async Task <List <GameDetailsModel> > Get(string value)
        {
            _address = new Uri("https://api.igdb.com/v4/games");
            string queryName = StringFormatter.ReturnFormattedValue(value);

            #region HttpClient Settings

            //Clear HttpClient
            HttpStaticClient.GetInstance.DefaultRequestHeaders.Accept.Clear();
            HttpStaticClient.GetInstance.DefaultRequestHeaders.Clear();

            //Set HttpClient
            HttpStaticClient.GetInstance.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpStaticClient.GetInstance.DefaultRequestHeaders.Add("Client-ID", "3yo2gt2qjjburcphl30wfyt0e64vxx");
            HttpStaticClient.GetInstance.DefaultRequestHeaders.Add("Authorization", "Bearer " + AuthManager.GetToken(nameof(TwitchAuthClient)));
            HttpContent requestMessage = null;

            #endregion

            #region Api Call

            requestMessage = new StringContent(($"fields id,name,first_release_date,summary,platforms; where name ~ *\"{queryName}\"* & version_parent = null; limit 500; sort name asc;"), Encoding.UTF8, "application/json");

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            ServicePointManager.ServerCertificateValidationCallback = (snder, cert, chain, error) => true;
            try
            {
                HttpResponseMessage response = await HttpStaticClient.GetInstance.PostAsync(_address, requestMessage).ConfigureAwait(false);

                var result = await HttpStaticClient.GetInstance.PostAsync(_address, null).ConfigureAwait(false);

                var jsonOutput = response.Content.ReadAsStringAsync().Result;
                List <GameDetailsModel> game = JsonConvert.DeserializeObject <List <GameDetailsModel> >(jsonOutput);
                return(game);
            }
            catch (HttpRequestException)
            {
                throw new HttpRequestException();
            }

            #endregion
        }
Example #36
0
        public void FormatX()
        {
            var x = ParsedFormat.Parse("x");
            var X = ParsedFormat.Parse("X");

            var sb = new StringFormatter();

            sb.Append((ulong)255, x);
            sb.Append((uint)255, X);
            Assert.Equal("ffFF", sb.ToString());

            sb.Clear();
            sb.Append((int)-1, X);
            Assert.Equal("FFFFFFFF", sb.ToString());

            sb.Clear();
            sb.Append((int)-2, X);
            Assert.Equal("FFFFFFFE", sb.ToString());
        }
Example #37
0
        public void FormatXPrecision()
        {
            var x = ParsedFormat.Parse("x10");
            var X = ParsedFormat.Parse("X10");

            var sb = new StringFormatter();

            sb.Append((ulong)255, x);
            sb.Append((uint)255, X);
            Assert.Equal("00000000ff00000000FF", sb.ToString());

            sb.Clear();
            sb.Append((int)-1, X);
            Assert.Equal("00FFFFFFFF", sb.ToString());

            sb.Clear();
            sb.Append((int)-2, X);
            Assert.Equal("00FFFFFFFE", sb.ToString());
        }
        public void deposit_amount_should_be_in_the_right_formatn()
        {
            List <HistoryLine> historyLines = new List <HistoryLine>
            {
                new HistoryLine(new DateTime(2012, 1, 10), 1000, null, new Balance(1000))
            };

            string[] message = new StringFormatter().Format(historyLines).Split(Environment.NewLine);
            string   firstHistoryFormattedLine = message[1];

            string[] splittedHistoryline = firstHistoryFormattedLine.Split("||");
            char     space = ' ';

            splittedHistoryline[0].Should().Be("10/01/2012" + space);
            splittedHistoryline[1].Should().Be(space + "1000.00" + space);
            splittedHistoryline[2].Should().Be(space.ToString());
            splittedHistoryline[3].Should().Be(space + "1000.00");
            firstHistoryFormattedLine.Should().Be("10/01/2012 || 1000.00 || || 1000.00");
        }
Example #39
0
        public T Delete <T>(string uuid) where T : EntityBase, new()
        {
            if (string.IsNullOrWhiteSpace(uuid))
            {
                throw new ArgumentNullException("uuid");
            }

            T model = new T();

            var query = new StringFormatter(QueryTemplates.TEMPLATE_DELETE);

            query.Add("@label", model.Label);
            query.Add("@Uuid", uuid);
            query.Add("@updatedAt", DateTime.UtcNow.ToTimeStamp());

            IStatementResult result = ExecuteQuery(query.ToString());

            return(result.Map <T>());
        }
Example #40
0
        /// <summary>
        /// Create a new instance of <see cref="YoutubeDumper"/>
        /// </summary>
        public YoutubeExperimentalDumper(YoutubeExperimentalConfig config)
        {
            _config = config;
            _pool   = ArrayPool <byte> .Shared;
            _client = config.HttpClient ?? new HttpClient();
            //Chrome User-Agent
            if (config.UseChromeUserAgent)
            {
                _client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
            }

            if (!string.IsNullOrWhiteSpace(config.UserAgent))
            {
                _client.DefaultRequestHeaders.Add("User-Agent", config.UserAgent);
            }
            sb         = new StringFormatter();
            sw_parsing = config.MeasureTime ? new Stopwatch() : null;
            sw         = config.MeasureTime ? new Stopwatch() : null;
        }
        public object Convert(object[] value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value.Length < 2)
            {
                throw new ArgumentException("2 values should be provided: string and int length.");
            }

            if (value[0] is not string str)
            {
                throw new ArgumentException("First value should be a string (string to shorten).");
            }

            if (value[1] is not int chars)
            {
                throw new ArgumentException("Second value should be an int (number of chars).");
            }

            return(StringFormatter.CutStart(Path.GetFileNameWithoutExtension(str), chars));
        }
Example #42
0
        public int DropByProperties <T>(Dictionary <string, object> props) where T : EntityBase, new()
        {
            if (props == null || !props.Any())
            {
                throw new ArgumentNullException("props");
            }

            dynamic properties = props.AsQueryClause();
            dynamic clause     = properties.clause;
            Dictionary <string, object> parameters = properties.parameters;

            var query = new StringFormatter(QueryTemplates.TEMPLATE_DROP_BY_PROPERTIES);

            query.Add("@label", new T().Label);
            query.Add("@clause", clause);

            IStatementResult result = ExecuteQuery(query.ToString(), parameters);

            return(result.Summary.Counters.NodesDeleted);
        }
Example #43
0
        public override string GetSummary()
        {
            string displaySummary = "";

            if (display != StageDisplayType.None)
            {
                displaySummary = StringFormatter.SplitCamelCase(display.ToString());
            }
            else
            {
                return("Error: No display selected");
            }
            string stageSummary = "";

            if (stage != null)
            {
                stageSummary = " \"" + stage.name + "\"";
            }
            return(displaySummary + stageSummary);
        }
        private void InvariantFormatStruct()
        {
            ManagedBufferPool <byte> pool = new ManagedBufferPool <byte>(1024);

            timer.Restart();
            for (int itteration = 0; itteration < itterationsInvariant; itteration++)
            {
                StringFormatter sb = new StringFormatter(numbersToWrite * 2, pool);
                for (int i = 0; i < numbersToWrite; i++)
                {
                    sb.Append(new Age(i % 10));
                }
                var text = sb.ToString();
                if (text.Length != numbersToWrite * 2)
                {
                    throw new Exception("test failed");
                }
            }
            PrintTime();
        }
Example #45
0
        private void InvariantFormatIntHex()
        {
            StandardFormat format = new StandardFormat('X', StandardFormat.NoPrecision);

            timer.Restart();
            for (int itteration = 0; itteration < itterationsInvariant; itteration++)
            {
                StringFormatter sb = new StringFormatter(numbersToWrite, pool);
                for (int i = 0; i < numbersToWrite; i++)
                {
                    sb.Append(((int)(i % 10)), format);
                }
                var text = sb.ToString();
                if (text.Length != numbersToWrite)
                {
                    throw new Exception("test failed");
                }
            }
            PrintTime();
        }
Example #46
0
        public IActionResult Index()
        {
            var events = _eventData.GetEventsWithOrganizer();
            var model  = new List <EventViewModel>();

            foreach (var e in events)
            {
                model.Add(new EventViewModel
                {
                    Id     = e.Id,
                    Author = string.IsNullOrEmpty(e.Organizer.Name) || string.IsNullOrEmpty(e.Organizer.Surname)?
                             e.Organizer.UserName:$"{e.Organizer.Name} {e.Organizer.Surname}",
                    ImageUrl    = e.ImageUrl,
                    ReleaseTime = e.Time,
                    TextPreview = StringFormatter.FormatForPreview(e.Text),
                    Title       = e.Name,
                });
            }
            return(View(model));
        }
        private void InvariantFormatIntHex()
        {
            ManagedBufferPool <byte> pool = new ManagedBufferPool <byte>(1024);

            timer.Restart();
            for (int itteration = 0; itteration < itterationsInvariant; itteration++)
            {
                StringFormatter sb = new StringFormatter(numbersToWrite, pool);
                for (int i = 0; i < numbersToWrite; i++)
                {
                    sb.Append(((int)(i % 10)), Format.Parsed.HexUppercase);
                }
                var text = sb.ToString();
                if (text.Length != numbersToWrite)
                {
                    throw new Exception("test failed");
                }
            }
            PrintTime();
        }
Example #48
0
        private void RenderBaseClass(ITable table)
        {
            hdrUtil.WriteClassHeader(output);

            output.autoTabLn("using System;");
            output.autoTabLn("using System.Collections.Generic;");
            output.autoTabLn("using System.Linq;");
            output.autoTabLn("using System.Text;");
            output.autoTabLn("using System.Data.Linq;");
            output.autoTabLn("");
            output.autoTabLn("using " + _script.Settings.BusinessObjects.BusinessObjectsNamespace + ";");
            output.autoTabLn("using " + _script.Settings.DataOptions.DataObjectsNamespace + ".Interfaces;");
            output.autoTabLn("using " + _script.Settings.DataOptions.DataObjectsNamespace + ".EntityFramework;");
            output.autoTabLn("");
            output.autoTabLn("namespace " + _script.Settings.DataOptions.DataObjectsNamespace + ".SQLServer");
            output.autoTabLn("{");
            output.tabLevel++;
            output.autoTabLn("public class " + StringFormatter.CleanUpClassName(table.Name) + "BaseDao : ICRUDDao<" + _context.Utility.BuildModelClassWithNameSpace(StringFormatter.CleanUpClassName(table.Name)) + ">");
            output.autoTabLn("{");
            output.tabLevel++;
            output.autoTabLn("#region CRUD Methods");
            output.autoTabLn("");
            output.tabLevel--;
            output.autoTabLn("");

            _dataStore.GetAll(table);
            _dataStore.Insert(table);
            _dataStore.Update(table);
            _dataStore.Delete(table);

            output.autoTabLn("");
            output.tabLevel++;
            output.autoTabLn("#endregion");
            output.tabLevel--;
            output.autoTabLn("}");
            output.tabLevel--;
            output.autoTabLn("}");

            _context.FileList.Add("    " + StringFormatter.CleanUpClassName(table.Name) + "Base" + _script.Settings.DataOptions.ClassSuffix.Name + ".cs");
            SaveOutput(CreateFullPath(_script.Settings.DataOptions.DataObjectsNamespace + "\\" + _script.Settings.DataOptions.DataStore.Selected + "\\Generated", StringFormatter.CleanUpClassName(table.Name) + "Base" + _script.Settings.DataOptions.ClassSuffix.Name + ".cs"), SaveActions.Overwrite);
        }
Example #49
0
        public void WriteTable(StringTable table, int columnSpacing = 3, bool addVerticalSeparation = false)
        {
            if (table == null)
            {
                throw new ArgumentNullException("table", "table is null.");
            }

            if (IsWordWrapEnabled)
            {
                int indent = m_indent;
                if (indent >= Console.WindowWidth - columnSpacing - 2)
                {
                    indent = 0;
                }

                int maxWidth   = Console.WindowWidth - indent;
                int col1Width  = Math.Min(table.Labels.Max(text => text.Length), maxWidth / 2);
                int colSpacing = columnSpacing;
                int col2Width  = maxWidth - col1Width - colSpacing - 1;

                for (int i = 0; i < table.Count; i++)
                {
                    if (i > 0 && addVerticalSeparation)
                    {
                        Console.WriteLine();
                    }

                    Console.WriteLine(
                        StringFormatter.FormatInColumns(indent, colSpacing,
                                                        new StringFormatter.ColumnInfo(col1Width, table.Labels[i]),
                                                        new StringFormatter.ColumnInfo(col2Width, table.Values[i])));
                }
            }
            else
            {
                for (int i = 0; i < table.Count; i++)
                {
                    Console.WriteLine("{0}{1}{2}{3}", new String(' ', m_indent), table.Labels[i], new String(' ', columnSpacing), table.Values[i]);
                }
            }
        }
Example #50
0
 public void Render(string modelName)
 {
     _output.tabLevel--;
     foreach (string tableName in _script.Tables)
     {
         _output.tabLevel++;
         _output.autoTabLn("#region " + StringFormatter.CleanUpClassName(tableName) + " Mappers");
         _output.autoTabLn("");
         _output.autoTabLn("public static " + StringFormatter.CleanUpClassName(tableName) + modelName + " ToModel(this " + StringFormatter.CleanUpClassName(tableName) + " entity)");
         _output.autoTabLn("{");
         _output.tabLevel++;
         _output.autoTabLn("return AutoMapper.Mapper.Map<" + StringFormatter.CleanUpClassName(tableName) + ", " + StringFormatter.CleanUpClassName(tableName) + modelName + ">(entity);");
         _output.tabLevel--;
         _output.autoTabLn("}");
         _output.autoTabLn("");
         _output.autoTabLn("public static List<" + StringFormatter.CleanUpClassName(tableName) + modelName + "> ToModel(this List<" + StringFormatter.CleanUpClassName(tableName) + "> " + StringFormatter.CamelCasing(StringFormatter.CleanUpClassName(tableName)) + "List)");
         _output.autoTabLn("{");
         _output.tabLevel++;
         _output.autoTabLn("var models = new List<" + StringFormatter.CleanUpClassName(tableName) + modelName + ">();");
         _output.autoTabLn("");
         _output.autoTabLn("if (" + StringFormatter.CamelCasing(StringFormatter.CleanUpClassName(tableName)) + "List != null && " + StringFormatter.CamelCasing(StringFormatter.CleanUpClassName(tableName)) + "List.Count > 0)");
         _output.tabLevel++;
         _output.autoTabLn(StringFormatter.CamelCasing(StringFormatter.CleanUpClassName(tableName)) + "List.ForEach(b => models.Add(b.ToModel()));");
         _output.tabLevel--;
         _output.autoTabLn("");
         _output.autoTabLn("return models;");
         _output.tabLevel--;
         _output.autoTabLn("}");
         _output.autoTabLn("");
         _output.autoTabLn("public static " + StringFormatter.CleanUpClassName(tableName) + " FromModel(this " + StringFormatter.CleanUpClassName(tableName) + modelName + " model)");
         _output.autoTabLn("{");
         _output.tabLevel++;
         _output.autoTabLn("return AutoMapper.Mapper.Map<" + StringFormatter.CleanUpClassName(tableName) + modelName + ", " + StringFormatter.CleanUpClassName(tableName) + ">(model);");
         _output.tabLevel--;
         _output.autoTabLn("} ");
         _output.autoTabLn("#endregion");
         _output.autoTabLn("");
         _output.tabLevel--;
     }
     _output.tabLevel++;
 }
Example #51
0
        public IList <T> GetByProperty <T>(
            string propertyName,
            object propertValue) where T : EntityBase, new()
        {
            if (string.IsNullOrWhiteSpace(propertyName))
            {
                throw new ArgumentNullException("propertyName");
            }

            if (propertValue == null)
            {
                throw new ArgumentNullException("propertValue");
            }

            var entites = new Lazy <List <T> >();

            var query = new StringFormatter(QueryTemplates.TEMPLATE_GET_BY_PROPERTY);

            query.Add("@label", new T().Label);
            query.Add("@property", propertyName);
            query.Add("@result", TAG);
            query.Add("@relatedNode", string.Empty);
            query.Add("@relationship", string.Empty);

            IStatementResult result = ExecuteQuery(query.ToString(), new { value = propertValue });

            foreach (IRecord record in result)
            {
                var node = record[0].As <INode>().Properties;

                var relatedNodes = FetchRelatedNode <T>(node["Uuid"].ToString());

                var nodes = node.Concat(relatedNodes).ToDictionary(x => x.Key, x => x.Value);

                T nodeObject = nodes.Map <T>();

                entites.Value.Add(nodeObject);
            }

            return(entites.Value);
        }
Example #52
0
        private void RenderClass(ITable table)
        {
            var output = _context.Zeus.Output;

            output.clear();

            try
            {
                _hdrUtil.WriteClassHeader(output);

                output.autoTabLn("using System;");
                output.autoTabLn("using System.Collections.Generic;");
                output.autoTabLn("using System.Runtime.Serialization;");
                output.autoTabLn("");
                output.autoTabLn("namespace " + _script.Settings.ServiceLayer.ServiceNamespace + ".DataTransferObjects");
                output.autoTabLn("{");
                output.autoTabLn("    [DataContract(Name = \"" + StringFormatter.CleanUpClassName(table.Name) + "\", Namespace = \"" + _script.Settings.ServiceLayer.DataContract + "\")]");
                output.autoTabLn("    public class " + StringFormatter.CleanUpClassName(table.Name) + "Dto ");
                output.autoTabLn("    {");
                output.autoTabLn("        #region Properties");
                output.autoTabLn("");
                output.tabLevel++;

                RenderProperties(table);

                output.tabLevel--;
                output.autoTabLn("");
                output.autoTabLn("");
                output.autoTabLn("        #endregion");
                output.autoTabLn("    }");
                output.autoTabLn("}");

                _context.FileList.Add("   " + StringFormatter.CleanUpClassName(table.Name) + "Dto.cs");
                SaveOutput(CreateFullPath(@"BusinessObjects", StringFormatter.CleanUpClassName(table.Name) + "Dto.cs"), SaveActions.DontOverwrite);
                output.clear();
            }
            catch (Exception)
            {
                throw;
            }
        }
 /// <summary>
 /// 订阅消息队列
 /// </summary>
 /// <param name="chanels">消息队列</param>
 public void Subscribe <T>(string chanels, Action <T> handler) where T : class, new()
 {
     if (handler == null)
     {
         throw new ArgumentNullException("handler");
     }
     if (string.IsNullOrEmpty(chanels))
     {
         throw new ArgumentException("chanels");
     }
     lock (m_contexts)
     {
         if (m_contexts.FirstOrDefault((i) => i.MqChanels == chanels) != null)
         {
             throw new ArgumentException("repeat");
         }
         MqSubscribeContext context = new MqSubscribeContext
         {
             EventHandler = (message) =>
             {
                 T value = null;
                 if (typeof(string) != typeof(T))
                 {
                     if (!string.IsNullOrEmpty(message))
                     {
                         value = StringFormatter.Deserialize <T>(message);
                     }
                 }
                 else
                 {
                     object obj = message;
                     value = (T)obj;
                 }
                 handler(value);
             },
             EventType = typeof(T),
             MqChanels = chanels
         };
         m_contexts.Add(context);
     }
 }
Example #54
0
        public static void AddMessenger(this IMutableDependencyResolver services)
        {
            // messenger
            services.RegisterLazySingleton <IBasicMessageModelFactory>(() =>
            {
                return(new BasicMessageModelFactory());
            });

            services.RegisterLazySingleton <INoteMessageModelFactory>(() =>
            {
                return(new NoteMessageModelFactory());
            });

            services.RegisterLazySingleton <ISpecialMessageModelFactory>(() =>
            {
                var stringFormatter = new StringFormatter();
                return(new SpecialMessageModelFactory(stringFormatter));
            });

            services.RegisterLazySingleton <IVisualMessageModelFactory>(() =>
            {
                return(new VisualMessageModelFactory());
            });

            services.RegisterLazySingleton <IMessageModelFactory>(() =>
            {
                var basicMessageModelFactory   = services.GetService <IBasicMessageModelFactory>();
                var noteMessageModelFactory    = services.GetService <INoteMessageModelFactory>();
                var specialMessageModelFactory = services.GetService <ISpecialMessageModelFactory>();
                var visualMessageModelFactory  = services.GetService <IVisualMessageModelFactory>();

                var stringFormatter = new StringFormatter();

                return(new MessageModelFactory(
                           basicMessageModelFactory,
                           noteMessageModelFactory,
                           specialMessageModelFactory,
                           visualMessageModelFactory,
                           stringFormatter));
            });
        }
Example #55
0
 public void RenderDaoInterface(ITable table)
 {
     _output.autoTabLn("using System;");
     _output.autoTabLn("using System.Linq;");
     _output.autoTabLn("using System.Collections.Generic;");
     _output.autoTabLn("");
     _output.autoTabLn("using " + _script.Settings.BusinessObjects.BusinessObjectsNamespace + ";");
     _output.autoTabLn("");
     _output.autoTabLn("namespace " + _script.Settings.DataOptions.DataObjectsNamespace + ".Interfaces");
     _output.autoTabLn("{");
     _output.tabLevel++;
     _output.autoTabLn("public interface I" + StringFormatter.CleanUpClassName(table.Name) + _script.Settings.DataOptions.ClassSuffix.Name + " : ICRUD" + _script.Settings.DataOptions.ClassSuffix.Name + "<" + _context.Utility.BuildModelClassWithNameSpace(StringFormatter.CleanUpClassName(table.Name)) + ">");
     _output.autoTabLn("{");
     _output.tabLevel++;
     _output.autoTabLn("" + _context.Utility.BuildModelClassWithNameSpace(StringFormatter.CleanUpClassName(table.Name)) + " GetById(" + StringFormatter.CamelCasing(_context.Utility.RenderConcreteMethodParameters(table)) + ");");
     _output.autoTabLn("List<" + _context.Utility.BuildModelClassWithNameSpace(StringFormatter.CleanUpClassName(table.Name)) + "> GetAll(string sortExpression, int startRowIndex, int maximumRows);");
     _output.tabLevel--;
     _output.autoTabLn("}");
     _output.tabLevel--;
     _output.autoTabLn("}");
 }
Example #56
0
 public void RenderServiceInterface(ITable table)
 {
     _output.autoTabLn("using System;");
     _output.autoTabLn("using System.Collections.Generic;");
     _output.autoTabLn("using System.Linq;");
     _output.autoTabLn("");
     _output.autoTabLn("");
     _output.autoTabLn("namespace " + _script.Settings.ServiceLayer.ServiceNamespace + ".Interfaces");
     _output.autoTabLn("{");
     _output.tabLevel++;
     _output.autoTabLn("public interface I" + StringFormatter.CleanUpClassName(table.Name) + "Service : ICRUDService<" + _context.Utility.BuildModelClassWithNameSpace(StringFormatter.CleanUpClassName(table.Name)) + ">");
     _output.autoTabLn("{");
     _output.tabLevel++;
     _output.autoTabLn(_context.Utility.BuildModelClassWithNameSpace(StringFormatter.CleanUpClassName(table.Name)) + " GetById(" + _context.Utility.RenderConcreteMethodParameters(table) + ");");
     _output.autoTabLn("List<" + _context.Utility.BuildModelClassWithNameSpace(StringFormatter.CleanUpClassName(table.Name)) + "> GetAll(string sortExpression, int startRowIndex, int maximumRows);");
     _output.autoTabLn("int GetCount();");
     _output.tabLevel--;
     _output.autoTabLn("}");
     _output.tabLevel--;
     _output.autoTabLn("}");
 }
Example #57
0
        /// <summary>
        /// Gets a string consisting of the program name, version and copyright notice.
        /// </summary>
        /// <param name="width">The total width in characters in which the string should be fitted</param>
        /// <returns>a string consisting of the program name, version and copyright notice.</returns>
        /// <remarks>This string is suitable for printing as the first output of a console application.</remarks>
        public string GetHeaderAsString(int width)
        {
            StringBuilder result = new StringBuilder();

            result.Append(ApplicationName ?? "Unnamed application");
            if (ApplicationVersion != null)
            {
                result.Append("  ");
                result.Append(CommandLineStrings.Version);
                result.Append(' ');
                result.Append(ApplicationVersion);
            }
            result.Append(Environment.NewLine);

            if (ApplicationCopyright != null)
            {
                result.Append(ApplicationCopyright);
                result.Append(Environment.NewLine);
            }
            return(StringFormatter.WordWrap(result.ToString(), width));
        }
Example #58
0
        private void FormatGuid()
        {
            var guid         = Guid.NewGuid();
            var guidsToWrite = numbersToWrite / 10;

            timer.Restart();
            for (int itteration = 0; itteration < itterationsInvariant; itteration++)
            {
                StringFormatter sb = new StringFormatter(guidsToWrite * 36, pool);
                for (int i = 0; i < guidsToWrite; i++)
                {
                    sb.Append(guid);
                }
                var text = sb.ToString();
                if (text.Length != guidsToWrite * 36)
                {
                    throw new Exception("test failed");
                }
            }
            PrintTime();
        }
        private void RenderInterface(ITable table)
        {
            _hdrUtil.WriteClassHeader(_output);

            _output.autoTabLn("using System;");
            _output.autoTabLn("using System.Linq;");
            _output.autoTabLn("using " + _script.Settings.BusinessObjects.BusinessObjectsNamespace + ";");
            _output.autoTabLn("using " + _script.Settings.ServiceLayer.ServiceNamespace + ".Generated;");
            _output.autoTabLn("");
            _output.autoTabLn("namespace " + _script.Settings.ServiceLayer.ServiceNamespace + ".Interfaces");
            _output.autoTabLn("{");
            _output.tabLevel++;
            _output.autoTabLn("public interface I" + StringFormatter.CleanUpClassName(table.Name) + "Service : IService<" + StringFormatter.CleanUpClassName(table.Name) + ">");
            _output.autoTabLn("{");
            _output.autoTabLn("}");
            _output.tabLevel--;
            _output.autoTabLn("}");

            _context.FileList.Add("    I" + StringFormatter.CleanUpClassName(table.Name) + "Service.cs");
            SaveOutput(CreateFullPath(_script.Settings.ServiceLayer.ServiceNamespace + "\\Interfaces", "I" + StringFormatter.CleanUpClassName(table.Name) + "Service.cs"), SaveActions.DontOverwrite);
        }
Example #60
0
        public static string __repr__(CodeContext /*!*/ context, double self)
        {
            if (Double.IsNaN(self))
            {
                return("nan");
            }

            // first format using Python's specific formatting rules...
            StringFormatter sf = new StringFormatter(context, "%.17g", self);

            sf._TrailingZeroAfterWholeFloat = true;
            string res = sf.Format();

            if (LiteralParser.ParseFloat(res) == self)
            {
                return(res);
            }

            // if it's not round trippable though use .NET's round-trip format
            return(self.ToString("R", CultureInfo.InvariantCulture));
        }