Exemple #1
0
        private static void DetectTextGetJson()
        {
            var configuration = Construction.GetConfiguration();

            var bucketName = configuration["S3BucketName"];

            var imageFilePath = configuration["ImageFilePath"];
            var objectKey     = Construction.GetKeyNameFromFilePath(imageFilePath);

            using (var rekognitionClient = Construction.GetAmazonRekognitionClient())
            {
                rekognitionClient.AfterResponseEvent += RekognitionClient_AfterResponseEvent;

                var detectTextRequest = new DetectTextRequest
                {
                    Image = new Image
                    {
                        S3Object = new S3Object
                        {
                            Bucket = bucketName,
                            Name   = objectKey,
                        },
                    },
                };

                var detectTextResponse = rekognitionClient.DetectTextAsync(detectTextRequest).Result;

                JsonFileSerializer.Serialize(@"C:\Temp\temp.json", detectTextResponse);
            }
        }
Exemple #2
0
        public void Start()
        {
            string path           = "SqlStatements.json";
            var    jsonSerializer = new JsonFileSerializer();

            while (true)
            {
                Console.WriteLine($"Press 1 : Tokenize list of sql statements{Environment.NewLine}");

                var selection = Console.ReadKey();

                switch (selection.KeyChar.ToString())
                {
                case "1":
                    foreach (var statement in jsonSerializer.ParseSqlStrings(path))
                    {
                        var tonkenizer = new RegexTokenizer();

                        Console.WriteLine($"Outputing token list:{Environment.NewLine}");
                        OutputTokenList(tonkenizer, statement);
                    }
                    break;

                default:
                    Console.WriteLine("Enter a valid selection.");
                    break;
                }
            }
        }
        public void Read_WhenRead_ThenNotThrowException()
        {
            // Arrange
            var serializer = new JsonFileSerializer();
            var collection = new List <int>();

            // Act - Assert
            Assert.DoesNotThrow(() => serializer.Read <int>("file1"));
        }
        public void Write_WhenWrite_ThenNotThrowException()
        {
            // Arrange
            var serializer = new JsonFileSerializer();
            var collection = new List <int>();

            // Act - Assert
            Assert.DoesNotThrow(() => serializer.Write(collection, "file1"));
        }
        public NavigationWrapper LoadNavigationFromJsonFile()
        {
            var cf       = Catalog.Factory.Resolve <IConfig>();
            var filePath = string.Format(NavigationFileFormat, cf[ContentFileStorage.NavigationConfig]);

            filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);
            var navigator = JsonFileSerializer.ExtractObject <NavigationWrapper>(filePath);

            return(navigator);
        }
        public static RoleSpecWrapper LoadRoleSpecsFromJson()
        {
            const string RolesFileFormat = "{0}.json";
            var          cf = Catalog.Factory.Resolve <IConfig>();

            var filePath = string.Format(RolesFileFormat, cf[ContentFileStorage.RolesSpecConfiguration]);

            filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);

            var rolesSpec = JsonFileSerializer.ExtractObject <RoleSpecWrapper>(filePath);

            return(rolesSpec);
        }
Exemple #7
0
 private void ExportToFileButton_Click(object sender, EventArgs e)
 {
     FileSaveDialog.InitialDirectory = Directory.GetCurrentDirectory();
     if (FileSaveDialog.ShowDialog() == DialogResult.OK)
     {
         try
         {
             JsonFileSerializer.SerializeSnapshotsToJson(ImportedDatabase, FileSaveDialog.OpenFile());
         }
         catch (Exception Ex)
         {
             if (Ex is JsonSerializationException || Ex is JsonReaderException)
             {
                 GUIHelper.ThrowWarning("File error", "Serialization failed.");
             }
         }
     }
 }
Exemple #8
0
        private void StartContext()
        {
            while (true)
            {
                Console.WriteLine("1. Добавить магазин");
                Console.WriteLine("2. Сохранить текущее состояние в файле");
                Console.WriteLine("3. Контроллер магазина");
                Console.WriteLine("Ответ: ");
                if (int.TryParse(Console.ReadLine(), out int answer))
                {
                    switch (answer)
                    {
                    case 1:
                    {
                        var builder = new ShopBuilder();
                        var shop    = builder.Build();
                        Shops.Add(shop);
                        break;
                    }

                    case 2:
                    {
                        var serializer = new JsonFileSerializer <List <Shop> >($"{Directory.GetCurrentDirectory()}//shops.json");
                        serializer.Rewrite(Shops);
                        break;
                    }

                    case 3:
                    {
                        if (Shops.Count == 0)
                        {
                            Console.WriteLine("Магазинов нет!");
                        }
                        else
                        {
                            var shop = GetShop();
                            ShopController(shop);
                        }
                        break;
                    }
                    }
                }
            }
        }
Exemple #9
0
 private void ImportButton_Click(object sender, EventArgs e)
 {
     FileSelectDialog.InitialDirectory = Directory.GetCurrentDirectory();
     if (FileSelectDialog.ShowDialog() == DialogResult.OK)
     {
         try
         {
             ImportedDatabase = JsonFileSerializer.DeserializeSnapshotsFromJson(FileSelectDialog.OpenFile());
             UpdateImportedEventsBox();
         }
         catch (Exception Ex)
         {
             if (Ex is JsonSerializationException || Ex is JsonReaderException)
             {
                 GUIHelper.ThrowWarning("File error", "Deserialization failed. Make sure to select the right file.");
             }
         }
     }
 }
        public static void Save()
        {
            if (_instance == null)
            {
                return;              //tu: ignore autosaves before fully rehydrated from the [iso] store.
            }
            switch (_storMode)
            {
            default:
            case StorageMode.OneDriveU: JsonFileSerializer.Save(_instance, _pathfile); break;

            case StorageMode.OneDrAlex: JsonFileSerializer.Save(_instance, _pathfile); break;

            case StorageMode.IsoProgDt: JsonIsoFileSerializer.Save(_instance); break;

            case StorageMode.IsoUsrLcl: JsonIsoFileSerializer.Save(_instance, null, IsoConst.ULocA); break;

            case StorageMode.IsoUsrRoa: JsonIsoFileSerializer.Save(_instance, null, IsoConst.URoaA); break;
            }
        }
Exemple #11
0
        public void OnExecute()
        {
            // Don't execute if we are showing help.
            if (ShowHelp)
            {
                return;
            }

            MtxEncoding encoding = null;
            var         version  = Version ?? "auto";

            if (version == "auto")
            {
                if (FntPath != null || FpdPath != null)
                {
                    version = "1";
                }
                else
                {
                    version = "2";
                }
            }
            if (version == "1")
            {
                if (FntPath != null)
                {
                    if (!File.Exists(FntPath))
                    {
                        Error(string.Format(ErrorMessages.FileDoesNotExist, FntPath));
                        return;
                    }

                    var fntFile = new FntFile(FntPath);
                    encoding = new CharacterMapMtxEncoding(fntFile.Characters);
                }
                else if (FpdPath != null)
                {
                    if (!File.Exists(FpdPath))
                    {
                        Error(string.Format(ErrorMessages.FileDoesNotExist, FpdPath));
                        return;
                    }

                    var fpdFile = new FpdFile(FpdPath);
                    encoding = new CharacterMapMtxEncoding(fpdFile.Characters);
                }
                else
                {
                    Error(ErrorMessages.FntOrFpdOptionMustBeSet);
                    return;
                }
            }
            else if (version == "2")
            {
                encoding = new Utf16MtxEncoding();
            }

            foreach (var file in Files)
            {
                if (!File.Exists(file))
                {
                    Error(string.Format(ErrorMessages.FileDoesNotExist, file));
                    continue;
                }

                var format = Format ?? "auto";
                if (format == "auto")
                {
                    var extension = Path.GetExtension(file);

                    if (extension.Equals(".mtx", StringComparison.OrdinalIgnoreCase))
                    {
                        format = "json";
                    }
                    else if (extension.Equals(".json", StringComparison.OrdinalIgnoreCase))
                    {
                        format = "mtx";
                    }
                    else
                    {
                        Error(string.Format(ErrorMessages.CouldNotDetermineOutputFormat, file));
                        continue;
                    }
                }

                if (format == "json")
                {
                    var outputFilename = Output ?? Path.ChangeExtension(file, ".json");

                    try
                    {
                        var mtxFile = new MtxFile(file, encoding);
                        var mtxJson = new MtxJson
                        {
                            Has64BitOffsets = mtxFile.Has64BitOffsets,
                            Entries         = mtxFile.Entries,
                        };
                        JsonFileSerializer.Serialize(outputFilename, mtxJson);
                    }
                    catch (Exception e)
                    {
                        Error(e.Message);
                    }
                }
                else if (format == "mtx")
                {
                    var outputFilename = Output ?? Path.ChangeExtension(file, ".mtx");

                    try
                    {
                        var mtxJson = JsonFileSerializer.Deserialize <MtxJson>(file);
                        var mtxFile = new MtxFile(mtxJson.Entries, encoding, mtxJson.Has64BitOffsets ? true : Has64BitOffsets);
                        mtxFile.Save(outputFilename);
                    }
                    catch (Exception e)
                    {
                        Error(e.Message);
                    }
                }
            }
        }
Exemple #12
0
        private static void DeserializeDetectTextResponse()
        {
            var jsonFilePath = @"C:\Temp\temp.json";

            var detectTextResponse = JsonFileSerializer.Deserialize <DetectTextResponse>(jsonFilePath);
        }
        async Task migrate(A0DbMdl db)
        {
            Bpr.Beep1of2();
            var obsVm = JsonFileSerializer.Load <ObsMainVM>(MainVM.MainVmJsonFile) as ObsMainVM;

            if (obsVm == null)
            {
                MessageBox.Show("No Go");
            }
            else
            {
                var srFromJsonWithNote = obsVm.SnRts.Where(r => !string.IsNullOrEmpty(r.Notes));

                try
                {
                    if (db.SessionResults.Any(r => r.Note != null && (r.Note == "zz" || r.Note.StartsWith("from fs at"))))
                    {
                        db.SessionResults.Where(r => r.Note != null && (r.Note == "zz" || r.Note.StartsWith("from fs at"))).ToList().ForEach(r => r.Note = "");
                    }

                    tbInfo.Text = $"Json: \t{obsVm.SnRts.Length} total runs incl-g {srFromJsonWithNote.Count()} with note;\r\nDB: \t{db.SessionResults.Count()} \r\n";
                    Debug.WriteLine($"::>{tbInfo.Text}");

                    await Task.Yield();

                    Bpr.BeepClk();

                    int brandNew = 0, noMatchesInDb = 0, alreadySame = 0, updated = 0;

                    foreach (var srjs in obsVm.SnRts)
                    {
                        var srdb0 = db.SessionResults.FirstOrDefault(d =>
                                                                     d.UserId == srjs.UserId &&
                                                                     d.Duration == srjs.Duration /*drn(srjs.Duration)*/ &&
                                                                     d.ExcerciseName == srjs.ExcerciseName &&
                                                                     d.PokedIn == srjs.PokedIn &&
                                                                     Math.Abs((d.DoneAt - srjs.DoneAt.DateTime.AddMinutes(srjs.DoneAt.OffsetMinutes)).TotalSeconds) < 5);
                        if (srdb0 == null)
                        {
                            db.SessionResults.Add(new SessionResult
                            {
                                DoneAt        = srjs.DoneAt.DateTime.AddMinutes(srjs.DoneAt.OffsetMinutes),
                                UserId        = srjs.UserId,
                                Duration      = srjs.Duration /*drn(srjs.Duration)*/,
                                ExcerciseName = srjs.ExcerciseName,
                                PokedIn       = srjs.PokedIn,
                                Note          = srjs.Notes
                            });
                            brandNew++;
                        }
                    }

                    try
                    {
                        foreach (var srjs in srFromJsonWithNote)
                        {
                            var srdb2 = db.SessionResults.FirstOrDefault(d => Math.Abs((d.DoneAt - srjs.DoneAt.DateTime.AddMinutes(srjs.DoneAt.OffsetMinutes)).TotalSeconds) < 5);
                            if (srdb2 == null)
                            {
                                db.SessionResults.Add(new SessionResult
                                {
                                    DoneAt        = srjs.DoneAt.DateTime.AddMinutes(srjs.DoneAt.OffsetMinutes),
                                    UserId        = srjs.UserId,
                                    Duration      = srjs.Duration /*drn(srjs.Duration)*/,
                                    ExcerciseName = srjs.ExcerciseName,
                                    PokedIn       = srjs.PokedIn,
                                    Note          = srjs.Notes
                                });
                                noMatchesInDb++;
                            }
                            else
                            {
                                if (srjs.Notes.Equals(srdb2.Note))
                                {
                                    alreadySame++;
                                }
                                else
                                {
                                    updated++;
                                    srdb2.Note = srjs.Notes;
                                }
                            }
                        }
                    }
                    catch (Exception ex) { Debug.WriteLine(ex); }


                    tbInfo.Text += $" brandNew {brandNew}, notFoundInDb {noMatchesInDb }, alreadySame {alreadySame }, updated {updated}\n";
                    Debug.WriteLine($"::>{tbInfo.Text}");

                    var rv = await db.TrySaveReportAsync();

                    tbInfo.Text += $" {rv}";
                    Bpr.Beep2of2();
                }
                catch (Exception ex) { tbEror.Text = ex.Log(); }
                finally { new DbExplorer2().Show(); }
            }
        }
        public static int Main(string[] args)
        {
            try
            {
#pragma warning disable CA1416
                ConsoleHelper.RedefineConsoleColors(bgColor: Color.FromArgb(17, 17, 17));
#pragma warning restore CA1416

                var cmdLineParser = ComparisonServices.CmdLineParser;
                cmdLineParser.ThrowIfNull(nameof(cmdLineParser));

                IOptions         options      = null !;
                string?          configToLoad = null;
                CmdLineParserSoE cmdParser    = new();

                if (File.Exists(DefaultConfigFileName))
                {
                    configToLoad = DefaultConfigFileName;
                }
                else
                {
                    options = cmdParser.Parse(args);

                    if (options.ConfigPath is { } configFile)
                    {
                        configToLoad = configFile;
                    }
                }

                if (configToLoad is not null)
                {
                    try
                    {
                        var loadedConfig = JsonFileSerializer.Deserialize <Options>(configToLoad);
                        options = cmdParser.Parse(args, loadedConfig);
                    }
                    catch (Exception ex)
                    {
                        ConsolePrinter.PrintError(ex);
                        options = cmdParser.Parse(args);
                    }
                }

                ConsolePrinter.ColorizeOutput = options.ColorizeOutput;

                if (configToLoad is not null)
                {
                    ConsolePrinter.PrintSectionHeader();
                    ConsolePrinter.PrintColoredLine(ConsoleColor.Green,
                                                    Resources.StatusConfigFileLoadedTemplate.InsertArgs(configToLoad));
                    ConsolePrinter.ResetColor();
                }

                if (options.BatchCommands is null)
                {
                    CommandMenu.Instance.Show(options);
                }
                else
                {
                    CommandQueue.Instance.Start(options);
                }
            }
            catch (Exception ex)
            {
                ConsolePrinter.PrintFatalError(ex.Message + Environment.NewLine + ex.StackTrace);

                try
                {
                    Console.ReadKey();
                }
                catch
                {
                    // Ignore
                }
            }

            return(0);
        }