Пример #1
0
        public async Task RefereshToken_When_Refresh_Token_Is_Valid()
        {
            var assertDatabase = await RfidDatabaseAssert.CreateAsync();

            var requestModel = Examples.Administrator();

            await RfidHttpClient.RegisterUserAsync(requestModel);

            using (var genResponse = await RfidHttpClient.GenerateAuthTokenAsync(requestModel.Email, requestModel.Password))
            {
                var jtoken = await genResponse.Content.AsJObjectAsync();

                using (var refreshResponse = await RfidHttpClient.RefreshAuthTokenAsync(jtoken.Token(), jtoken.RefreshToken()))
                {
                    await AssertAuthTokenResponseAsync(refreshResponse, System.Net.HttpStatusCode.OK);

                    var rtoken = await refreshResponse.Content.AsJObjectAsync();

                    Assert.NotEqual(expected: jtoken.Token(), actual: rtoken.Token());
                    Assert.NotEqual(expected: jtoken.RefreshToken(), actual: rtoken.RefreshToken());
                }
            }

            await assertDatabase.AssertCntAsync(requestModel);
        }
Пример #2
0
        public void Export_AllExamplesInExampleLibrary_CheckThatAllFilesExist()
        {
            const string DestinationDirectory = "PdfExporterTests_ExampleLibrary";

            if (!Directory.Exists(DestinationDirectory))
            {
                Directory.CreateDirectory(DestinationDirectory);
            }

            // A4
            const double Width  = 297 / 25.4 * 72;
            const double Height = 210 / 25.4 * 72;

            foreach (var example in Examples.GetList())
            {
                if (example.PlotModel == null)
                {
                    continue;
                }

                var path = Path.Combine(DestinationDirectory, FileNameUtilities.CreateValidFileName(example.Category + " - " + example.Title, ".pdf"));
                using (var s = File.Create(path))
                {
                    PdfExporter.Export(example.PlotModel, s, Width, Height);
                }

                Assert.IsTrue(File.Exists(path));
            }
        }
Пример #3
0
        public async Task DeActivate_When_Tag_Active()
        {
            var assertDatabase = await RfidDatabaseAssert.CreateAsync();

            var userRM = Examples.Administrator();
            var tagRM  = Examples.Tag();

            await RfidHttpClient.RegisterUserAsync(userRM);

            using (var authHttpResponse = await RfidHttpClient.GenerateAuthTokenAsync(userRM))
            {
                var authToken = await AuthTokenHelper.FromHttpResponseMessageAsync(authHttpResponse);

                var token = await authToken.GetTokenAsync();

                using (var registerTagHttpResponse = await RfidHttpClient.RegisterTagAsync(tagRM, token))
                {
                    RfidAssert.AssertHttpResponse(registerTagHttpResponse, System.Net.HttpStatusCode.OK);

                    using (var activateHttpResponse = await RfidHttpClient.DeActivateTagAsync(tagRM.Number, token))
                    {
                        RfidAssert.AssertHttpResponse(activateHttpResponse, System.Net.HttpStatusCode.OK);
                    }
                }
            }

            var tagId = await RfidDatabase.GetTagIdByNumberAsync(tagRM.Number);

            await assertDatabase.AssertCntAsync(userRM, tagRM);

            await assertDatabase.AssertStateAsync("access_control.Tags", tagId, new { Id = tagId, IsActive = false });
        }
Пример #4
0
        /// <summary>Indicates whether the current object is equal to another object of the same type.</summary>
        /// <param name="other">An object to compare with this object.</param>
        /// <returns>true if the current object is equal to the <paramref name="other">other</paramref> parameter; otherwise, false.</returns>
        public virtual bool Equals(MediaType other)
        {
            if (other is null)
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            if (!Schema.Equals(other.Schema))
            {
                return(false);
            }
            if (!Examples.NullableDictionaryEquals(other.Examples))
            {
                return(false);
            }
            if (!Encoding.NullableDictionaryEquals(other.Encoding))
            {
                return(false);
            }

            return(true);
        }
Пример #5
0
        public void AddExample(Example example)
        {
            example.Context = this;
            Examples.Add(example);

            example.Pending |= example.Context.IsPending();
        }
Пример #6
0
        /// <summary>
        /// Gets structured content
        /// </summary>
        public DataTree <string> Get()
        {
            DataTree <string> result = new DataTree <string>($"Documentation for {Name}: {Description}");

            if (Examples.Count == 1)
            {
                result.Add($"Example: {Examples[0]}");
            }
            if (Examples.Count > 1)
            {
                DataTree <string> example = new DataTree <string>("Examples:");
                Examples.ForEach(x => example.Add(x));
                result.Add(example);
            }
            if (!Default.IsNullOrWhiteSpace())
            {
                result.Add($"Default: {Default}");
            }
            if (!PossibleValues.IsNullOrWhiteSpace())
            {
                result.Add($"PossibleValues: {PossibleValues}");
            }
            if (!Remark.IsNullOrWhiteSpace())
            {
                result.Add($"Remarks: {Remark}");
            }

            return(result);
        }
Пример #7
0
 static void Main(string[] args)
 {
     var examples = new Examples();
     examples.Sequantial();
     examples.WithFutures();
     examples.WithContinuation();
 }
Пример #8
0
 public void ExampleLoadTextFileShouldThrowException()
 {
     Assert.Throws <System.IO.FileNotFoundException>(() =>
     {
         Examples.ExampleLoadTextFile("");
     });
 }
Пример #9
0
        public void Export_AllExamplesInExampleLibrary_CheckThatAllFilesExist()
        {
            const string DestinationDirectory = "SvgExporterTests_ExampleLibrary";

            if (!Directory.Exists(DestinationDirectory))
            {
                Directory.CreateDirectory(DestinationDirectory);
            }

            foreach (var example in Examples.GetList())
            {
                void ExportModelAndCheckFileExists(PlotModel model, string fileName)
                {
                    if (model == null)
                    {
                        return;
                    }

                    var path = Path.Combine(DestinationDirectory, FileNameUtilities.CreateValidFileName(fileName, ".svg"));

                    using (var s = File.Create(path))
                    {
                        SvgExporter.Export(model, s, 800, 500, true);
                    }

                    Assert.IsTrue(File.Exists(path));
                }

                ExportModelAndCheckFileExists(example.PlotModel, $"{example.Category} - {example.Title}");
                ExportModelAndCheckFileExists(example.TransposedPlotModel, $"{example.Category} - {example.Title} - Transposed");
            }
        }
Пример #10
0
        /// <summary>Prints a help message describing the effects of all available options.</summary>
        /// <param name="errorMessage">Optional error message to display.</param>
        public void PrintHelp(string errorMessage = null)
        {
            string argList = string.Join(" ", Arguments.OrderBy(k => k.Key).Select(a => ArgumentToArgList(a.Key, a.Value)));

            OutputWriter.WriteLine(ApplicationInfo);
            OutputWriter.WriteLine();
            if (!string.IsNullOrWhiteSpace(errorMessage))
            {
                OutputWriter.WriteLine(errorMessage);
                OutputWriter.WriteLine();
            }
            OutputWriter.WriteLine("Usage:");
            OutputWriter.WriteLine("{0} {1}", ExecutableName, argList);

            foreach (var kvp in Arguments.OrderBy(k => k.Key))
            {
                OutputWriter.WriteLine();
                OutputWriter.WriteLine("{0,-10}{1}", kvp.Key, kvp.Value.HelpMessage);
                OutputWriter.WriteLine("{0,-10}{1}", "", GetArgumentInfo(kvp.Value));
            }

            if (Examples.Any())
            {
                OutputWriter.WriteLine();
                OutputWriter.WriteLine("Examples:");

                foreach (var kvp in Examples.OrderBy(k => k.Key))
                {
                    OutputWriter.WriteLine();
                    OutputWriter.WriteLine(kvp.Key);
                    OutputWriter.WriteLine(kvp.Value);
                }
            }
        }
Пример #11
0
        public void Export_AllExamplesInExampleLibrary_CheckThatAllFilesExist()
        {
            var destinationDirectory = Path.Combine(TestContext.CurrentContext.WorkDirectory, "PdfExporterTests_ExampleLibrary");

            if (!Directory.Exists(destinationDirectory))
            {
                Directory.CreateDirectory(destinationDirectory);
            }

            // A4
            const double Width  = 297 / 25.4 * 72;
            const double Height = 210 / 25.4 * 72;

            foreach (var example in Examples.GetList())
            {
                void ExportModelAndCheckFileExists(PlotModel model, string fileName)
                {
                    if (model == null)
                    {
                        return;
                    }

                    var path = Path.Combine(destinationDirectory, FileNameUtilities.CreateValidFileName(fileName, ".pdf"));

                    using (var s = File.Create(path))
                    {
                        PdfExporter.Export(model, s, Width, Height);
                    }

                    Assert.IsTrue(File.Exists(path));
                }

                ExportModelAndCheckFileExists(example.PlotModel, $"{example.Category} - {example.Title}");
            }
        }
Пример #12
0
        public void Export_AllExamplesInExampleLibrary_CheckThatAllFilesExist()
        {
            const string DestinationDirectory = "SvgExporterTests_ExampleLibrary";

            if (!Directory.Exists(DestinationDirectory))
            {
                Directory.CreateDirectory(DestinationDirectory);
            }

            foreach (var example in Examples.GetList())
            {
                if (example.PlotModel == null)
                {
                    continue;
                }

                var path = Path.Combine(DestinationDirectory, FileNameUtilities.CreateValidFileName(example.Category + " - " + example.Title, ".svg"));
                using (var s = File.Create(path))
                {
                    SvgExporter.Export(example.PlotModel, s, 800, 500, true);
                }

                Assert.IsTrue(File.Exists(path));
            }
        }
Пример #13
0
        protected override async Task OnInitializedAsync()
        {
            lexer       = new PascalLexer(this);
            ast         = new PascalAst(this);
            analyzer    = new PascalSemanticAnalyzer(this);
            csharp      = new PascalToCSharp();
            con         = new ConsoleModel();
            interpreter = new PascalInterpreter(console: con);
            Examples.Add("Hello World", @"program hello;
begin
    writeln('hello world!');
end.");

            Examples.Add("Simple Program", @"program test;
begin
end.");
            Examples.Add("Math", @"program math;
var a,b,c : integer;
begin
    a := 10;
    b := 20;
    c := 30;
    writeln(a + c - b);
end.");
            //Compile();
            base.OnInitialized();
        }
Пример #14
0
 public bool Equals(NBehaveExampleParentTask task)
 {
     return(task != null &&
            FeatureFile == task.FeatureFile &&
            Scenario == task.Scenario &&
            Examples.AsString() == task.Examples.AsString());
 }
Пример #15
0
        void importExamples(PSObject example)
        {
            List <PSObject> examples = new List <PSObject>();

            if (example.Members["example"].Value as PSObject == null)
            {
                examples = new List <PSObject>((PSObject[])example.Members["example"].Value);
            }
            else
            {
                examples.Add((PSObject)example.Members["example"].Value);
            }
            foreach (PSObject ex in examples)
            {
                String title       = ((String)((PSObject)ex.Members["title"].Value).BaseObject).Replace("-", String.Empty).Trim();
                String code        = (String)((PSObject)ex.Members["code"].Value).BaseObject;
                String description = ((PSObject[])ex.Members["remarks"].Value)
                                     .Aggregate(String.Empty, (current, paragraph) => current + (paragraph.Members["Text"].Value + Environment.NewLine));
                Examples.Add(new Example {
                    Name        = title,
                    Cmd         = code,
                    Description = description
                });
            }
        }
Пример #16
0
        public void TrimSkippedDescendants()
        {
            Contexts.RemoveAll(c => !c.HasAnyExecutedExample());

            Examples.RemoveAll(e => !e.HasRun);

            Contexts.Do(c => c.TrimSkippedDescendants());
        }
Пример #17
0
 public void Update_AllExamples_ThrowsNoExceptions()
 {
     foreach (var example in Examples.GetList())
     {
         ((IPlotModel)example.PlotModel)?.Update(true);
         ((IPlotModel)example.TransposedPlotModel)?.Update(true);
     }
 }
Пример #18
0
 public void Test_All_Methods_Against_String_with_no_spaces()
 {
     Assert.AreEqual("test", Examples.RemoveSpacesCustomReplace(_nospacesstring), "Method failed on no space string");
     Assert.AreEqual("test", Examples.RemoveSpacesLinq(_nospacesstring), "Method failed on no space string");
     Assert.AreEqual("test", Examples.RemoveSpacesStringbuilderForeach(_nospacesstring), "Method failed on no space string");
     Assert.AreEqual("test", Examples.RemoveSpacesStringBuilder(_nospacesstring), "Method failed on no space string");
     Assert.AreEqual("test", Examples.RemoveSpaces(_nospacesstring), "Method failed on no space string");
 }
Пример #19
0
        public void AddExample(ExampleBase example)
        {
            example.AddTo(this);

            Examples.Add(example);

            runnables.Add(new RunnableExample(this, example));
        }
Пример #20
0
        bool AnyUnfilteredExampleInSubTree(nspec nspec)
        {
            Func <ExampleBase, bool> shouldNotSkip = e => e.ShouldNotSkip(nspec.tagsFilter);

            bool anyExampleOrSubExample = Examples.Any(shouldNotSkip) || Contexts.Examples().Any(shouldNotSkip);

            return(anyExampleOrSubExample);
        }
        // Methods ----------------

        /// <summary>
        /// Prints this entity in the console
        /// </summary>
        public void Print()
        {
            Console.WriteLine(Definition);
            foreach (var example in Examples.Union(Quotes))
            {
                Console.WriteLine("--> " + example);
            }
        }
Пример #22
0
 public void Test_All_Methods_Against_null_string()
 {
     Assert.AreEqual(null, Examples.RemoveSpacesCustomReplace(_nullstring), "Method failed on null string");
     Assert.AreEqual(null, Examples.RemoveSpacesLinq(_nullstring), "Method failed on null string");
     Assert.AreEqual(null, Examples.RemoveSpacesStringbuilderForeach(_nullstring), "Method failed on null string");
     Assert.AreEqual(null, Examples.RemoveSpacesStringBuilder(_nullstring), "Method failed on null string");
     Assert.AreEqual(null, Examples.RemoveSpaces(_nullstring), "Method failed on null string");
 }
        private ScenarioOutline PatchScenario(string tagString, Scenario scenario)
        {
            var tokens                  = tagString.Split('=');
            var propertyName            = tokens[0];
            var propertyValueExpression = tokens[1];

            var propertyValueTokens = propertyValueExpression.Split('.');

            var testValues = _testDataProvider.TestData;

            foreach (var propertyValueToken in propertyValueTokens)
            {
                var dict = testValues as Dictionary <string, object>;
                if (dict == null)
                {
                    throw new InvalidOperationException($"Cannot resolve properties from {testValues}");
                }

                if (!dict.TryGetValue(propertyValueToken, out testValues) &&
                    !dict.TryGetValue(propertyValueToken.Replace("_", " "), out testValues))
                {
                    throw new InvalidOperationException($"Cannot resolve property {propertyValueToken}");
                }
            }

            var examples = new List <Examples>(scenario.Examples);

            var header = new TableRow(scenario.Location, new TableCell[]
            {
                new TableCell(scenario.Location, "Variant"),
                new TableCell(scenario.Location, propertyName)
            });

            var testValuesDict = testValues as Dictionary <string, object>;

            var rows = testValuesDict
                       .Select(p => new TableRow(scenario.Location, new[]
            {
                new TableCell(scenario.Location, p.Key),
                new TableCell(scenario.Location, p.Value.ToString()),
            })).ToArray();


            var newExample = new Examples(new Tag[0], scenario.Location, "Examples", string.Empty, string.Empty, header, rows);

            examples.Add(newExample);


            var newScenarioOutline = new ScenarioOutline(scenario.Tags.ToArray(),
                                                         scenario.Location,
                                                         scenario.Keyword,
                                                         scenario.Name,
                                                         scenario.Description,
                                                         scenario.Steps.ToArray(),
                                                         examples.ToArray());

            return(newScenarioOutline);
        }
Пример #24
0
        public void Read(string fileName)
        {
            StreamReader  reader      = File.OpenText(fileName);
            StringBuilder str         = new StringBuilder();
            string        category    = "";
            string        name        = "";
            string        description = "";
            string        message     = "";
            int           pos         = 0;

            try
            {
                while (reader.EndOfStream == false)
                {
                    string line = reader.ReadLine().Trim();
                    pos++;
                    if (line.StartsWith("@"))
                    {
                        message = str.ToString().Trim();
                        if (category != "" && message != "")
                        {
                            Examples.AddExamplesRow(category, name, message, description);
                            str = new StringBuilder();
                        }
                        line        = line.Remove(0, 1);
                        category    = "";
                        name        = "";
                        description = "";
                        string[] values = line.Split(',');
                        if (values.Length > 0)
                        {
                            category = values[0].Trim();
                        }
                        if (values.Length > 1)
                        {
                            name = values[1].Trim();
                        }
                        if (values.Length > 2)
                        {
                            description = values[2].Trim();
                        }
                    }
                    else if (line.StartsWith(";") == false) // komentarz
                    {
                        str.AppendLine(line);
                    }
                }
                if (category != "" && message != "")
                {
                    Examples.AddExamplesRow(category, name, message, description);
                    str = new StringBuilder();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format(Messages.ErrorAtLine, pos) + " " + ex.Message);
            }
        }
Пример #25
0
        static void Main(string[] args)
        {
            Colorful.Console.WriteLine("------------------------------------------");
            Colorful.Console.WriteLine("               Retry Example              ");
            Colorful.Console.WriteLine("------------------------------------------");

            Examples.RetryPolicyExample();

            Colorful.Console.WriteLine("------------------------------------------");
            Colorful.Console.WriteLine("         Retry and Wait Example           ");
            Colorful.Console.WriteLine("------------------------------------------");


            Examples.RetryAndWaitPolicyExample();

            Colorful.Console.WriteLine("------------------------------------------");
            Colorful.Console.WriteLine("             Fallback Example             ");
            Colorful.Console.WriteLine("------------------------------------------");

            Examples.FallbackPolicyExample();

            Colorful.Console.WriteLine("------------------------------------------");
            Colorful.Console.WriteLine("             Policy Wrap Example          ");
            Colorful.Console.WriteLine("------------------------------------------");


            Examples.WrapPoliciesExample();

            Colorful.Console.WriteLine("------------------------------------------");
            Colorful.Console.WriteLine("          Circuit Breaker Example          ");
            Colorful.Console.WriteLine("------------------------------------------");

            for (var i = 0; i < 3; i++)
            {
                Examples.CircuitBreakerExample();
            }

            Colorful.Console.WriteLine("Waiting some seconds until the circuit is opened again...", Color.Aqua);
            Thread.Sleep(20000);

            Colorful.Console.WriteLine("Retrying... circuit should be open now.", Color.Aqua);
            Examples.CircuitBreakerExample(false);

            Colorful.Console.WriteLine("------------------------------------------");
            Colorful.Console.WriteLine("               Cache Example             ");
            Colorful.Console.WriteLine("------------------------------------------");

            for (var i = 0; i < 3; i++)
            {
                Examples.CacheExample();
            }

            Colorful.Console.WriteLine("Waiting some seconds until the cache expires", Color.Aqua);
            Thread.Sleep(20000);

            Colorful.Console.WriteLine("Retrying... cache should be expired now.", Color.Aqua);
            Examples.CacheExample();
        }
Пример #26
0
        private async void button3_Click(object sender, EventArgs e)
        {
            ExPanel.Hide();
            Examples.Hide();
            GraphEditorPanel.Hide();
            meniu1.Hide();

            Sidebar.Show();
        }
Пример #27
0
 public DefaultSearchBlockViewModel(DefaultSearchCriteria defaultSearchCriteria, ISearchHistory history, Action <SearchSuggestionViewModel> applySuggestionAction)
     : base(defaultSearchCriteria, applySuggestionAction)
 {
     _history = history;
     foreach (var(keyword, exampleTerm) in defaultSearchCriteria.ExamplesFromEachSubCriteria())
     {
         Examples.Add(new SearchBlockExampleViewModel($" {keyword}: ", exampleTerm));
     }
 }
Пример #28
0
        public void NewExamples(Examples examples)
        {
            BDDScenarioOutlineBuilder scenarioOutlineBuilder = CurrentScenarioBuilder as BDDScenarioOutlineBuilder;

            if (scenarioOutlineBuilder != null)
            {
                scenarioOutlineBuilder.AddExamples(examples);
            }
        }
Пример #29
0
 public MainViewModel()
 {
     this.Models       = Examples.GetPropertyGridExamples().ToList();
     this.SelectedItem = this.Models.FirstOrDefault(o => o.GetType() == typeof(SimpleTypesExample));
     foreach (Example m in this.Models)
     {
         m.PropertyChanged += this.TestChanged;
     }
 }
Пример #30
0
 private void button2_Click(object sender, EventArgs e)
 {
     ExPanel.Hide();
     GraphEditorPanel.Hide();
     meniu1.Hide();
     Examples.Show();
     Examples.BringToFront();
     Sidebar.Show();
 }
Пример #31
0
        public void ExampleLoadTextFile_ValidNameShouldWork()
        {
            //Arrange and Act in the same statement
            string actual = Examples.ExampleLoadTextFile("This is a valid file name.");


            //Assert
            Assert.True(actual.Length > 0);
        }
Пример #32
0
    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }

        if (Application.loadedLevelName == "_Examples" && Application.levelCount > 1)
        {
            loadNextLevel();
            Destroy(GetComponent<Example>());
        }
    }
Пример #33
0
        public void TestMethod1()
        {
            //quite las // para que pueda ir viendo los ejemplos en ejecucion.
            Examples example = new Examples();
            //example.TaskUsage();//como el metodo Task pide ayuda de otro thread , se demuestra en el output el trabajo alternado entre dos threads.

            //example.TaskReturningValue();//es un Task<string>, se crea un nuevo hilo que va a cierto metodo y cuando lo termina retorna un resultado, en este caso, de tipo string.
            //example.TaskReturningValueStatus();//retorna cuando esta ha sido created, cuando is running y RanToCompletion.
            //example.NotificationsContinueWith();//encadena tasks. invica cual va a continuar despues de un task padre y bajo que condiciones.
            //example.ExeptionHandling();//manejo con try catch y explicacion de bubbling.
            //example.ExeptionHandlingContinueWith();//manejo de exepcion con continue.
            //example.CancellingTask();//cancelacion de un thread a travez de un Token.
            //example.LongRunningTask();//un parametro que se puede pasar para indicarle que la tarea se va a tardar y que considere si se crea un thread o se saca del pool, lo que se evalue pertinente.
            //example.ParallelIterations();//utiliza varios threads para ejecutar un loop, pero hay riesgo de hacer un race condition.,ademas, puede ser que unos hilos terminen primero que otros.
            //example.ParallelIterationsExceptions();//como cachar una exepcion en parallel.
            //example.ParallelLoopCancelation();//una variable va afuera y envia un mensaje de cancelacion a otra variable que va dentro del parallel loop , estas dos variables se comunican y entonces se cancela el loop.
            example.ParallelOptions();//se le puede poner un break al loop y tambien otra opcion es indicarle con cuantos hilos de ejecucion se va ayudar el loop.
        }
Пример #34
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Examples examples = new Examples();

        examples.ConnectionString = ConfigurationManager.ConnectionStrings["ODDB"].ConnectionString;
        examples.NetworkCode = ConfigurationManager.AppSettings["network"];
        examples.VocabularyCode = ConfigurationManager.AppSettings["vocabulary"];

        List<String> sites = examples.GetSites();
        GetSites.DataSource = sites;
        GetSites.DataBind();

        List<String> siteInfos = examples.GetSiteInfo();
        GetSiteInfo.DataSource = siteInfos;
        GetSiteInfo.DataBind();

        GetVariableInfo.DataSource = examples.GetVariableSimple();
        GetVariableInfo.DataBind();

        GetVariableInfoDetailed.DataSource = examples.GetVariableDetailed();
        GetVariableInfoDetailed.DataBind();
    }
Пример #35
0
 static void Main()
 {
     var examples = new Examples();
     examples.RunPipeline();
 }