Exemple #1
0
        public override string ToString()
        {
            ConsoleWrite.Write("Subject: ");
            ConsoleWrite.Write($"{this.Subject.ToString()}", ConsoleColor.Cyan);
            Console.WriteLine();

            ConsoleWrite.Write("Presentation URL: ");
            ConsoleWrite.Write($"{this.PresentationUrl.ToString()}", ConsoleColor.Cyan);
            Console.WriteLine();

            ConsoleWrite.Write($"Speaker: ");
            ConsoleWrite.Write($"{this.Speaker.Name}", ConsoleColor.Cyan);
            Console.WriteLine();

            ConsoleWrite.Write("Company: ");
            ConsoleWrite.Write($"{this.Speaker.Company.Name}", ConsoleColor.Cyan);
            Console.WriteLine();

            ConsoleWrite.Write("Role: ");
            ConsoleWrite.Write($"{this.Speaker.Company.Role}", ConsoleColor.Cyan);
            Console.WriteLine();

            ConsoleWrite.WriteLine($"Contacts:");

            ConsoleWrite.WriteLine($"- LinkedIn: {this.Speaker.Linkedin}", ConsoleColor.Cyan);
            ConsoleWrite.WriteLine($"- GitHub: {this.Speaker.GitHub}", ConsoleColor.Cyan);

            return(base.ToString());
        }
Exemple #2
0
        public static void CreateDatabase()
        {
            var conn      = new SqlConnectionStringBuilder(Configuration.GetConnectionString("DefaultConnection"));
            var rootDir   = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "..", "..", ".."));
            var dbName    = conn.InitialCatalog;
            var dbServer  = conn.DataSource;
            var dbTrusted = conn.IntegratedSecurity;

            using (var ps = PowerShell.Create())
            {
                ps.AddScript($@"if (!(Test-Path ""{rootDir}\Database"")) {{
                                    mkdir ""{rootDir}\Database""
                                }}");

                var script = $@"
                                IF EXISTS(SELECT * FROM sys.databases WHERE name='{dbName}')
                                BEGIN
                                    ALTER DATABASE [{dbName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
                                    DROP DATABASE [{dbName}];
                                END
                                CREATE DATABASE [{dbName}] On (NAME = '{dbName}', FILENAME = '{rootDir}\Database\{dbName}.mdf') COLLATE SQL_Latin1_General_CP1_CI_AI;
                            ";

                var exec = $@"sqlcmd -S ""{dbServer}"" $(&{{ If({dbTrusted}) {{ ""-E"" }} }}) -Q ""{script}"" ";

                ps.AddScript(exec);

                var results = ps.Invoke();
                foreach (var result in results)
                {
                    Debug.Write(result.ToString());
                    ConsoleWrite.Color(result.ToString());
                }
            }
        }
Exemple #3
0
        public ISqlScript[] GetScripts()
        {
            var files   = new List <ISqlScript>();
            var baseDir = BaseFolder;

            var filteredFolders = Folders.ToList();

            foreach (var folder in filteredFolders)
            {
                var fullPath = Path.Combine(baseDir, folder.Path.Trim('\\'));
                if (!Directory.Exists(fullPath))
                {
                    ConsoleWrite.WriteLine("> Folder not found (ignored): " + fullPath, ConsoleColor.Yellow);
                    continue;
                }

                foreach (var filePath in Directory.GetFiles(fullPath, "*.sql", SearchOption.AllDirectories))
                {
                    var content = File.ReadAllText(filePath);
                    var name    = filePath.Replace(baseDir, "");
                    if (files.All(x => x.Name != name))
                    {
                        files.Add(new SqlScript(name, content));
                    }
                }
            }

            return(files.ToArray());
        }
        private static void SetupListening()
        {
            ConsoleWrite.LineLine("Starting setting up DiagnosticSource listening.");

            IDisposable listenerSubscription = DiagnosticListener.AllListeners.Subscribe(ObserverAdapter.OnNextHandler(
                                                                                             (DiagnosticListener diagLstnr) =>
            {
                // This lambda looks at ALL Diagnostic Listeners (aka Sources),
                // picks the one it is inderested in and subscibes to that particular Source.

                ConsoleWrite.Line($"Subscriber called: OnNext(diagLstnr.Name: \"{diagLstnr.Name}\")");

                if (diagLstnr.Name.Equals("DemoXxx.UseDiagnosticSource.Name1", StringComparison.Ordinal))
                {
                    IDisposable eventSubscription = diagLstnr.Subscribe(ObserverAdapter.OnNextHandler(
                                                                            (KeyValuePair <string, object> eventInfo) =>
                    {
                        ConsoleWrite.Line($"Event Handler called: OnNext(eventInfo.Key: \"{eventInfo.Key}\", eventInfo.Value: {(eventInfo.Value ?? "<null>")})");
                    }),
                                                                        (name, arg1, arg2) =>
                    {
                        Validate.NotNull(name, nameof(name));
                        bool res = name.StartsWith("EventXyzName", StringComparison.OrdinalIgnoreCase) &&
                                   (arg1 == null || !(arg1 is Int32 arg1Val) || arg1Val >= 0);
                        ConsoleWrite.Line($"Filter called: IsEnabled(name: \"{name}\", arg1: {(arg1 ?? "<null>")}, arg2: {(arg2 ?? "<null>")})."
                                          + $" Returning: {res}.");
                        return(res);
                    });
                }
            }));

            ConsoleWrite.Line("Finished setting up DiagnosticSource listening.");
        }
Exemple #5
0
        public static void Run_Fancy()
        {
            var scores = new List <double>();

            for (double s = ConsoleRead.ReadDouble(); s != -1; s = ConsoleRead.ReadDouble())
            {
                scores.Add(s);
            }
            double avg       = scores.Average();
            double threshold = 0.0001;

            for (int i = 0; i < scores.Count; i++)
            {
                string pos   = "";
                var    color = ConsoleColor.Yellow;

                if (scores[i] - threshold > avg)
                {
                    pos   = "ABOVE ";
                    color = ConsoleColor.Green;
                }
                else if (scores[i] + threshold < avg)
                {
                    pos   = "BELOW ";
                    color = ConsoleColor.Red;
                }

                ConsoleWrite.WriteLinesColored(color, $"{scores[i]:f2} {pos}AVERAGE");
            }
        }
Exemple #6
0
        static int[] MainMenu()
        {
            int mode = int.MaxValue;

            while (mode > 2)
            {
                if (mode == 3)
                {
                    if (!File.Exists("Highscores"))
                    {
                        mode = ConsoleWrite.Menu("Snake", new[] { "Start Playing", "Tron (2P)", "Looping mode", "No Highscores" });
                        continue;
                    }
                    string[] scores;
                    using (var reader = new StreamReader("Highscores"))
                    {
                        var lines = new List <string>(reader.ReadToEnd().Split(new [] { "\r\r\n", "\r\n", "\n" }, StringSplitOptions.None));
                        lines.Remove("");
                        scores = lines.ToArray();
                    }
                }
                mode = ConsoleWrite.Menu("Snake", new[] { "Start Playing", "Tron (2P)", "Looping mode", "View Highscores" });
            }
            int x     = (ConsoleWrite.Menu("Board X", Enumerable.Range(2, (Console.LargestWindowWidth - 2) / 10 - 1).Select(i => (i * 10).ToString()).ToArray()) + 2) * 10;
            int y     = (ConsoleWrite.Menu("Board Y", Enumerable.Range(2, (Console.LargestWindowHeight - 5) / 10 - 1).Select(i => (i * 10).ToString()).ToArray()) + 2) * 10;
            int speed = (ConsoleWrite.Menu("Snake Speed", new[] { "10", "20", "30", "40", "50", "60", "70", "80", "90", "100" }) + 1) * 10;

            return(new[] { x, y, speed, mode });
        }
Exemple #7
0
        public void Print(int depth = 0)
        {
            int c = 0;

            if (depth > 0)
            {
                for (int i = 0; i < depth; i++)
                {
                    while (c > colors.Length - 1)
                    {
                        c -= colors.Length;
                    }
                    ConsoleWrite.WriteColored(darkColors[c], "   |");
                    c++;
                }
            }

            while (c > colors.Length - 1)
            {
                c -= colors.Length;
            }

            ConsoleWrite.WriteLinesColored(this.completesString ? colors[c] : darkColors[c], (IsLeaf ? " " : " > ") + this.letter);

            foreach (TrieSet child in children.Values.OrderBy(x => x.children.Count))
            {
                child.Print(depth + 1);
            }
        }
        private void ReadOsm(System.Xml.XmlTextReader xml)
        {
            using (var osm = xml.ReadSubtree())
            {
                //while (osm.Read())
                //{
                //    if (osm.NodeType == System.Xml.XmlNodeType.Element && (osm.Name == "node" || osm.Name == "way"))
                //    {
                //        ReadAnyOsmElement(osm);
                //    }
                //}

                while (true)
                {
                    try
                    {
                        bool canRead = osm.Read();
                        if (!canRead)
                        {
                            break;
                        }
                        if (osm.NodeType == System.Xml.XmlNodeType.Element && (osm.Name == "node" || osm.Name == "way"))
                        {
                            ReadAnyOsmElement(osm);
                        }
                    }
                    catch (Exception e)
                    {
                        ConsoleWrite.Red("Error occured when reading XML-tree.");
                    }
                }
            }
        }
Exemple #9
0
        private static void SetupListening()
        {
            ConsoleWrite.LineLine("Starting setting up DiagnosticSource listening.");

            IDisposable listenerSubscription = DiagnosticListening.SubscribeToAllSources(ObserverAdapter.OnNextHandler(
                                                                                             (DiagnosticListenerStub diagnosticListener) =>
            {
                ConsoleWrite.Line($"Subscriber called: diagnosticSourceObserver(diagnosticListener.Name: \"{diagnosticListener.Name}\")");

                if (diagnosticListener.Name.Equals("DemoXxx.UseDiagnosticSource.Name1", StringComparison.Ordinal))
                {
                    IDisposable eventSubscription = diagnosticListener.SubscribeToEvents(
                        ObserverAdapter.OnNextHandler((KeyValuePair <string, object> eventInfo) =>
                    {
                        ConsoleWrite.Line($"Event Handler called: eventObserver(eventName: \"{eventInfo.Key}\", payloadValue: {(eventInfo.Value ?? "<null>")})");
                    }),
                        (string eventName, object arg1, object arg2) =>
                    {
                        Validate.NotNull(eventName, nameof(eventName));
                        bool res = eventName.StartsWith("EventXyzName", StringComparison.OrdinalIgnoreCase) &&
                                   (arg1 == null || !(arg1 is Int32 arg1Val) || arg1Val >= 0);
                        ConsoleWrite.Line($"Filter called: isEventEnabledFilter(eventName: \"{eventName}\", arg1: {(arg1 ?? "<null>")}, arg2: {(arg2 ?? "<null>")})."
                                          + $" Returning: {res}.");
                        return(res);
                    });
                }
            }));

            ConsoleWrite.Line("Finished setting up DiagnosticSource listening.");
        }
Exemple #10
0
        public void ShouldOutputFromInt()
        {
            IWrite writer = new ConsoleWrite();
            IInto  value  = new IntegerOf(3);

            value.Into(writer);
        }
        public async Task RunAssessmentsForExercise(ApplicationUser user, string code, int chapter, int exercise)
        {
            var      output = new StringBuilder();
            Exercise exerciseDetails;
            string   userCode;
            var      result = false;

            if (!user.ExercisePermitted(chapter, exercise))
            {
                WriteToConsole("You do not have permission to do this exercise\r\n");
                return;
            }
            if ((exerciseDetails = await rep.GetExerciseAsync(chapter, exercise)) == null)
            {
                WriteToConsole("Invalid exercise details\r\n");
                return;
            }
            if (!code.StartsWith(exerciseDetails.HiddenCodeHeader))
            {
                WriteToConsole("Something went wrong with the pre-prepared code header");
                throw new InvalidOperationException("Start of user's code does not match the hidden code header");
            }
            userCode = code.Substring(exerciseDetails.HiddenCodeHeader.Length + 1);

            try
            {
                var assessmentGroups = await rep.GetAssessmentGroupsForExerciseAsync(chapter, exercise);

                var assessmentRunner = new AssessmentRunner(codeRunner, code);
                assessmentRunner.ConsoleWrite += OnConsoleWrite;
                result = await assessmentRunner.RunAssessmentsAsync(assessmentGroups);

                assessmentRunner.ConsoleWrite -= OnConsoleWrite;
            }
            finally
            {
                var savedAssessment = new Submission
                {
                    UserId             = user.Id,
                    ChapterNo          = chapter,
                    ExerciseNo         = exercise,
                    SubmittedCode      = userCode,
                    Output             = output.ToString(),
                    Success            = result,
                    SubmissionDateTime = DateTimeOffset.UtcNow
                };
                await rep.InsertSubmissionAsync(savedAssessment);
            }

            void WriteToConsole(string message)
            {
                OnConsoleWrite(this, new ConsoleWriteEventArgs(message));
            }

            void OnConsoleWrite(object sender, ConsoleWriteEventArgs e)
            {
                output.Append(e.Message);
                ConsoleWrite?.Invoke(sender, e);
            }
        }
Exemple #12
0
 public void ConsoleIn(string text)
 {
     if (text == "Console In")
     {
         ConsoleWrite?.Invoke(this, new ConsoleWriteEventArgs("Received"));
         done.Set();
     }
 }
Exemple #13
0
        // This demo shows how to use the stub APIs directly, without protecting against dynamic invocation exceptions.
        // The corresponding Net Core demo shows one of several possible ways for dealing with such exceptions.
        // Other demos show other approaches for dealing with these exceptions.

        public static void Main(string[] _)
        {
            ConsoleWrite.Line(typeof(Program).FullName);

            UseDiagnosticSourceStub.Run();

            ConsoleWrite.Line("Done. Press enter.");
            Console.ReadLine();
        }
        public static void Run()
        {
            // This demo shows one of several possible ways for dealing with dynamic invocation exceptions.
            // The corresponding Net Fx demo shows how to use the APIs directly.
            // Other demos show other approaches for dealing with these exceptions.

            ConsoleWrite.LineLine($"STARTING DEMO '{nameof(UseDiagnosticSourceStub)}'.");

            SetupListening();

            DiagnosticSourceSafeExtensions.Configure.LogComponentMoniker    = "Demo.Slimple.NetCore31";
            DiagnosticSourceSafeExtensions.Configure.IsLogExceptionsEnabled = true;

            ConsoleWrite.LineLine("Starting to create new Diagnostic Sources.");

            if (!DiagnosticSourceSafeExtensions.CreateNewSourceSafe("DemoXxx.UseDiagnosticSource.Name1", out DiagnosticSourceStub diagnosticSource1, out _))
            {
                ConsoleWrite.Line("Cannot create DiagnosticSource. Error was logged. Bailing out.");
                return;
            }

            if (!DiagnosticSourceSafeExtensions.CreateNewSourceSafe("DemoXxx.UseDiagnosticSource.Name2", out DiagnosticSourceStub diagnosticSource2, out _))
            {
                ConsoleWrite.Line("Cannot create DiagnosticSource. Error was logged. Bailing out.");
                return;
            }

            ConsoleWrite.Line("Finished creating new Diagnostic Sources.");

            ConsoleWrite.LineLine("Starting to emit DiagnosticSource events.");
            for (int i = 0; i < 1000; i++)
            {
                if (diagnosticSource1.IsEnabledSafe("EventXyzName.A", out bool isEventEnabled, out _) && isEventEnabled)
                {
                    diagnosticSource1.WriteSafe("EventXyzName", new EventXyzNamePayload("Foo", 42, i), out _);
                }

                if (diagnosticSource1.IsEnabledSafe("EventXyzName.B", arg1: "Something", arg2: 13.7, out isEventEnabled, out _) && isEventEnabled)
                {
                    diagnosticSource1.WriteSafe("EventXyzName", new EventXyzNamePayload("Bar", new[] { 1, 2, 3 }, i), out _);
                }

                if (diagnosticSource1.IsEnabledSafe("EventXyzName.C", arg1: -1, out isEventEnabled, out _) && isEventEnabled)
                {
                    diagnosticSource1.WriteSafe("EventXyzName", new EventXyzNamePayload(null, null, i), out _);
                }

                diagnosticSource2.WriteSafe("EventAbcName", new { Value = "Something", IterationNr = i }, out _);

                ConsoleWrite.LineLine($"-----------{i}-----------");
            }

            ConsoleWrite.Line("Finished to emit DiagnosticSource events.");

            ConsoleWrite.LineLine($"FINISHED DEMO '{nameof(UseDiagnosticSourceStub)}'.");
        }
        static void Main(string[] args)
        {
            var building = new Building();
            var input    = new ConsoleRead();
            var output   = new ConsoleWrite();

            Engine gameEngine = new Engine(building, input, output);

            gameEngine.Run();
        }
Exemple #16
0
        public void Write(string text)
        {
            var consoleWrite = new ConsoleWrite()
            {
                Text = text, NewLine = false
            };

            UserDataOutput = consoleWrite;
            Status         = EnumProcessStatus.WaitingForUserData;
            Hibernate();
        }
 public virtual T ReadUntilCorrect(T?min = null, T?max = null)
 {
     while (true)
     {
         try
         {
             return(Read(min, max));
         }
         catch (ConsoleInputException ciex)
         {
             ConsoleWrite.Error(ciex.Message);
         }
     }
 }
Exemple #18
0
        private async Task Plugin()
        {
            //const string DSAssemblyNameForPlugin = "System.Diagnostics.DiagnosticSource, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51";
            const string DSAssemblyFileForPlugin = "PluginRessource.System.Diagnostics.DiagnosticSource.dll";
            const int    RunningTimeMillis       = 500;

            string currentDirectory = Directory.GetCurrentDirectory();
            string assemblyPath     = Path.Combine(currentDirectory, DSAssemblyFileForPlugin);

            ConsoleWrite.LineLine($"Mock Plug-In: Loading assembly from \"{assemblyPath}\".");

            var      asmLoadCtx = new MockPluginAssemblyLoadContext();
            Assembly dsAsm      = asmLoadCtx.LoadFromAssemblyPath(assemblyPath);

            ConsoleWrite.Line($"Mock Plug-In: Assembly loaded ({dsAsm.FullName}) from \"{dsAsm.Location}\".");
            ConsoleWrite.Line($"Mock Plug-In: Doing mock work.");

            await Task.Delay(RunningTimeMillis);

            ConsoleWrite.LineLine($"Mock Plug-In: Mock work done. Unloading plugin and assemblies.");

            dsAsm = null;
            asmLoadCtx.Unload();

            var asmLoadCtxWeakRef = new WeakReference(asmLoadCtx);

            asmLoadCtx = null;

            int unloadWaitIterations = 0;

            while (asmLoadCtxWeakRef.IsAlive)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                unloadWaitIterations++;

                if (unloadWaitIterations % 100 == 0)
                {
                    ConsoleWrite.Line($"Plugin => Waiting To Unload => unloadIterations={unloadWaitIterations}.");
                }
                else if (unloadWaitIterations % 10 == 0)
                {
                    await Task.Delay(1);
                }
            }

            ConsoleWrite.LineLine($"Mock Plug-In: Plugin and assemblies unloaded. That's it.");
        }
Exemple #19
0
        private static AssemblyName GetAssemblyNameFromPath(string path)
        {
            if (String.IsNullOrWhiteSpace(path))
            {
                return(null);
            }

            try
            {
                return(AssemblyName.GetAssemblyName(path));
            }
            catch (Exception ex)
            {
                ConsoleWrite.Exception(ex);
                return(null);
            }
        }
Exemple #20
0
 public virtual T ReadUntilCorrect(Func <T> FunctionToRun, string message = "")
 {
     while (true)
     {
         try
         {
             return(FunctionToRun());
         }
         catch (ConsoleInputException)
         {
             if (!string.IsNullOrEmpty(message))
             {
                 ConsoleWrite.Error(message);
             }
         }
     }
 }
Exemple #21
0
        public static void Run()
        {
            // This demo shows how to use the stub APIs directly, without protecting against dynamic invocation exceptions.
            // The corresponding Net Core demo shows one of several possible ways for dealing with such exceptions.
            // Other demos show other approaches for dealing with these exceptions.

            ConsoleWrite.LineLine($"STARTING DEMO '{nameof(UseDiagnosticSourceStub)}'.");

            SetupListening();

            ConsoleWrite.LineLine("Starting to create new Diagnostic Sources.");

            DiagnosticSourceStub diagnosticSource1 = DiagnosticListening.CreateNewSource("DemoXxx.UseDiagnosticSource.Name1");
            DiagnosticSourceStub diagnosticSource2 = DiagnosticListening.CreateNewSource("DemoXxx.UseDiagnosticSource.Name2");

            ConsoleWrite.Line("Finished creating new Diagnostic Sources.");

            ConsoleWrite.LineLine("Starting to emit DiagnosticSource events.");
            for (int i = 0; i < 1000; i++)
            {
                if (diagnosticSource1.IsEnabled("EventXyzName.A"))
                {
                    diagnosticSource1.Write("EventXyzName", new EventXyzNamePayload("Foo", 42, i));
                }

                if (diagnosticSource1.IsEnabled("EventXyzName.B", arg1: "Something", arg2: 13.7))
                {
                    diagnosticSource1.Write("EventXyzName", new EventXyzNamePayload("Bar", new[] { 1, 2, 3 }, i));
                }

                if (diagnosticSource1.IsEnabled("EventXyzName.C", arg1: -1))
                {
                    diagnosticSource1.Write("EventXyzName", new EventXyzNamePayload(null, null, i));
                }

                diagnosticSource2.Write("EventAbcName", new { Value = "Something", IterationNr = i });

                ConsoleWrite.LineLine($"-----------{i}-----------");
            }

            ConsoleWrite.Line("Finished to emit DiagnosticSource events.");

            ConsoleWrite.LineLine($"FINISHED DEMO '{nameof(UseDiagnosticSourceStub)}'.");
        }
Exemple #22
0
 public void InsertTemperature(DateTime time, double temperature)
 {
     try
     {
         using (MySqlConnection db = new MySqlConnection(CONNECTION_STRING))
         {
             db.Open();
             MySqlCommand cmd = new MySqlCommand(@"INSERT INTO `Temperatures` (`Time`, `Temperature`) 
                 VALUES (@time, @temp)", db);
             cmd.Parameters.AddWithValue("@time", time);
             cmd.Parameters.AddWithValue("@temp", temperature);
             int rows = cmd.ExecuteNonQuery();
         }
     }
     catch (Exception e)
     {
         ConsoleWrite.Red("Error while inserting test data. Error: " + e.Message);
     }
 }
Exemple #23
0
        public void Run()
        {
            ConsoleRead  consoleRead  = new ConsoleRead();
            ConsoleWrite consoleWrite = new ConsoleWrite();
            CreateBlobs  createBlob   = new CreateBlobs();
            Attacking    attacking    = new Attacking();
            Data         data         = new Data();

            string input = "";

            while (input != "drop")
            {
                input = consoleRead.Read();

                string[] commant = input.Split();

                if (commant[0] == "create")
                {
                    string name     = commant[1];
                    int    health   = Int32.Parse(commant[2]);
                    int    damage   = Int32.Parse(commant[3]);
                    string behavior = commant[4];
                    string attack   = commant[5];

                    data.AddBlob(createBlob.Create(name, health, damage, behavior, attack));
                }
                else if (commant[0] == "attack")
                {
                    attacking.Attack(data.Blobs, commant[1], commant[2]);
                }
                else if (commant[0] == "status")
                {
                    consoleWrite.WriteList(data.Blobs);
                }
                else if (commant[0] == "pass")
                {
                }
                else if (commant[0] == "drop")
                {
                    Environment.Exit(0);
                }
            }
        }
Exemple #24
0
 static void InitUi(int x, int y)
 {
     Console.CursorVisible = false;
     ConsoleSize.SetWindowSize(x + 2, y + 7);
     Console.SetCursorPosition(0, 0);
     ConsoleWrite.WriteRowOf('#');
     for (int i = 0; i < y; i++)
     {
         Console.Write("#");
         for (int j = 0; j < x; j++)
         {
             Console.Write(" ");
         }
         Console.Write("#");
     }
     ConsoleWrite.WriteRowOf('#');
     ConsoleWrite.WriteCentered("Snake");
     ShowScore(y, 0);
 }
Exemple #25
0
        private Assembly AssemblyResolveEventHandler(object sender, ResolveEventArgs args)
        {
            if (!GetPhaseOneCompleted())
            {
                ConsoleWrite.Line($"AssemblyResolveEventHandler: Phase One not completed => doing nothing.");
                return(null);
            }

            string asmNameRequestedStr = args?.Name;

            if (asmNameRequestedStr == null)
            {
                ConsoleWrite.Line($"AssemblyResolveEventHandler: No good arguments => doing nothing.");
                return(null);
            }

            string       dsAsmFilePath = Path.Combine(DiagnosticSourceAssemblyHiddenPath, DiagnosticSourceAssemblyFilename);
            AssemblyName asmNameAtPath = GetAssemblyNameFromPath(dsAsmFilePath);

            if (asmNameAtPath == null)
            {
                ConsoleWrite.Line($"AssemblyResolveEventHandler: Cannot extract assembly name from \"{dsAsmFilePath}\". Doing nothing.");
                return(null);
            }
            else
            {
                AssemblyName asmNameRequested = new AssemblyName(asmNameRequestedStr);
                if (AreEqual(asmNameAtPath, asmNameRequested))
                {
                    ConsoleWrite.Line($"AssemblyResolveEventHandler: Match. Loading DS from special location.");
                    return(Assembly.Load(asmNameAtPath));
                }
                else
                {
                    ConsoleWrite.Line($"AssemblyResolveEventHandler: No Match. Doing nothing.");
                    ConsoleWrite.Line($"    Requested assembly: \"{asmNameRequested.FullName}\";");
                    ConsoleWrite.Line($"    Present assembly:   \"{asmNameAtPath.FullName}\".");
                    return(null);
                }
            }
        }
        private static void SetupListening()
        {
            ConsoleWrite.LineLine("Starting setting up DiagnosticSource listening.");

            if (!DiagnosticSourceSafeExtensions.SubscribeToAllSourcesSafe(ObserverAdapter.OnNextHandler(
                                                                              (DiagnosticListenerStub diagnosticListener) =>
            {
                diagnosticListener.GetNameSafe(out string diagnosticListenerName, out _);
                ConsoleWrite.Line($"Subscriber called: diagnosticSourceObserver(diagnosticListener.Name: \"{diagnosticListenerName}\")");

                if (diagnosticListenerName.Equals("DemoXxx.UseDiagnosticSource.Name1", StringComparison.Ordinal))
                {
                    if (!diagnosticListener.SubscribeToEventsSafe(
                            ObserverAdapter.OnNextHandler((KeyValuePair <string, object> eventInfo) =>
                    {
                        ConsoleWrite.Line($"Event Handler called: eventObserver(eventName: \"{eventInfo.Key}\", payloadValue: {(eventInfo.Value ?? "<null>")})");
                    }),
                            (string eventName, object arg1, object arg2) =>
                    {
                        Validate.NotNull(eventName, nameof(eventName));
                        bool res = eventName.StartsWith("EventXyzName", StringComparison.OrdinalIgnoreCase) &&
                                   (arg1 == null || !(arg1 is Int32 arg1Val) || arg1Val >= 0);
                        ConsoleWrite.Line($"Filter called: isEventEnabledFilter(eventName: \"{eventName}\", arg1: {(arg1 ?? "<null>")}, arg2: {(arg2 ?? "<null>")})."
                                          + $" Returning: {res}.");
                        return(res);
                    },
                            out IDisposable eventSubscription,
                            out _))
                    {
                        ConsoleWrite.LineLine("Could not set up an events subscription. Likely no events will be received. Error has been logged.");
                    }
                }
            }),
                                                                          out IDisposable listenerSubscription,
                                                                          out _))
            {
                ConsoleWrite.LineLine("Could not set up an all-sources-subscription. Likely no events will be received. Error has been logged.");
            }

            ConsoleWrite.Line("Finished setting up DiagnosticSource listening.");
        }
        public static void Run()
        {
            ConsoleWrite.LineLine($"STARTING DEMO '{nameof(UseDiagnosticSource)}'.");

            SetupListening();

            ConsoleWrite.LineLine("Starting to create new Diagnostic Sources.");

            DiagnosticSource diagnosticSource1 = new DiagnosticListener("DemoXxx.UseDiagnosticSource.Name1");
            DiagnosticSource diagnosticSource2 = new DiagnosticListener("DemoXxx.UseDiagnosticSource.Name2");

            ConsoleWrite.Line("Finished creating new Diagnostic Sources.");

            ConsoleWrite.LineLine("Starting to emit DiagnosticSource events.");
            for (int i = 0; i < 1000; i++)
            {
                if (diagnosticSource1.IsEnabled("EventXyzName.A"))
                {
                    diagnosticSource1.Write("EventXyzName", new EventXyzNamePayload("Foo", 42, i));
                }

                if (diagnosticSource1.IsEnabled("EventXyzName.B", arg1: "Something", arg2: 13.7))
                {
                    diagnosticSource1.Write("EventXyzName", new EventXyzNamePayload("Bar", new[] { 1, 2, 3 }, i));
                }

                if (diagnosticSource1.IsEnabled("EventXyzName.C", arg1: -1))
                {
                    diagnosticSource1.Write("EventXyzName", new EventXyzNamePayload(null, null, i));
                }

                diagnosticSource2.Write("EventAbcName", new { Value = "Something", IterationNr = i });

                ConsoleWrite.LineLine($"-----------{i}-----------");
            }

            ConsoleWrite.Line("Finished to emit DiagnosticSource events.");

            ConsoleWrite.LineLine($"FINISHED DEMO '{nameof(UseDiagnosticSource)}'.");
        }
Exemple #28
0
        public static async Task ConnectionPessoa()
        {
            var connectionString = Configuration.GetConnectionString("DefaultConnection");

            using (var db = new SessionHelper(connectionString))
            {
                var pessoaFisica = new PessoaFisica();
                await db.Session.SaveOrUpdateAsync(pessoaFisica.New());

                var pessoaJuridica = new PessoaJuridica();
                await db.Session.SaveOrUpdateAsync(pessoaJuridica.New());

                await db.Session.FlushAsync();

                var pessoas = db.Session.Query <Pessoa>().Count();
                ConsoleWrite.Color($"Quantidade de entidades do tipo Pessoa: {pessoas}", ConsoleColor.Green);

                var pessoasFisicas = db.Session.Query <PessoaFisica>().Count();
                ConsoleWrite.Color($"Quantidade de entidades do tipo PessoaFisica: {pessoasFisicas}", ConsoleColor.Green);

                var pessoasJuridicas = db.Session.Query <PessoaJuridica>().Count();
                ConsoleWrite.Color($"Quantidade de entidades do tipo PessoaJuridica: {pessoasJuridicas}", ConsoleColor.Green);
            }
        }
Exemple #29
0
        static async Task Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            ConsoleWrite.Color("======================================================================================================", ConsoleColor.Yellow);
            ConsoleWrite.Color("Configurando Nhibernate com FluentNHibernate, Teste de Mapeamento do FluentNhibernate e FluentMigrator", ConsoleColor.Yellow);
            ConsoleWrite.Color("======================================================================================================", ConsoleColor.Yellow);

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            Configuration = builder.Build();

            CreateDatabase();
            var serviceProvider = CreateServices();

            using (var scope = serviceProvider.CreateScope())
            {
                UpdateDatabase(scope.ServiceProvider);
            }

            await ConnectionPessoa();
            await ConnectionAnimal();
        }
Exemple #30
0
        public static async Task ConnectionAnimal()
        {
            var connectionString = Configuration.GetConnectionString("DefaultConnection");

            using (var db = new SessionHelper(connectionString))
            {
                var cachorro = new Cachorro();
                await db.Session.SaveOrUpdateAsync(cachorro.New());

                var papagaio = new Papagaio();
                await db.Session.SaveOrUpdateAsync(papagaio.New());

                await db.Session.FlushAsync();

                var animais = db.Session.Query <Animal>().Count();
                ConsoleWrite.Color($"Quantidade de entidades do tipo Animal: {animais}", ConsoleColor.Green);

                var cachorros = db.Session.Query <Cachorro>().Count();
                ConsoleWrite.Color($"Quantidade de entidades do tipo Cachorros: {cachorros}", ConsoleColor.Green);

                var papagaios = db.Session.Query <Papagaio>().Count();
                ConsoleWrite.Color($"Quantidade de entidades do tipo Papagaios: {papagaios}", ConsoleColor.Green);
            }
        }