public void ShouldBePreserved()
        {
            var source = new TestSource
            {
                Foo = "Foobar",
                Bar = 32,
                Child = new TestEmbedded
                {
                    Blah = "o hai",
                    Qux = 64
                }
            };

            var compiled = new ConfigurationBuilder()
                .AddObject(source)
                .Build();

            var dest = new TestTarget();
            compiled.Bind(dest);

            dest.Foo.Should().Be("Foobar");
            dest.Bar.Should().Be(32);
            dest.Child.Blah.Should().Be("o hai");
            dest.Child.Qux.Should().Be(64);
        }
Exemple #2
0
        /// <summary>
        /// Configure and run the KickStart extensions.
        /// </summary>
        /// <param name="configurator">The <see langword="delegate"/> to configure KickStart before execution of the extensions.</param>
        /// <example>Configure KickStart to use startup tasks using Autofac container to resolve <see cref="T:KickStart.StartupTask.IStartupTask" /> instances.
        /// <code><![CDATA[
        /// Kick.Start(config => config
        ///     .IncludeAssemblyFor<TestStartup>()
        ///     .UseAutofac()
        ///     .UseStartupTask(c => c.UseContainer())
        ///     .LogLevel(TraceLevel.Verbose)
        /// );]]></code>
        /// </example>
        public static void Start(Action<IConfigurationBuilder> configurator)
        {
            var config = new Configuration();
            var builder = new ConfigurationBuilder(config);

            configurator(builder);

            var assemblies = config.Assemblies.Resolve();
            var context = new Context(assemblies);

            foreach (var starter in config.Starters)
            {
                Logger.Trace()
                    .Logger(typeof(Kick).FullName)
                    .Message("Execute Starter: {0}", starter)
                    .Write();

                Stopwatch watch = Stopwatch.StartNew();

                starter.Run(context);

                watch.Stop();

                Logger.Trace()
                    .Logger(typeof(Kick).FullName)
                    .Message("Completed Starter: {0}, Time: {1} ms", starter, watch.ElapsedMilliseconds)
                    .Write();
            }
        }
        public void NewConfigurationProviderOverridesOldOneWhenKeyIsDuplicated()
        {
            // Arrange
            var dic1 = new Dictionary<string, string>()
                {
                    {"Key1:Key2", "ValueInMem1"}
                };
            var dic2 = new Dictionary<string, string>()
                {
                    {"Key1:Key2", "ValueInMem2"}
                };
            var memConfigSrc1 = new MemoryConfigurationProvider(dic1);
            var memConfigSrc2 = new MemoryConfigurationProvider(dic2);

            var configurationBuilder = new ConfigurationBuilder();

            // Act
            configurationBuilder.Add(memConfigSrc1, load: false);
            configurationBuilder.Add(memConfigSrc2, load: false);

            var config = configurationBuilder.Build();

            // Assert
            Assert.Equal("ValueInMem2", config["Key1:Key2"]);
        }
        public void CanReAddMetaConfigurationSectionAfterChangeIsCanceled()
        {
            ConfigurationSettings existingSettings = null;
            using (ConfigurationBuilder originalConfigReader = new ConfigurationBuilder(configFile))
            {
                existingSettings = originalConfigReader.ReadMetaConfiguration();
            }

            try
            {
                builder.ConfigurationChanging += new ConfigurationChangingEventHandler(CancelingHandler);
                builder.ConfigurationChanged += new ConfigurationChangedEventHandler(OnMetaDataConfigurationChanged);
                Thread.Sleep(100);
                builder.WriteMetaConfig(CreateNewConfigurationSection());
                Thread.Sleep(250);

                builder.ConfigurationChanging -= new ConfigurationChangingEventHandler(CancelingHandler);
                builder.ConfigurationChanging += new ConfigurationChangingEventHandler(AcceptingHandler);
                builder.WriteMetaConfig(CreateNewConfigurationSection());
                Thread.Sleep(250);

                Assert.AreEqual("ChangeCanceledChangeAcceptedMetaDataChanged", eventString);
            }
            finally
            {
                builder.WriteMetaConfiguration(existingSettings);
            }
        }
        public void DifferentConfigSources_Merged_KeysAreSorted()
        {
            var configurationBuilder = new ConfigurationBuilder();
            configurationBuilder.AddJsonFile(_json1ConfigFilePath);
            configurationBuilder.AddIniFile(_iniConfigFilePath);
            configurationBuilder.AddJsonFile(_json2ConfigFilePath);
            configurationBuilder.AddXmlFile(_xmlConfigFilePath);

            var config = configurationBuilder.Build();

            var configurationSection = config.GetSection("address");
            var indexConfigurationSections = configurationSection.GetChildren().ToArray();

            Assert.Equal(8, indexConfigurationSections.Length);
            Assert.Equal("0", indexConfigurationSections[0].Key);
            Assert.Equal("1", indexConfigurationSections[1].Key);
            Assert.Equal("2", indexConfigurationSections[2].Key);
            Assert.Equal("3", indexConfigurationSections[3].Key);
            Assert.Equal("4", indexConfigurationSections[4].Key);
            Assert.Equal("i", indexConfigurationSections[5].Key);
            Assert.Equal("j", indexConfigurationSections[6].Key);
            Assert.Equal("x", indexConfigurationSections[7].Key);

            Assert.Equal("address:0", indexConfigurationSections[0].Path);
            Assert.Equal("address:1", indexConfigurationSections[1].Path);
            Assert.Equal("address:2", indexConfigurationSections[2].Path);
            Assert.Equal("address:3", indexConfigurationSections[3].Path);
            Assert.Equal("address:4", indexConfigurationSections[4].Path);
            Assert.Equal("address:i", indexConfigurationSections[5].Path);
            Assert.Equal("address:j", indexConfigurationSections[6].Path);
            Assert.Equal("address:x", indexConfigurationSections[7].Path);
        }
		protected override void OnCreate(Bundle bundle)
		{
			base.OnCreate(bundle);

			// Set our view from the "main" layout resource
			SetContentView(Resource.Layout.Autorize);

			// Get our button from the layout resource,
			// and attach an event to it
			Button button = FindViewById<Button>(Resource.Id.sumbit);

			button.Click += delegate {
				EditText textLogin = FindViewById<EditText> (Resource.Id.login);
				EditText textPass = FindViewById<EditText> (Resource.Id.password);
				string login = textLogin.Text.ToString ();
				string pass = textPass.Text.ToString ();
				// TODO change OAuth keys and tokens and username and password 

				config = new ConfigurationBuilder ();
				config.SetOAuthConsumerKey ("nz2FD8IELdrglLbNMJ1WeMsze");
				config.SetOAuthConsumerSecret ("Q5ZGt7Bc2McY3xdfjks3AU4yw5DKKSv0h3oXCTpjYhV25qwKL0");
				config.SetOAuthAccessToken ("4359603449-6z2CXsqmH4REQayCNgqwq71wM49PjbkSmNIUJil");
				config.SetOAuthAccessTokenSecret ("nAvebHjYLn1JXnO4PwqtmTBhPoet5rhIRUnlKghtmT8Ns");
				config.SetUser (login);
				config.SetPassword (pass);

				factory = new TwitterFactory (config.Build ());
				twitter = factory.Instance;

				GetInfo ();
			};
		}
        public void WithSimpleProperty_maps_properly()
        {
            //Arrange
            var builder = new ConfigurationBuilder();
            var post = new Post() { Title = "test" };

            //Act
            builder
                .Resource<Post, PostsController>()
                .WithSimpleProperty(p => p.Title);

            var configuration = builder.Build();
            var mapping = configuration.GetMapping(typeof(Post));

            //Assert
            Assert.Equal(mapping.PropertyGetters.Count, 1);
            Assert.Equal(mapping.PropertySetters.Count, 1);

            var getter = mapping.PropertyGetters.Single().Value;
            var setter = mapping.PropertySetters.Single().Value;

            Assert.Equal(((string)getter(post)), "test");

            setter(post, "works");
            Assert.Equal(post.Title, "works");
        }
        public void WithAllProperties_maps_properly()
        {
            //Arrange
            var builder = new ConfigurationBuilder();
            builder
                .WithConvention(new DefaultPropertyScanningConvention())
                .WithConvention(new CamelCaseLinkNameConvention())
                .WithConvention(new PluralizedCamelCaseTypeConvention())
                .WithConvention(new SimpleLinkedIdConvention());

            //Act
            builder
                .Resource<Post>()
                .WithAllProperties();

            builder.Resource<Author>();
            builder.Resource<Comment>();

            var configuration = builder.Build();
            var postMapping = configuration.GetMapping(typeof(Post));

            //Assert
            postMapping.Relationships.Count.ShouldEqual(2);
            postMapping.Relationships.SingleOrDefault(l => l.RelatedBaseResourceType == "authors").ShouldNotBeNull();
            postMapping.Relationships.SingleOrDefault(l => l.RelatedBaseResourceType == "comments").ShouldNotBeNull();
            postMapping.PropertyGetters.Count.ShouldEqual(2);
            postMapping.PropertySetters.Count.ShouldEqual(2);
            postMapping.IdGetter.ShouldNotBeNull();
        }
 public void SetUp()
 {
     _contentRepository = new CmsContentRepositoryFake();
     _contentSourceRegistration = new ContentSourceRegistration(() => _contentRepository, null);
     _contentService = new ContentService(_contentSourceRegistration);
     _builder = new ConfigurationBuilder(_contentService);
 }
Exemple #10
0
        public void ArrayMerge()
        {
            var json1 = @"{
                'ip': [
                    '1.2.3.4',
                    '7.8.9.10',
                    '11.12.13.14'
                ]
            }";

            var json2 = @"{
                'ip': {
                    '3': '15.16.17.18'
                }
            }";

            var jsonConfigSource1 = new JsonConfigurationProvider(TestStreamHelpers.ArbitraryFilePath);
            jsonConfigSource1.Load(TestStreamHelpers.StringToStream(json1));

            var jsonConfigSource2 = new JsonConfigurationProvider(TestStreamHelpers.ArbitraryFilePath);
            jsonConfigSource2.Load(TestStreamHelpers.StringToStream(json2));

            var builder = new ConfigurationBuilder();
            builder.Add(jsonConfigSource1, load: false);
            builder.Add(jsonConfigSource2, load: false);
            var config = builder.Build();

            Assert.Equal(4, config.GetSection("ip").GetChildren().Count());
            Assert.Equal("1.2.3.4", config["ip:0"]);
            Assert.Equal("7.8.9.10", config["ip:1"]);
            Assert.Equal("11.12.13.14", config["ip:2"]);
            Assert.Equal("15.16.17.18", config["ip:3"]);
        }
        public void SetBasePath_CheckPropertiesValueOnBuilder()
        {
            var expectedBasePath = @"C:\ExamplePath";
            var builder = new ConfigurationBuilder();

            builder.SetBasePath(expectedBasePath);
            Assert.Equal(expectedBasePath, builder.Properties["BasePath"]);
        }
        public object SerializeObject(ConfigurationBuilder serializerConfig, object obj)
        {
            var config = serializerConfig.Build();
            var sut = new JsonApiTransformer() { TransformationHelper = new TransformationHelper() };
            CompoundDocument result = sut.Transform(obj, new Context() { Configuration = config, RoutePrefix = _routePrefix });

            return result;
        }
        public void SetBasePath_ThrowsIfBasePathIsNull()
        {
            // Arrange
            var builder = new ConfigurationBuilder();

            // Act and Assert
            var ex = Assert.Throws<ArgumentNullException>(() => builder.SetBasePath(null));
            Assert.Equal("basePath", ex.ParamName);
        }
        public void WithLinkedResource_maps_properly()
        {
            //Arrange
            var builder = new ConfigurationBuilder();
            builder
                .WithConvention(new CamelCaseLinkNameConvention())
                .WithConvention(new PluralizedCamelCaseTypeConvention())
                .WithConvention(new SimpleLinkedIdConvention());

            var post = new Post();
            var author = new Author
            {
                Posts = new List<Post> { post }
            };

            post.Author = author;
            post.AuthorId = 4;

            //Act
            builder
                .Resource<Post, PostsController>()
                .WithLinkedResource(p => p.Author);

            builder
                .Resource<Author, AuthorsController>()
                .WithLinkedResource(a => a.Posts);

            var configuration = builder.Build();
            var postMapping = configuration.GetMapping(typeof(Post));
            var authorMapping = configuration.GetMapping(typeof(Author));

            //Assert
            Assert.Equal(postMapping.Relationships.Count, 1);

            var linkToAuthor = postMapping.Relationships.Single();

            Assert.False(linkToAuthor.IsCollection);
            Assert.Equal(linkToAuthor.RelationshipName, "author");
            Assert.Equal(linkToAuthor.ParentType, typeof(Post));
            Assert.Equal(linkToAuthor.RelatedBaseType, typeof(Author));
            Assert.Same(linkToAuthor.RelatedResource(post), author);
            Assert.Equal(linkToAuthor.RelatedResourceId(post), 4);
            Assert.Same(linkToAuthor.ResourceMapping, authorMapping);
            Assert.Equal(authorMapping.Relationships.Count, 1);
            
            var linkToPosts = authorMapping.Relationships.Single();

            Assert.True(linkToPosts.IsCollection);
            Assert.Equal(linkToPosts.RelationshipName, "posts");
            Assert.Equal(linkToPosts.ParentType, typeof(Author));
            Assert.Equal(linkToPosts.RelatedBaseType, typeof(Post));
            Assert.Same(linkToPosts.RelatedResource(author), author.Posts);
            Assert.Null(linkToPosts.RelatedResourceId);
            Assert.Same(linkToPosts.ResourceMapping, postMapping);
            
        }
        public void AddJsonFile_ThrowsIfFileDoesNotExistAtPath()
        {
            // Arrange
            var path = Path.Combine(Directory.GetCurrentDirectory(), "file-does-not-exist.json");
            var builder = new ConfigurationBuilder();

            // Act and Assert
            var ex = Assert.Throws<FileNotFoundException>(() => JsonConfigurationExtension.AddJsonFile(builder, path));
            Assert.Equal($"The configuration file '{path}' was not found and is not optional.", ex.Message);
        }
        public void AddJsonFile_ThrowsIfFilePathIsNullOrEmpty(string path)
        {
            // Arrange
            var builder = new ConfigurationBuilder();

            // Act and Assert
            var ex = Assert.Throws<ArgumentException>(() => JsonConfigurationExtension.AddJsonFile(builder, path));
            Assert.Equal("path", ex.ParamName);
            Assert.StartsWith("File path must be a non-empty string.", ex.Message);
        }
        public void AddUserSecrets_Does_Not_Fail_On_Non_Existing_File()
        {
            var projectPath = UserSecretHelper.GetTempSecretProject();

            var builder = new ConfigurationBuilder().SetBasePath(projectPath).AddUserSecrets();
            var configuration = builder.Build();
            Assert.Equal(null, configuration["Facebook:AppSecret"]);

            UserSecretHelper.DeleteTempSecretProject(projectPath);
        }
 public void CanReadStaticProperty()
 {
     var dic = new Dictionary<string, string>
     {
         {"StaticProperty", "stuff"},
     };
     var builder = new ConfigurationBuilder(new MemoryConfigurationSource(dic));
     var config = builder.Build();
     var options = ConfigurationBinder.Bind<ComplexOptions>(config);
     Assert.Equal("stuff", ComplexOptions.StaticProperty);
 }
        public void GetBasePath_ReturnEmptyIfNotSet()
        {
            // Arrange
            var builder = new ConfigurationBuilder();

            // Act
            var actualPath = builder.GetBasePath();

            // Assert
            Assert.Equal(string.Empty, actualPath);
        }
        public void ConfigurationBuilder_TryInvokeMember_KnownMethodStrategy_IsExecutedWithCorrectParameters()
        {
            var strategyMock = new Mock<IMethodStrategy>();
            var config = new DynamicConfiguration();
            strategyMock.Setup(s => s.IsMatch(It.IsAny<string>())).Returns(true);

            var strategyList = new List<IMethodStrategy> { strategyMock.Object };

            dynamic configurationBuilder = new ConfigurationBuilder(config, strategyList);
            configurationBuilder.SomeExpectedMethod("ParamValue");
            strategyMock.Verify(s => s.Execute("SomeExpectedMethod", config, new object[] { "ParamValue" }));
        }
        public void ConfigurationBuilder_TryInvokeMember_KnownMethodStrategy_IsExecuted()
        {
            var strategyMock = new Mock<IMethodStrategy>();
            var config = new DynamicConfiguration();
            strategyMock.Setup(s => s.IsMatch(It.IsAny<string>())).Returns(true);

            var strategyList = new List<IMethodStrategy> { strategyMock.Object };

            dynamic configurationBuilder = new ConfigurationBuilder(config, strategyList);
            configurationBuilder.SomeExpectedMethod();
            strategyMock.Verify(s => s.Execute(It.IsAny<string>(), It.IsAny<Object>(), It.IsAny<Object[]>()));
        }
        public void GetBasePath_ReturnBaseBathIfSet()
        {
            // Arrange
            var testDir = Path.GetDirectoryName(Path.GetTempFileName());
            var builder = new ConfigurationBuilder();
            builder.SetBasePath(testDir);

            // Act
            var actualPath = builder.GetBasePath();

            // Assert
            Assert.Equal(testDir, actualPath);
        }
        public void Resource_creates_mapping()
        {
            //Arrange
            var builder = new ConfigurationBuilder();

            //Act
            builder.Resource<Post, PostsController>();

            var result = builder.Build();

            //Assert
            Assert.True(result.IsMappingRegistered(typeof(Post)));
            Assert.NotNull(result.GetMapping(typeof(Post)));
        }
        public void Resource_creates_mapping()
        {
            //Arrange
            var builder = new ConfigurationBuilder();

            //Act
            builder.Resource<Post>();

            var result = builder.Build();

            //Assert
            result.IsMappingRegistered(typeof(Post)).ShouldBeTrue();
            result.GetMapping(typeof(Post)).ShouldNotBeNull();
        }
        public void CanGetConfigurationSection()
        {
            // Arrange
            var dic1 = new Dictionary<string, string>()
                {
                    {"Data:DB1:Connection1", "MemVal1"},
                    {"Data:DB1:Connection2", "MemVal2"}
                };
            var dic2 = new Dictionary<string, string>()
                {
                    {"DataSource:DB2:Connection", "MemVal3"}
                };
            var dic3 = new Dictionary<string, string>()
                {
                    {"Data", "MemVal4"}
                };
            var memConfigSrc1 = new MemoryConfigurationSource(dic1);
            var memConfigSrc2 = new MemoryConfigurationSource(dic2);
            var memConfigSrc3 = new MemoryConfigurationSource(dic3);

            var builder = new ConfigurationBuilder();
            builder.Add(memConfigSrc1, load: false);
            builder.Add(memConfigSrc2, load: false);
            builder.Add(memConfigSrc3, load: false);

            var config = builder.Build();

            string memVal1, memVal2, memVal3, memVal4, memVal5;

            // Act
            var configFocus = config.GetSection("Data");

            memVal1 = configFocus["DB1:Connection1"];
            memVal2 = configFocus["DB1:Connection2"];
            memVal3 = configFocus["DB2:Connection"];
            memVal4 = configFocus["Source:DB2:Connection"];
            memVal5 = configFocus.Value;

            // Assert
            Assert.Equal("MemVal1", memVal1);
            Assert.Equal("MemVal2", memVal2);
            Assert.Equal("MemVal4", memVal5);

            Assert.Equal("MemVal1", configFocus["DB1:Connection1"]);
            Assert.Equal("MemVal2", configFocus["DB1:Connection2"]);
            Assert.Null(configFocus["DB2:Connection"]);
            Assert.Null(configFocus["Source:DB2:Connection"]);
            Assert.Equal("MemVal4", configFocus.Value);
        }
 public void CanReadComplexProperties()
 {
     var dic = new Dictionary<string, string>
     {
         {"Integer", "-2"},
         {"Boolean", "TRUe"},
         {"Nested:Integer", "11"}
     };
     var builder = new ConfigurationBuilder(new MemoryConfigurationSource(dic));
     var config = builder.Build();
     var options = ConfigurationBinder.Bind<ComplexOptions>(config);
     Assert.True(options.Boolean);
     Assert.Equal(-2, options.Integer);
     Assert.Equal(11, options.Nested.Integer);
 }
        public void ExceptionIncludesKeyOfFailedBinding()
        {
            var input = new Dictionary<string, string>
            {
                {"NestedOptionsProperty:NestedOptions2Property:ISomeInterfaceProperty:subkey", "x"}
            };

            var builder = new ConfigurationBuilder(new MemoryConfigurationSource(input));
            var config = builder.Build();

            var exception = Assert.Throws<InvalidOperationException>(
                () => ConfigurationBinder.Bind<TestOptions>(config));
            Assert.Equal(
                Resources.FormatError_CannotActivateAbstractOrInterface(typeof(ISomeInterface)),
                exception.Message);
        }
        public void full_test()
        {
            var valueProviderStub = new FeatureToggleValueProviderBuilder()
                .WithFeatureToggle("f1", true)
                .WithFeatureToggle("f2", false)
                .Build();

            var cfg = new ConfigurationBuilder()
                .WithValueProvider(valueProviderStub)
                .Build();

            TogglrEngine.ApplyConfiguration(cfg);

            Assert.IsTrue(TogglrEngine.IsFeatureEnabled("f1"));
            Assert.IsFalse(TogglrEngine.IsFeatureEnabled("f2"));
        }
        public void AddUserSecrets_With_An_Existing_Secret_File()
        {
            string userSecretsId;
            var projectPath = UserSecretHelper.GetTempSecretProject(out userSecretsId);

            var logger = new TestLogger(_runtimeEnv);
            var secretManager = new Program(_runtimeEnv) { Logger = logger };

            secretManager.Main(new string[] { "set", "Facebook:AppSecret", "value1", "-p", projectPath });

            var builder = new ConfigurationBuilder().SetBasePath(projectPath).AddUserSecrets();
            var configuration = builder.Build();
            Assert.Equal("value1", configuration["Facebook:AppSecret"]);

            UserSecretHelper.DeleteTempSecretProject(projectPath);
        }
        public void LoadAndCombineKeyValuePairsFromDifferentConfigurationProviders()
        {
            // Arrange
            var dic1 = new Dictionary<string, string>()
                {
                    {"Mem1:KeyInMem1", "ValueInMem1"}
                };
            var dic2 = new Dictionary<string, string>()
                {
                    {"Mem2:KeyInMem2", "ValueInMem2"}
                };
            var dic3 = new Dictionary<string, string>()
                {
                    {"Mem3:KeyInMem3", "ValueInMem3"}
                };
            var memConfigSrc1 = new MemoryConfigurationProvider(dic1);
            var memConfigSrc2 = new MemoryConfigurationProvider(dic2);
            var memConfigSrc3 = new MemoryConfigurationProvider(dic3);

            var configurationBuilder = new ConfigurationBuilder();

            // Act
            configurationBuilder.Add(memConfigSrc1, load: false);
            configurationBuilder.Add(memConfigSrc2, load: false);
            configurationBuilder.Add(memConfigSrc3, load: false);

            var config = configurationBuilder.Build();

            var memVal1 = config["mem1:keyinmem1"];
            var memVal2 = config["Mem2:KeyInMem2"];
            var memVal3 = config["MEM3:KEYINMEM3"];

            // Assert
            Assert.Contains(memConfigSrc1, configurationBuilder.Providers);
            Assert.Contains(memConfigSrc2, configurationBuilder.Providers);
            Assert.Contains(memConfigSrc3, configurationBuilder.Providers);

            Assert.Equal("ValueInMem1", memVal1);
            Assert.Equal("ValueInMem2", memVal2);
            Assert.Equal("ValueInMem3", memVal3);

            Assert.Equal("ValueInMem1", config["mem1:keyinmem1"]);
            Assert.Equal("ValueInMem2", config["Mem2:KeyInMem2"]);
            Assert.Equal("ValueInMem3", config["MEM3:KEYINMEM3"]);
            Assert.Null(config["NotExist"]);
        }
Exemple #31
0
        static void Main(string[] args)
        {
            var sandbox = new Session()
            {
                EndPoint = "https://api-sandbox.pitneybowes.com", Requester = new ShippingApiHttpRequest()
            };

            var configs = new Dictionary <string, string>
            {
                { "ApiKey", "YOUR_API_KEY" },
                { "ApiSecret", "YOUR_API_SECRET" },
                { "RatePlan", "YOUR_RATE_PLAN" },
                { "ShipperID", "YOUR_SHIPPER_ID" },
                { "DeveloperID", "YOUR_DEVELOPER_ID" }
            };
            var configurationBuilder = new ConfigurationBuilder();

            configurationBuilder
            .AddInMemoryCollection(configs)
            .AddJsonFile(Globals.GetConfigPath("shippingapisettings.json"), optional: true, reloadOnChange: true);

            sandbox.GetConfigItem = (c) => configurationBuilder.Build()[c];
            Model.RegisterSerializationTypes(sandbox.SerializationRegistry);
            Globals.DefaultSession = sandbox;

            var shipment = (Shipment)ShipmentFluent <Shipment> .Create()
                           .ToAddress((Address)AddressFluent <Address> .Create()
                                      .AddressLines("643 Greenway Rd")
                                      .PostalCode("28607")
                                      .CountryCode("US")
                                      .Verify())
                           .FromAddress((Address)AddressFluent <Address> .Create()
                                        .Company("Pitney Bowes Inc")
                                        .AddressLines("27 Waterview Drive")
                                        .CityTown("Shelton").StateProvince("CT").PostalCode("06484")
                                        .CountryCode("US")
                                        )
                           .Parcel((Parcel)ParcelFluent <Parcel> .Create()
                                   .Dimension(12, 0.25M, 9)
                                   .Weight(3m, UnitOfWeight.OZ))
                           .Rates(RatesArrayFluent <Rates> .Create()
                                  .USPSPriority <Rates, Parameter>()
                                  .InductionPostalCode("06484")
                                  )
                           .Documents((List <IDocument>)DocumentsArrayFluent <Document> .Create()
                                      .ShippingLabel(ContentType.BASE64, Size.DOC_4X6, FileFormat.PNG))
                           .ShipmentOptions(ShipmentOptionsArrayFluent <ShipmentOptions> .Create()
                                            .ShipperId(sandbox.GetConfigItem("ShipperID"))
                                            .MinimalAddressvalidation()
                                            )
                           .TransactionId(Guid.NewGuid().ToString().Substring(15));

            shipment.IncludeDeliveryCommitment = true;
            var label = Api.CreateShipment(shipment).GetAwaiter().GetResult();

            if (label.Success)
            {
                var sw = new StreamWriter("label.pdf");
                foreach (var d in label.APIResponse.Documents)
                {
                    Api.WriteToStream(d, sw.BaseStream).GetAwaiter().GetResult();
                }
            }
        }
Exemple #32
0
        public static void Main(string[] args)
        {
            var    secret = "profile";
            string luis   = null;

            if (args.Length == 0)
            {
                Help();
            }

            for (var i = 0; i < args.Length; ++i)
            {
                var arg = args[i];
                if (arg.StartsWith("-"))
                {
                    if (arg == "-secret")
                    {
                        if (++i < args.Length)
                        {
                            secret = args[i];
                        }
                        else
                        {
                            throw new System.ArgumentException("Missing --secret value");
                        }
                    }
                    else if (arg == "-luis")
                    {
                        if (++i < args.Length)
                        {
                            luis = args[i];
                        }
                        else
                        {
                            throw new System.ArgumentException("Missing --luis value");
                        }
                    }
                    else
                    {
                        Console.Error.WriteLine($"Unknown arg {arg}");
                        Help();
                    }
                }
                else
                {
                    var cd     = Directory.GetCurrentDirectory();
                    var dir    = Path.GetDirectoryName(arg);
                    var name   = Path.GetFileName(arg);
                    var config = new ConfigurationBuilder()
                                 .AddInMemoryCollection()
                                 .UseLuisSettings(luis ?? dir, secret)
                                 .Build();
                    var explorer = new ResourceExplorer().AddFolder(dir);
                    DeclarativeTypeLoader.Reset();
                    TypeFactory.Configuration = config;
                    DeclarativeTypeLoader.AddComponent(new DialogComponentRegistration());
                    DeclarativeTypeLoader.AddComponent(new AdaptiveComponentRegistration());
                    DeclarativeTypeLoader.AddComponent(new LanguageGenerationComponentRegistration());
                    DeclarativeTypeLoader.AddComponent(new QnAMakerComponentRegistration());
                    DeclarativeTypeLoader.AddComponent(new MockLuisComponentRegistration());
                    var script = explorer.LoadType <TestScript>(name);
                    var timer  = new System.Diagnostics.Stopwatch();
                    Console.Write($"Executing {arg}");
                    timer.Start();
                    script.ExecuteAsync(testName: name, configuration: config, resourceExplorer: explorer).Wait();
                    timer.Stop();
                    Console.WriteLine($" took {timer.ElapsedMilliseconds} ms");
                }
            }
        }
Exemple #33
0
        public void AddConfigServer_VCAP_SERVICES_Override_Defaults()
        {
            // Arrange
            var          configurationBuilder = new ConfigurationBuilder();
            const string vcap_application     = @" 
                {
                    ""application_id"": ""fa05c1a9-0fc1-4fbd-bae1-139850dec7a3"",
                    ""application_name"": ""foo"",
                    ""application_uris"": [
                        ""foo.10.244.0.34.xip.io""
                    ],
                    ""application_version"": ""fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca"",
                    ""limits"": {
                        ""disk"": 1024,
                        ""fds"": 16384,
                        ""mem"": 256
                    },
                    ""name"": ""foo"",
                    ""space_id"": ""06450c72-4669-4dc6-8096-45f9777db68a"",
                    ""space_name"": ""my-space"",
                    ""uris"": [
                        ""foo.10.244.0.34.xip.io""
                    ],
                    ""users"": null,
                    ""version"": ""fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca""
                }";

            const string vcap_services = @"
                {
                    ""p-config-server"": [
                    {
                        ""name"": ""config-server"",
                        ""instance_name"": ""config-server"",
                        ""binding_name"": null,
                        ""credentials"": {
                            ""uri"": ""https://uri-from-vcap-services"",
                            ""client_secret"": ""some-secret"",
                            ""client_id"": ""some-client-id"",
                            ""access_token_uri"": ""https://uaa-uri-from-vcap-services/oauth/token""
                        },
                        ""syslog_drain_url"": null,
                        ""volume_mounts"": [],
                        ""label"": ""p-config-server"",
                        ""plan"": ""standard"",
                        ""provider"": null,
                        ""tags"": [
                            ""configuration"",
                            ""spring-cloud""
                        ]
                    }]
                }";

            Environment.SetEnvironmentVariable("VCAP_APPLICATION", vcap_application);
            Environment.SetEnvironmentVariable("VCAP_SERVICES", vcap_services);
            var settings = new ConfigServerClientSettings()
            {
                Uri = "https://uri-from-settings"
            };

            // Act
            configurationBuilder
            .AddEnvironmentVariables()
            .AddConfigServer(settings);
            var config = configurationBuilder.Build();
            var configServerProvider = config.Providers.OfType <ConfigServerConfigurationProvider>().FirstOrDefault();

            // Assert
            Assert.NotNull(configServerProvider);
            Assert.IsType <ConfigServerConfigurationProvider>(configServerProvider);

            Assert.NotEqual("https://uri-from-settings", configServerProvider.Settings.Uri);
            Assert.Equal("https://uri-from-vcap-services", configServerProvider.Settings.Uri);

            // reset to avoid breaking other tests
            Environment.SetEnvironmentVariable("VCAP_APPLICATION", string.Empty);
            Environment.SetEnvironmentVariable("VCAP_SERVICES", string.Empty);
        }
        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            try
            {
                //   var config = new ConfigurationBuilder()
                //.SetBasePath(Directory.GetCurrentDirectory())
                //.AddJsonFile("hostsettings.json", optional: true)
                //.AddCommandLine(args)
                //.Build();

                var config = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
      .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true).AddCommandLine(args).Build();

                return Host.CreateDefaultBuilder(args)
                      .ConfigureWebHostDefaults(webBuilder =>
                      {
                          //webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
                          webBuilder.UseConfiguration(config);
                          //webBuilder.UseIISIntegration();
                          //webBuilder.ConfigureKestrel(serverOptions =>
                          //{
                          //    // Set properties and call methods on options
                          //    serverOptions.Limits.MaxConcurrentConnections = 100;
                          //    serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
                          //    serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
                          //    serverOptions.Limits.MinRequestBodyDataRate =
                          //        new MinDataRate(bytesPerSecond: 100,
                          //            gracePeriod: TimeSpan.FromSeconds(10));
                          //    serverOptions.Limits.MinResponseDataRate =
                          //        new MinDataRate(bytesPerSecond: 100,
                          //            gracePeriod: TimeSpan.FromSeconds(10));
                          //    serverOptions.Listen(IPAddress.Loopback, 5000);

                          //    serverOptions.Limits.KeepAliveTimeout =
                          //        TimeSpan.FromMinutes(2);
                          //    serverOptions.Limits.RequestHeadersTimeout =
                          //        TimeSpan.FromMinutes(1);
                          //});
                          webBuilder.UseKestrel(a => a.ConfigureEndpoints());
                          webBuilder.UseContentRoot(Directory.GetCurrentDirectory());             
                          webBuilder.UseUrls(config.GetSection("urls").Value);
                          webBuilder.UseIISIntegration();
                          // //
                          //webBuilder.ConfigureKestrel(serverOptions =>
                          //{
                          //    serverOptions.ConfigureHttpsDefaults(listenOptions =>
                          //    {
                          //        // certificate is an X509Certificate2
                          //        listenOptions.ServerCertificate = certificate;
                          //    });
                          //});
                          webBuilder.UseStartup<Startup>();
                      });
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                throw ex;
            }

        }
Exemple #35
0
        public bool run_action(ChocolateyConfiguration configuration, PackageResult packageResult, CommandNameType command)
        {
            var installerRun = false;

            var packageDirectory = packageResult.InstallLocation;

            if (packageDirectory.is_equal_to(ApplicationParameters.InstallLocation) || packageDirectory.is_equal_to(ApplicationParameters.PackagesLocation))
            {
                packageResult.Messages.Add(
                    new ResultMessage(
                        ResultType.Error,
                        "Install location is not specific enough, cannot run PowerShell script:{0} Erroneous install location captured as '{1}'".format_with(Environment.NewLine, packageResult.InstallLocation)
                        )
                    );

                return(false);
            }

            if (!_fileSystem.directory_exists(packageDirectory))
            {
                packageResult.Messages.Add(new ResultMessage(ResultType.Error, "Package install not found:'{0}'".format_with(packageDirectory)));
                return(installerRun);
            }

            var chocoPowerShellScript = get_script_for_action(packageResult, command);

            if (!string.IsNullOrEmpty(chocoPowerShellScript))
            {
                var failure = false;

                ConfigurationBuilder.set_environment_variables(configuration);

                var package = packageResult.Package;
                Environment.SetEnvironmentVariable("chocolateyPackageName", package.Id);
                Environment.SetEnvironmentVariable("packageName", package.Id);
                Environment.SetEnvironmentVariable("chocolateyPackageVersion", package.Version.to_string());
                Environment.SetEnvironmentVariable("packageVersion", package.Version.to_string());
                Environment.SetEnvironmentVariable("chocolateyPackageFolder", packageDirectory);
                Environment.SetEnvironmentVariable("packageFolder", packageDirectory);
                Environment.SetEnvironmentVariable("installArguments", configuration.InstallArguments);
                Environment.SetEnvironmentVariable("installerArguments", configuration.InstallArguments);
                Environment.SetEnvironmentVariable("chocolateyInstallArguments", configuration.InstallArguments);
                Environment.SetEnvironmentVariable("packageParameters", configuration.PackageParameters);
                Environment.SetEnvironmentVariable("chocolateyPackageParameters", configuration.PackageParameters);

                if (configuration.ForceX86)
                {
                    Environment.SetEnvironmentVariable("chocolateyForceX86", "true");
                }
                if (configuration.OverrideArguments)
                {
                    Environment.SetEnvironmentVariable("chocolateyInstallOverride", "true");
                }

                if (configuration.NotSilent)
                {
                    Environment.SetEnvironmentVariable("chocolateyInstallOverride", "true");
                }

                //todo:if (configuration.NoOutput)
                //{
                //    Environment.SetEnvironmentVariable("ChocolateyEnvironmentQuiet","true");
                //}

                if (package.IsDownloadCacheAvailable)
                {
                    foreach (var downloadCache in package.DownloadCache.or_empty_list_if_null())
                    {
                        var urlKey = CryptoHashProvider.hash_value(downloadCache.OriginalUrl, CryptoHashProviderType.Sha256).Replace("=", string.Empty);
                        Environment.SetEnvironmentVariable("CacheFile_{0}".format_with(urlKey), downloadCache.FileName);
                        Environment.SetEnvironmentVariable("CacheChecksum_{0}".format_with(urlKey), downloadCache.Checksum);
                        Environment.SetEnvironmentVariable("CacheChecksumType_{0}".format_with(urlKey), "sha512");
                    }
                }

                this.Log().Debug(ChocolateyLoggers.Important, "Contents of '{0}':".format_with(chocoPowerShellScript));
                string chocoPowerShellScriptContents = _fileSystem.read_file(chocoPowerShellScript);
                this.Log().Debug(chocoPowerShellScriptContents.escape_curly_braces());

                bool shouldRun = !configuration.PromptForConfirmation;

                if (!shouldRun)
                {
                    this.Log().Info(ChocolateyLoggers.Important, () => "The package {0} wants to run '{1}'.".format_with(package.Id, _fileSystem.get_file_name(chocoPowerShellScript)));
                    this.Log().Info(ChocolateyLoggers.Important, () => "Note: If you don't run this script, the installation will fail.");
                    this.Log().Info(ChocolateyLoggers.Important, () => @"Note: To confirm automatically next time, use '-y' or consider setting 
 'allowGlobalConfirmation'. Run 'choco feature -h' for more details.");

                    var selection = InteractivePrompt.prompt_for_confirmation(@"Do you want to run the script?",
                                                                              new[] { "yes", "no", "print" },
                                                                              defaultChoice: null,
                                                                              requireAnswer: true,
                                                                              allowShortAnswer: true,
                                                                              shortPrompt: true
                                                                              );

                    if (selection.is_equal_to("print"))
                    {
                        this.Log().Info(ChocolateyLoggers.Important, "------ BEGIN SCRIPT ------");
                        this.Log().Info(() => "{0}{1}{0}".format_with(Environment.NewLine, chocoPowerShellScriptContents.escape_curly_braces()));
                        this.Log().Info(ChocolateyLoggers.Important, "------- END SCRIPT -------");
                        selection = InteractivePrompt.prompt_for_confirmation(@"Do you want to run this script?",
                                                                              new[] { "yes", "no" },
                                                                              defaultChoice: null,
                                                                              requireAnswer: true,
                                                                              allowShortAnswer: true,
                                                                              shortPrompt: true
                                                                              );
                    }

                    if (selection.is_equal_to("yes"))
                    {
                        shouldRun = true;
                    }
                    if (selection.is_equal_to("no"))
                    {
                        Environment.ExitCode = 1;
                        packageResult.Messages.Add(new ResultMessage(ResultType.Error, "User cancelled powershell portion of installation for '{0}'.{1} Specify -n to skip automated script actions.".format_with(chocoPowerShellScript, Environment.NewLine)));
                    }
                }

                if (shouldRun)
                {
                    installerRun = true;

                    if (configuration.Features.UsePowerShellHost)
                    {
                        add_assembly_resolver();
                    }

                    var result = new PowerShellExecutionResults
                    {
                        ExitCode = -1
                    };

                    try
                    {
                        result = configuration.Features.UsePowerShellHost
                                    ? Execute.with_timeout(configuration.CommandExecutionTimeoutSeconds).command(() => run_host(configuration, chocoPowerShellScript), result)
                                    : run_external_powershell(configuration, chocoPowerShellScript);
                    }
                    catch (Exception ex)
                    {
                        this.Log().Error(ex.Message.escape_curly_braces());
                        result.ExitCode = -1;
                    }

                    if (configuration.Features.UsePowerShellHost)
                    {
                        remove_assembly_resolver();
                    }

                    if (result.StandardErrorWritten && configuration.Features.FailOnStandardError)
                    {
                        failure = true;
                    }
                    else if (result.StandardErrorWritten && result.ExitCode == 0)
                    {
                        this.Log().Warn(
                            () =>
                            @"Only an exit code of non-zero will fail the package by default. Set 
 `--failonstderr` if you want error messages to also fail a script. See 
 `choco -h` for details.");
                    }


                    if (result.ExitCode != 0)
                    {
                        Environment.ExitCode   = result.ExitCode;
                        packageResult.ExitCode = result.ExitCode;
                    }

                    // 0 - most widely used success exit code
                    // MSI valid exit codes
                    // 1605 - (uninstall) - the product is not found, could have already been uninstalled
                    // 1614 (uninstall) - the product is uninstalled
                    // 1641 - restart initiated
                    // 3010 - restart required
                    var validExitCodes = new List <int> {
                        0, 1605, 1614, 1641, 3010
                    };
                    if (!validExitCodes.Contains(result.ExitCode))
                    {
                        failure = true;
                    }

                    if (failure)
                    {
                        packageResult.Messages.Add(new ResultMessage(ResultType.Error, "Error while running '{0}'.{1} See log for details.".format_with(chocoPowerShellScript, Environment.NewLine)));
                    }
                    packageResult.Messages.Add(new ResultMessage(ResultType.Note, "Ran '{0}'".format_with(chocoPowerShellScript)));
                }
            }

            return(installerRun);
        }
Exemple #36
0
        static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .AddUserSecrets(typeof(Program).Assembly)
                                .Build();

            // var connectionString = configuration.GetConnectionString("ConnectionString");

            // Console.WriteLine(connectionString.Substring(0, 10));

            // using var connection = new SqlConnection(connectionString);

            // connection.Open();

            // Console.Write("Input search string: ");

            // var searchString = Console.ReadLine();

            // var cmdText = $"SELECT * FROM Characters WHERE Name LIKE '%' + @SearchString + '%'";

            // using var command = new SqlCommand(cmdText, connection);
            // command.Parameters.AddWithValue("@SearchString", searchString);

            // using var reader = command.ExecuteReader();

            // while (reader.Read())
            // {
            //     Console.WriteLine(reader["Name"]);
            // }

            // RawSqlDemo.Run(connectionString);

            // var builder = new DbContextOptionsBuilder<FuturamaContext>();
            // builder.UseSqlServer(connectionString);
            // using var context = new FuturamaContext(builder.Options);

            // foreach (var character in context.Characters)
            // {
            //     Console.WriteLine(character.Name);
            // }

            // var amy = from c in context.Characters
            //           where c.Name == "Amy Wong"
            //           select new { c.Name, Actor = c.Actor.Name };

            // amy.Print();

            // var hermes = context.Characters.First(h => h.Name.Contains("Conrad"));

            // context.Characters.Remove(hermes);
            // context.SaveChanges();

            // var hubert = context.Characters.Find(7);

            // Console.WriteLine(hubert.Name);

            // hubert.Name = "Hubert Farnsworth";

            // context.SaveChanges();

            var connectionString = configuration.GetConnectionString("Superheroes");
            var builder          = new DbContextOptionsBuilder <SuperheroContext>();

            builder.UseSqlServer(connectionString)
            .UseLazyLoadingProxies();

            using var context = new SuperheroContext(builder.Options);

            // var superheroes = from h in context.Superheroes
            //                   select new
            //                   {
            //                       h.Name,
            //                       Powers = h.Powers.Select(p => p.Power.Name)
            //                   };

            // foreach (var superhero in superheroes)
            // {
            //     Console.WriteLine(superhero.Name);
            //     superhero.Powers.Print();
            // }

            // context.Database.ExecuteSqlRaw("UPDATE Powers SET Name = 'Updated(' + Name + ')'");

            var superheroes = context.Superheroes; //.Include(c => c.City);

            foreach (var superhero in superheroes)
            {
                Console.WriteLine(superhero.City.Name);
            }

            // var superheroes = from h in context.Superheroes
            //                   orderby h.AlterEgo
            //                   select new
            //                   {
            //                       h.AlterEgo,
            //                       h.Name,
            //                       City = h.City.Name
            //                   };

            // superheroes.Print();
        }
        /// <summary>
        /// Entry point
        /// </summary>
        public static void Main(string[] args)
        {
            var    checkTrust = true;
            var    withServer = false;
            var    verbose = false;
            string deviceId = null, moduleId = null;

            Console.WriteLine("Publisher module command line interface.");
            var configuration = new ConfigurationBuilder()
                                .AddFromDotEnvFile()
                                .AddEnvironmentVariables()
                                .AddEnvironmentVariables(EnvironmentVariableTarget.User)
                                // Above configuration providers will provide connection
                                // details for KeyVault configuration provider.
                                .AddFromKeyVault(providerPriority: ConfigurationProviderPriority.Lowest)
                                .Build();
            var cs = configuration.GetValue <string>(PcsVariable.PCS_IOTHUB_CONNSTRING, null);

            if (string.IsNullOrEmpty(cs))
            {
                cs = configuration.GetValue <string>("_HUB_CS", null);
            }
            IIoTHubConfig config      = null;
            var           unknownArgs = new List <string>();

            try {
                for (var i = 0; i < args.Length; i++)
                {
                    switch (args[i])
                    {
                    case "-C":
                    case "--connection-string":
                        i++;
                        if (i < args.Length)
                        {
                            cs = args[i];
                            break;
                        }
                        throw new ArgumentException(
                                  "Missing arguments for connection string");

                    case "-?":
                    case "-h":
                    case "--help":
                        throw new ArgumentException("Help");

                    case "-t":
                    case "--only-trusted":
                        checkTrust = true;
                        break;

                    case "-s":
                    case "--with-server":
                        withServer = true;
                        break;

                    case "-v":
                    case "--verbose":
                        verbose = true;
                        break;

                    default:
                        unknownArgs.Add(args[i]);
                        break;
                    }
                }
                if (string.IsNullOrEmpty(cs))
                {
                    throw new ArgumentException("Missing connection string.");
                }
                if (!ConnectionString.TryParse(cs, out var connectionString))
                {
                    throw new ArgumentException("Bad connection string.");
                }
                config = connectionString.ToIoTHubConfig();

                if (deviceId == null)
                {
                    deviceId = Utils.GetHostName();
                    Console.WriteLine($"Using <deviceId> '{deviceId}'");
                }
                if (moduleId == null)
                {
                    moduleId = "publisher";
                    Console.WriteLine($"Using <moduleId> '{moduleId}'");
                }

                args = unknownArgs.ToArray();
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
                Console.WriteLine(
                    @"
Usage:       Microsoft.Azure.IIoT.Modules.OpcUa.Publisher.Cli [options]

Options:
     -C
    --connection-string
             IoT Hub owner connection string to use to connect to IoT hub for
             operations on the registry.  If not provided, read from environment.

    --help
     -?
     -h      Prints out this help.
"
                    );
                return;
            }

            var logger = ConsoleLogger.Create(LogEventLevel.Error);

            AppDomain.CurrentDomain.UnhandledException += (s, e) => {
                logger.Fatal(e.ExceptionObject as Exception, "Exception");
                Console.WriteLine(e);
            };

            try {
                if (!withServer)
                {
                    HostAsync(config, logger, deviceId, moduleId, args, verbose, !checkTrust).Wait();
                }
                else
                {
                    WithServerAsync(config, logger, deviceId, moduleId, args, verbose).Wait();
                }
            }
            catch (Exception e) {
                Console.WriteLine(e);
            }
        }
Exemple #38
0
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath).AddJsonFile("appsettings.json");

            Configuration = builder.Build();
        }
        /// <summary>
        /// Private constructor used to construct the only instance which will
        /// exist of this class.
        /// </summary>
        private WebPipeline()
        {
            IConfiguration config = new ConfigurationBuilder()
                .AddPipelineConfig()
                .Build();
            _options = new PipelineWebIntegrationOptions();
            config.Bind("PipelineOptions", _options);
            
            if (_options == null ||
                _options.Elements == null)
            {
                throw new PipelineConfigurationException(
                   Messages.ExceptionNoConfiguration);
            }

            // Add the sequence element.
            var sequenceConfig = _options.Elements.Where(e =>
                e.BuilderName.IndexOf(nameof(SequenceElement),
                    StringComparison.OrdinalIgnoreCase) >= 0);
            if (sequenceConfig.Any() == false)
            {
                // The sequence element is not included so add it.
                // Make sure it's added as the first element.
                _options.Elements.Insert(0, new ElementOptions()
                {
                    BuilderName = nameof(SequenceElement)
                });
            }

            if (ClientSideEvidenceEnabled)
            {
                // Client-side evidence is enabled so make sure the 
                // JsonBuilderElement and JavaScriptBundlerElement has been 
                // included.
                var jsonConfig = _options.Elements.Where(e =>
                    e.BuilderName.StartsWith(nameof(JsonBuilderElement),
                        StringComparison.OrdinalIgnoreCase));
                var javascriptConfig = _options.Elements.Where(e =>
                    e.BuilderName.StartsWith(nameof(JavaScriptBuilderElement),
                        StringComparison.OrdinalIgnoreCase));

                var jsIndex = javascriptConfig.Any() ?
                    _options.Elements.IndexOf(javascriptConfig.First()) : -1;

                if (jsonConfig.Any() == false)
                {
                    // The json builder is not included so add it.
                    var newElementOptions = new ElementOptions()
                    {
                        BuilderName = nameof(JsonBuilderElement)
                    };
                    if (jsIndex > -1)
                    {
                        // There is already a javascript builder element
                        // so insert the json builder before it.
                        _options.Elements.Insert(jsIndex, newElementOptions);
                    }
                    else
                    {
                        _options.Elements.Add(newElementOptions);
                    }
                }

                if (jsIndex == -1)
                {
                    // The javascript builder is not included so add it.
                    _options.Elements.Add(new ElementOptions()
                    {
                        BuilderName = nameof(JavaScriptBuilderElement),
                        BuildParameters = new Dictionary<string, object>()
                        {
                            { "EndPoint", "/51dpipeline/json" }
                        }
                    });
                }
                else
                {
                    // There is already a JavaScript builder config so check if 
                    // the endpoint is specified. If not, add it.
                    if (javascriptConfig.Single().BuildParameters.ContainsKey("EndPoint") == false)
                    {
                        javascriptConfig.Single().BuildParameters.Add("EndPoint", "/51dpipeline/json");
                    }
                }
            }

            // Add the set headers
            var setHeadersConfig = _options.Elements.Where(e =>
                e.BuilderName.IndexOf(nameof(SetHeadersElement),
                    StringComparison.OrdinalIgnoreCase) >= 0);
            if (setHeadersConfig.Any() == false)
            {
                // The set headers element is not included, so add it.
                // Make sure it's added as the last element.
                _options.Elements.Add(new ElementOptions()
                {
                    BuilderName = nameof(SetHeadersElement)
                });
            }

            // Set up common services.
            var loggerFactory = new LoggerFactory();
            var updateService = new DataUpdateService(
                loggerFactory.CreateLogger<DataUpdateService>(),
                new System.Net.Http.HttpClient());
            var services = new FiftyOneServiceProvider();
            // Add data update and missing property services.
            services.AddService(updateService);
            services.AddService(MissingPropertyService.Instance);

            Pipeline = new PipelineBuilder(
                loggerFactory,
                services)
                .BuildFromConfiguration(_options);
        }
Exemple #40
0
        static async Task Main(string[] args)
        {
            //Create Serilog logger
            Log.Logger = new LoggerConfiguration()
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .CreateLogger();

            //setup our DI
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddLogging(loggingBuilder =>
                                         loggingBuilder.AddSerilog(dispose: true))
            .AddTransient <IDataProvider, LibrariesLiteDbDataProvider>()
            .AddTransient <IIngressProvider, LibrariesSODADataProvider>()
            .AddTransient <LibraryParser>()
            .AddTransient <Csv.VisitorsParser>()
            .AddTransient <LiteDbRepository>();


            Log.Debug("Starting application");

            Log.Debug("Initializing configuration");
            try
            {
                var builder = new ConfigurationBuilder()
                              .SetBasePath(Path.Combine(AppContext.BaseDirectory))
                              .AddJsonFile("appsettings.json", optional: true);
                IConfigurationRoot configuration = builder.Build();
                serviceCollection.AddSingleton <IConfiguration>(configuration);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Configuration initialization failed");
                return;
            }


            IDictionary <string, object> parsedArgs = null;

            try
            {
                parsedArgs = new Arguments(args).Data.ToDictionary(_ => _.Key, _ => (object)_.Value);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Cannot parse commmand line arguments");
                return;
            }

            var serviceProvider = serviceCollection.BuildServiceProvider();

            var ingressProvider = serviceProvider.GetService <IIngressProvider>();

            (int entitiesProcessed, Exception exception) = await ingressProvider.ProcessDataAsync(parsedArgs);

            if (exception == null)
            {
                Log.Information("All done! {entitiesProcessed} processed", entitiesProcessed);
            }
            else
            {
                Log.Error(exception, "Error");
            }
        }
Exemple #41
0
        protected void PopulateFromConfigFile()
        {
            var configLocation = GetConfigFileLocation();

            if (configLocation == null || configLocation.Trim() == string.Empty)
            {
                throw new Exception("Unable to find the Config location");
            }

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Path.GetDirectoryName(configLocation))
                          .AddJsonFile(Path.GetFileName(configLocation), optional: false, reloadOnChange: true);

            var config = builder.Build();

            var appSettings          = config.GetSection("configuration:appSettings");
            var frameworkLogSettings = config.GetSection("Logging");

            PopulateFromConfigFile(appSettings, frameworkLogSettings, configLocation);

            if (DbSettings.MigrationNamespace.IsTrimmedStringNullOrEmpty())
            {
                throw new Exception(ErrorConstants.MigrationNamespaceIsEmpty);
            }

            ServerPort       = SafeUtils.Int(appSettings[Strings.Config.ServerPort], ServerPort);
            AppName          = Path.GetFileNameWithoutExtension(this.GetType().GetTypeInfo().Assembly.Location);
            BatchSizeToIndex = SafeUtils.Int(appSettings[StringConstants.Config.BatchSizeToIndex], BatchSizeToIndex);

            EnablePushToMasterIndexServer = SafeUtils.Bool(appSettings[StringConstants.Config.EnablePushToMasterIndexServer], false);
            if (EnablePushToMasterIndexServer)
            {
                var masterIndexServerSettings = appSettings.GetSection(StringConstants.Config.MasterIndexStoreSettings);
                MasterIndexStoreSettings = new MasterIndexStoreSettings(masterIndexServerSettings);
            }

            this.IndexStoreType = SafeUtils.Enum <IndexStoreType>(appSettings[StringConstants.Config.IndexStoreType], IndexStoreType.None);

            if (IndexStoreType == IndexStoreType.Lucene)
            {
                var luceneSettings = appSettings.GetSection(StringConstants.Config.LuceneIndexStoreSettings);
                LuceneIndexStoreSettings = new LuceneIndexStoreSettings(luceneSettings, (str) =>
                {
                    if (str.IsTrimmedStringNotNullOrEmpty() && str.Contains(Strings.Config.ConfigPath))
                    {
                        str = str.Replace(Strings.Config.ConfigPath, FileUtils.GetFileDirectory(configLocation));
                        str = Path.GetFullPath(new Uri(str).LocalPath);
                    }
                    return(str);
                });

                if (Directory.Exists(LuceneIndexStoreSettings.AppLogIndexFolder) == false)
                {
                    Directory.CreateDirectory(LuceneIndexStoreSettings.AppLogIndexFolder);
                }

                if (Directory.Exists(LuceneIndexStoreSettings.PerformanceLogIndexFolder) == false)
                {
                    Directory.CreateDirectory(LuceneIndexStoreSettings.PerformanceLogIndexFolder);
                }
            }
            else if (IndexStoreType == IndexStoreType.Sqlite3 || IndexStoreType == IndexStoreType.SqlServer || IndexStoreType == IndexStoreType.Postgresql || IndexStoreType == IndexStoreType.MySql)
            {
                var configSettings = appSettings.GetSection(StringConstants.Config.SqlIndexStoreSettings);
                this.SqlIndexStoreSettings = new DbSettings(configSettings, (str) =>
                {
                    if (str.IsTrimmedStringNotNullOrEmpty() && str.Contains(Strings.Config.ConfigPath))
                    {
                        str = str.Replace(Strings.Config.ConfigPath, FileUtils.GetFileDirectory(configLocation));
                        str = Path.GetFullPath(new Uri(str).LocalPath);
                    }
                    return(str);
                });
            }
            else if (IndexStoreType == IndexStoreType.ElasticSearch)
            {
                var configSettings = appSettings.GetSection(StringConstants.Config.EmbbededElasticSearchIndexStoreSettings);
                this.ElasticSearchIndexStoreSettings = new ElasticSearchIndexStoreSettings(configSettings);
            }

            //else if (IndexStoreType == IndexStoreType.EmbbededElasticSearch)
            //{
            //    var configSettings = appSettings.GetSection("embeddedElasticSearchIndexStoreSettings");
            //    this.EmbeddedElasticSearchIndexStoreSettings = new EmbeddedElasticSearchIndexStoreSettings(configSettings, (str) =>
            //    {
            //        if (str.IsTrimmedStringNotNullOrEmpty() && str.Contains(Strings.Config.ConfigPath))
            //        {
            //            str = str.Replace(Strings.Config.ConfigPath, FileUtils.GetFileDirectory(configLocation));
            //            str = Path.GetFullPath(new Uri(str).LocalPath);
            //        }
            //        return str;
            //    });
            //}
            else if (IndexStoreType == IndexStoreType.RaptorDB)
            {
                var configSettings = appSettings.GetSection(StringConstants.Config.RaptorDBIndexStoreSettings);
                this.RaptorDBIndexStoreSettings = new RaptorDBIndexStoreSettings(configSettings, (str) =>
                {
                    if (str.IsTrimmedStringNotNullOrEmpty() && str.Contains(Strings.Config.ConfigPath))
                    {
                        str = str.Replace(Strings.Config.ConfigPath, FileUtils.GetFileDirectory(configLocation));
                        str = Path.GetFullPath(new Uri(str).LocalPath);
                    }
                    return(str);
                });
            }
            else if (IndexStoreType == IndexStoreType.MongoDB)
            {
                var configSettings = appSettings.GetSection("mongoDBIndexStoreSettings");
                this.MongoDBIndexStoreSettings = new MongoDBIndexStoreSettings(configSettings);
            }
            else
            {
                throw new Exception("Index Store Type is not configured");
            }
        }
Exemple #42
0
 public void ServiceCollectionExtentionMethodsTestsSetup()
 {
     _serviceCollection    = new ServiceCollection();
     _configurationBuilder = new ConfigurationBuilder();
 }
Exemple #43
0
        public static void Main(string[] args)
        {
            Args = args;

            Console.WriteLine();
            Console.WriteLine("ASP.NET Core Benchmarks");
            Console.WriteLine("-----------------------");

            Console.WriteLine($"Current directory: {Directory.GetCurrentDirectory()}");
            Console.WriteLine($"AspNetCore location: {typeof(IWebHostBuilder).GetTypeInfo().Assembly.Location}");
            Console.WriteLine($"AspNetCore version: {typeof(IWebHostBuilder).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion}");

            Console.WriteLine($".NET Runtime location: {typeof(object).GetTypeInfo().Assembly.Location}");
            Console.WriteLine($".NET Runtime version: {typeof(object).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion}");

            Console.WriteLine($"Environment.ProcessorCount: {Environment.ProcessorCount}");

            BenchmarksEventSource.MeasureAspNetVersion();
            BenchmarksEventSource.MeasureNetCoreAppVersion();

            var config = new ConfigurationBuilder()
                         .AddJsonFile("hosting.json", optional: true)
                         .AddEnvironmentVariables(prefix: "ASPNETCORE_")
                         .AddCommandLine(args)
                         .Build();

            Server = config["server"] ?? "Kestrel";

            Protocol = config["protocol"] ?? "";

            var webHostBuilder = new WebHostBuilder()
                                 .UseContentRoot(Directory.GetCurrentDirectory())
                                 .UseConfiguration(config)
                                 .UseStartup <Startup>()
                                 .ConfigureLogging(loggerFactory =>
            {
                if (Enum.TryParse(config["LogLevel"], out LogLevel logLevel))
                {
                    Console.WriteLine($"Console Logging enabled with level '{logLevel}'");
                    loggerFactory.AddConsole().SetMinimumLevel(logLevel);
                }
            })
                                 .ConfigureServices(services => services
                                                    .AddSingleton(new ConsoleArgs(args))
                                                    .AddSingleton <IScenariosConfiguration, ConsoleHostScenariosConfiguration>()
                                                    .AddSingleton <Scenarios>()
                                                    .Configure <LoggerFilterOptions>(options =>
            {
#if NETCOREAPP3_0 || NETCOREAPP3_1 || NETCOREAPP5_0 || NET5_0
                if (Boolean.TryParse(config["DisableScopes"], out var disableScopes) && disableScopes)
                {
                    Console.WriteLine($"LoggerFilterOptions.CaptureScopes = false");
                    options.CaptureScopes = false;
                }
#endif
            })
                                                    )
                                 .UseDefaultServiceProvider(
                (context, options) => options.ValidateScopes = context.HostingEnvironment.IsDevelopment());

            bool?threadPoolDispatching = null;

            if (String.Equals(Server, "Kestrel", StringComparison.OrdinalIgnoreCase))
            {
                webHostBuilder = webHostBuilder.UseKestrel(options =>
                {
                    var urls = config["urls"] ?? config["server.urls"];

                    if (!string.IsNullOrEmpty(urls))
                    {
                        foreach (var value in urls.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            Listen(options, config, value);
                        }
                    }
                    else
                    {
                        Listen(options, config, "http://localhost:5000/");
                    }
#if !NETCOREAPP3_0 && !NETCOREAPP3_1 && !NETCOREAPP5_0 && !NET5_0
                    var kestrelThreadPoolDispatchingValue = config["KestrelThreadPoolDispatching"];
                    if (kestrelThreadPoolDispatchingValue != null)
                    {
                        if (bool.Parse(kestrelThreadPoolDispatchingValue))
                        {
                            options.ApplicationSchedulingMode = SchedulingMode.ThreadPool;
                        }
                        else
                        {
                            options.ApplicationSchedulingMode = SchedulingMode.Inline;
                        }
                    }
#endif
                });

                var threadCount      = GetThreadCount(config);
                var kestrelTransport = config["KestrelTransport"];

                if (threadPoolDispatching == false || string.Equals(kestrelTransport, "Libuv", StringComparison.OrdinalIgnoreCase))
                {
                    webHostBuilder.UseLibuv(options =>
                    {
                        if (threadCount > 0)
                        {
                            options.ThreadCount = threadCount;
                        }
                        else if (threadPoolDispatching == false)
                        {
                            // If thread pool dispatching is explicitly set to false
                            // and the thread count wasn't specified then use 2 * number of logical cores
                            options.ThreadCount = Environment.ProcessorCount * 2;
                        }

                        Console.WriteLine($"Using Libuv with {options.ThreadCount} threads");
                    });
                }
                else if (string.Equals(kestrelTransport, "Sockets", StringComparison.OrdinalIgnoreCase))
                {
                    webHostBuilder.UseSockets(socketOptions =>
                    {
                        if (threadCount > 0)
                        {
                            socketOptions.IOQueueCount = threadCount;
                        }

                        Console.WriteLine($"Using Sockets with {socketOptions.IOQueueCount} threads");
                    });
                }
                else if (string.IsNullOrEmpty(kestrelTransport))
                {
                    throw new InvalidOperationException($"Transport must be specified");
                }
                else
                {
                    throw new InvalidOperationException($"Unknown transport {kestrelTransport}");
                }

                webHostBuilder.UseSetting(WebHostDefaults.ServerUrlsKey, string.Empty);
            }
            else if (String.Equals(Server, "HttpSys", StringComparison.OrdinalIgnoreCase))
            {
                webHostBuilder = webHostBuilder.UseHttpSys();
            }
#if NETCOREAPP2_2 || NETCOREAPP3_0 || NETCOREAPP3_1 || NETCOREAPP5_0 || NET5_0
            else if (String.Equals(Server, "IISInProcess", StringComparison.OrdinalIgnoreCase))
            {
                webHostBuilder = webHostBuilder.UseIIS();
            }
#endif
            else if (String.Equals(Server, "IISOutOfProcess", StringComparison.OrdinalIgnoreCase))
            {
                webHostBuilder = webHostBuilder.UseKestrel().UseIISIntegration();
            }
            else
            {
                throw new InvalidOperationException($"Unknown server value: {Server}");
            }

            var webHost = webHostBuilder.Build();

            Console.WriteLine($"Using server {Server}");
            Console.WriteLine($"Server GC is currently {(GCSettings.IsServerGC ? "ENABLED" : "DISABLED")}");

            var nonInteractiveValue = config["nonInteractive"];
            if (nonInteractiveValue == null || !bool.Parse(nonInteractiveValue))
            {
                StartInteractiveConsoleThread();
            }

            webHost.Run();
        }
Exemple #44
0
        public static async Task <bool> MainAsync(bool test = false)
        {
            bool                  success = true;
            Exception             toThrow = null;
            IConfigurationBuilder builder = new ConfigurationBuilder()
                                            .SetBasePath(Directory.GetCurrentDirectory())
                                            .AddJsonFile("appsettings.json")
                                            .AddJsonFile("appsettings.test.json", optional: true);
            IConfiguration configuration = builder.Build();

            // ==== Client constants ====
            var tenantId    = configuration["TenantId"];
            var namespaceId = configuration["NamespaceId"];
            var resource    = configuration["Resource"];
            var clientId    = configuration["ClientId"];
            var clientKey   = configuration["ClientKey"];

            // ==== Metadata IDs ====
            string streamId          = "SampleStream";
            string streamIdSecondary = "SampleStream_Secondary";
            string streamIdCompound  = "SampleStream_Compound";

            string typeId             = "SampleType";
            string targetTypeId       = "SampleType_Target";
            string targetIntTypeId    = "SampleType_TargetInt";
            string autoStreamViewId   = "SampleAutoStreamView";
            string manualStreamViewId = "SampleManualStreamView";
            string compoundTypeId     = "SampleType_Compound";

            var uriResource = new Uri(resource);
            // Step 1
            // Get Sds Services to communicate with server
            AuthenticationHandler authenticationHandler = new AuthenticationHandler(uriResource, clientId, clientKey);

            SdsService sdsService      = new SdsService(new Uri(resource), authenticationHandler);
            var        metadataService = sdsService.GetMetadataService(tenantId, namespaceId);
            var        dataService     = sdsService.GetDataService(tenantId, namespaceId);
            var        tableService    = sdsService.GetTableService(tenantId, namespaceId);

            // LoggerCallbackHandler.UseDefaultLogging = false;


            Console.WriteLine(@"-------------------------------------------------------------");
            Console.WriteLine(@"  _________    .___           _______  ______________________");
            Console.WriteLine(@" /   _____/  __| _/______     \      \ \_   _____/\__    ___/");
            Console.WriteLine(@" \_____  \  / __ |/  ___/     /   |   \ |    __)_   |    |   ");
            Console.WriteLine(@" /        \/ /_/ |\___ \     /    |    \|        \  |    |   ");
            Console.WriteLine(@"/_______  /\____ /____  > /\ \____|__  /_______  /  |____|   ");
            Console.WriteLine(@"        \/      \/    \/  \/         \/        \/            ");
            Console.WriteLine(@"-------------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine($"Sds endpoint at {resource}");
            Console.WriteLine();

            try
            {
                // Step 2
                // create an SdsType
                Console.WriteLine("Creating an SdsType");
                SdsType type = SdsTypeBuilder.CreateSdsType <WaveData>();
                type.Id = typeId;
                type    = await metadataService.GetOrCreateTypeAsync(type);

                // Step 3
                // create an SdsStream
                Console.WriteLine("Creating an SdsStream");
                var stream = new SdsStream
                {
                    Id          = streamId,
                    Name        = "Wave Data Sample",
                    TypeId      = type.Id,
                    Description = "This is a sample SdsStream for storing WaveData type measurements"
                };
                stream = await metadataService.GetOrCreateStreamAsync(stream);

                // Step 4
                // insert data
                Console.WriteLine("Inserting data");

                // insert a single event
                var wave = GetWave(0, 200, 2);
                await dataService.InsertValueAsync(stream.Id, wave);

                // insert a list of events
                var waves = new List <WaveData>();
                for (var i = 2; i <= 18; i += 2)
                {
                    waves.Add(GetWave(i, 200, 2));
                }
                await dataService.InsertValuesAsync(stream.Id, waves);

                // Step 5
                // get last event
                Console.WriteLine("Getting latest event");
                var latest = await dataService.GetLastValueAsync <WaveData>(streamId);

                Console.WriteLine(latest.ToString());
                Console.WriteLine();

                // get all events
                Console.WriteLine("Getting all events");
                var allEvents = (List <WaveData>) await dataService.GetWindowValuesAsync <WaveData>(streamId, "0", "180");

                Console.WriteLine($"Total events found: {allEvents.Count}");
                foreach (var evnt in allEvents)
                {
                    Console.WriteLine(evnt.ToString());
                }
                Console.WriteLine();

                // Step 6
                //Step2 Getting all events in table format with headers.
                var tableEvents = await tableService.GetWindowValuesAsync(stream.Id, "0", "180");

                Console.WriteLine("Getting table events");
                foreach (var evnt in tableEvents.Rows)
                {
                    Console.WriteLine(String.Join(",", evnt.ToArray()));
                }
                Console.WriteLine();

                // Step 7
                // update events
                Console.WriteLine("Updating events");

                // update one event
                var updatedWave = UpdateWave(allEvents.First(), 4);
                await dataService.UpdateValueAsync(stream.Id, updatedWave);

                // update all events, adding ten more
                var updatedCollection = new List <WaveData>();
                for (int i = 2; i < 40; i = i + 2)
                {
                    updatedCollection.Add(GetWave(i, 400, 4));
                }
                await dataService.UpdateValuesAsync(stream.Id, updatedCollection);

                allEvents = (List <WaveData>) await dataService.GetWindowValuesAsync <WaveData>(stream.Id, "0", "180");

                Console.WriteLine("Getting updated events");
                Console.WriteLine($"Total events found: {allEvents.Count}");

                foreach (var evnt in allEvents)
                {
                    Console.WriteLine(evnt.ToString());
                }
                Console.WriteLine();

                // Step 8
                // replacing events
                Console.WriteLine("Replacing events");

                // replace one event
                var replaceEvent = allEvents.First();
                replaceEvent.Sin = 0.717;
                replaceEvent.Cos = 0.717;
                replaceEvent.Tan = Math.Sqrt(2 * (0.717 * 0.717));

                await dataService.ReplaceValueAsync <WaveData>(streamId, replaceEvent);

                // replace all events
                foreach (var evnt in allEvents)
                {
                    evnt.Sin = 5.0 / 2;
                    evnt.Cos = 5 * Math.Sqrt(3) / 2;
                    evnt.Tan = 5 / Math.Sqrt(3);
                }

                await dataService.ReplaceValuesAsync <WaveData>(streamId, allEvents);

                Console.WriteLine("Getting replaced events");
                var replacedEvents = (List <WaveData>) await dataService.GetWindowValuesAsync <WaveData>(streamId, "0", "180");

                Console.WriteLine($"Total events found: {replacedEvents.Count}");
                foreach (var evnt in replacedEvents)
                {
                    Console.WriteLine(evnt.ToString());
                }
                Console.WriteLine();

                // Step 9
                // Property Overrides
                Console.WriteLine("Sds can interpolate or extrapolate data at an index location where data does not explicitly exist:");
                Console.WriteLine();

                // We will retrieve three events using the default behavior, Continuous
                var retrieved = await dataService
                                .GetRangeValuesAsync <WaveData>(stream.Id, "1", 3, SdsBoundaryType.ExactOrCalculated);

                Console.WriteLine("Default (Continuous) requesting data starting at index location '1', where we have not entered data, Sds will interpolate a value for this property and then return entered values:");
                foreach (var value in retrieved)
                {
                    Console.WriteLine(value.ToString());
                }
                Console.WriteLine();


                var retrievedInterpolated = await dataService
                                            .GetValuesAsync <WaveData>(stream.Id, "5", "32", 4);

                Console.WriteLine(" Sds will interpolate a value for each index asked for (5,14,23,32):");
                foreach (var value in retrievedInterpolated)
                {
                    Console.WriteLine(value.ToString());
                }
                Console.WriteLine();

                // Step 10
                // We will retrieve events filtered to only get the ones where the radians are less than 50.  Note, this can be done on index properties too.

                var retrievedInterpolatedFiltered = (await dataService.GetWindowFilteredValuesAsync <WaveData>(stream.Id, "0", "180", SdsBoundaryType.ExactOrCalculated, "Radians lt 50"));
                Console.WriteLine(" Sds will only return the values where the radains are less than 50:");
                foreach (var value in retrievedInterpolatedFiltered)
                {
                    Console.WriteLine(value.ToString());
                }
                Console.WriteLine();


                // Step 11
                // create a Discrete stream PropertyOverride indicating that we do not want Sds to calculate a value for Radians and update our stream
                var propertyOverride = new SdsStreamPropertyOverride()
                {
                    SdsTypePropertyId = "Radians",
                    InterpolationMode = SdsInterpolationMode.Discrete
                };
                var propertyOverrides = new List <SdsStreamPropertyOverride>()
                {
                    propertyOverride
                };

                // update the stream
                stream.PropertyOverrides = propertyOverrides;
                await metadataService.CreateOrUpdateStreamAsync(stream);

                retrieved = await dataService
                            .GetRangeValuesAsync <WaveData>(stream.Id, "1", 3, SdsBoundaryType.ExactOrCalculated);

                Console.WriteLine("We can override this behavior on a property by property basis, here we override the Radians property instructing Sds not to interpolate.");
                Console.WriteLine("Sds will now return the default value for the data type:");

                foreach (var value in retrieved)
                {
                    Console.WriteLine(value.ToString());
                }
                Console.WriteLine();


                // Step 12
                // StreamViews
                Console.WriteLine("SdsStreamViews");

                // create target types
                var targetType = SdsTypeBuilder.CreateSdsType <WaveDataTarget>();
                targetType.Id = targetTypeId;

                var targetIntType = SdsTypeBuilder.CreateSdsType <WaveDataInteger>();
                targetIntType.Id = targetIntTypeId;

                await metadataService.GetOrCreateTypeAsync(targetType);

                await metadataService.GetOrCreateTypeAsync(targetIntType);

                // create StreamViews
                var autoStreamView = new SdsStreamView()
                {
                    Id           = autoStreamViewId,
                    SourceTypeId = typeId,
                    TargetTypeId = targetTypeId
                };

                // create explicit mappings
                var vp1 = new SdsStreamViewProperty()
                {
                    SourceId = "Order", TargetId = "OrderTarget"
                };
                var vp2 = new SdsStreamViewProperty()
                {
                    SourceId = "Sin", TargetId = "SinInt"
                };
                var vp3 = new SdsStreamViewProperty()
                {
                    SourceId = "Cos", TargetId = "CosInt"
                };
                var vp4 = new SdsStreamViewProperty()
                {
                    SourceId = "Tan", TargetId = "TanInt"
                };

                var manualStreamView = new SdsStreamView()
                {
                    Id           = manualStreamViewId,
                    SourceTypeId = typeId,
                    TargetTypeId = targetIntTypeId,
                    Properties   = new List <SdsStreamViewProperty>()
                    {
                        vp1, vp2, vp3, vp4
                    }
                };

                await metadataService.CreateOrUpdateStreamViewAsync(autoStreamView);

                await metadataService.CreateOrUpdateStreamViewAsync(manualStreamView);

                Console.WriteLine("Here is some of our data as it is stored on the server:");
                foreach (var evnt in retrieved)
                {
                    Console.WriteLine($"Sin: {evnt.Sin}, Cos: {evnt.Cos}, Tan {evnt.Tan}");
                }
                Console.WriteLine();

                // get autoStreamView data
                var autoStreamViewData = await dataService.GetRangeValuesAsync <WaveDataTarget>(stream.Id, "1", 3, SdsBoundaryType.ExactOrCalculated, autoStreamViewId);

                Console.WriteLine("Specifying a StreamView with an SdsType of the same shape returns values that are automatically mapped to the target SdsType's properties:");

                foreach (var value in autoStreamViewData)
                {
                    Console.WriteLine($"SinTarget: {value.SinTarget} CosTarget: {value.CosTarget} TanTarget: {value.TanTarget}");
                }
                Console.WriteLine();

                // get manualStreamView data
                Console.WriteLine("SdsStreamViews can also convert certain types of data, here we return integers where the original values were doubles:");
                var manualStreamViewData = await dataService.GetRangeValuesAsync <WaveDataInteger>(stream.Id, "1", 3, SdsBoundaryType.ExactOrCalculated, manualStreamViewId);

                foreach (var value in manualStreamViewData)
                {
                    Console.WriteLine($"SinInt: {value.SinInt} CosInt: {value.CosInt} TanInt: {value.TanInt}");
                }
                Console.WriteLine();

                // get SdsStreamViewMap
                Console.WriteLine("We can query Sds to return the SdsStreamViewMap for our SdsStreamView, here is the one generated automatically:");
                var autoStreamViewMap = await metadataService.GetStreamViewMapAsync(autoStreamViewId);

                PrintStreamViewMapProperties(autoStreamViewMap);

                Console.WriteLine("Here is our explicit mapping, note SdsStreamViewMap will return all properties of the Source Type, even those without a corresponding Target property:");
                var manualStreamViewMap = await metadataService.GetStreamViewMapAsync(manualStreamViewId);

                PrintStreamViewMapProperties(manualStreamViewMap);

                // Step 13
                // Update Stream Type based on SdsStreamView
                Console.WriteLine("We will now update the stream type based on the streamview");

                var firstVal = await dataService.GetFirstValueAsync <WaveData>(stream.Id);

                await metadataService.UpdateStreamTypeAsync(stream.Id, autoStreamViewId);

                var newStream = await metadataService.GetStreamAsync(stream.Id);

                var firstValUpdated = await dataService.GetFirstValueAsync <WaveDataTarget>(stream.Id);

                Console.WriteLine($"The new type id {newStream.TypeId} compared to the original one {stream.TypeId}.");
                Console.WriteLine($"The new type value {firstValUpdated.ToString()} compared to the original one {firstVal.ToString()}.");

                // Step 14
                // Show filtering on Type, works the same as filtering on Streams

                var types = await metadataService.GetTypesAsync("");

                var typesFiltered = await metadataService.GetTypesAsync("", "contains(Id, 'Target')");

                Console.WriteLine($"The number of types returned without filtering: {types.Count()}.  With filtering {typesFiltered.Count()}.");

                // Step 15
                // tags and metadata
                Console.WriteLine("Let's add some Tags and Metadata to our stream:");
                var tags = new List <string> {
                    "waves", "periodic", "2018", "validated"
                };
                var metadata = new Dictionary <string, string>()
                {
                    { "Region", "North America" }, { "Country", "Canada" }, { "Province", "Quebec" }
                };

                await metadataService.UpdateStreamTagsAsync(streamId, tags);

                await metadataService.UpdateStreamMetadataAsync(streamId, metadata);

                tags = (List <string>) await metadataService.GetStreamTagsAsync(streamId);

                Console.WriteLine();
                Console.WriteLine($"Tags now associated with {streamId}:");
                foreach (var tag in tags)
                {
                    Console.WriteLine(tag);
                }
                Console.WriteLine();
                Console.WriteLine($"Metadata now associated with {streamId}:");
                Console.WriteLine("Metadata key Region: " + await metadataService.GetStreamMetadataValueAsync(streamId, "Region"));
                Console.WriteLine("Metadata key Country: " + await metadataService.GetStreamMetadataValueAsync(streamId, "Country"));
                Console.WriteLine("Metadata key Province: " + await metadataService.GetStreamMetadataValueAsync(streamId, "Province"));

                Console.WriteLine();

                // Step 16
                // delete values
                Console.WriteLine("Deleting values from the SdsStream");

                // delete one event
                await dataService.RemoveValueAsync(stream.Id, 0);

                // delete all events
                await dataService.RemoveWindowValuesAsync(stream.Id, 1, 200);

                retrieved = await dataService.GetWindowValuesAsync <WaveData>(stream.Id, "0", "200");

                if (retrieved.ToList <WaveData>().Count == 0)
                {
                    Console.WriteLine("All values deleted successfully!");
                }
                Console.WriteLine();

                // Step 17
                // Adding a new stream with a secondary index.
                Console.WriteLine("Adding a stream with a secondary index.");

                SdsStreamIndex measurementIndex = new SdsStreamIndex()
                {
                    SdsTypePropertyId = type.Properties.First(p => p.Id.Equals("Radians")).Id
                };

                SdsStream secondary = new SdsStream()
                {
                    Id      = streamIdSecondary,
                    TypeId  = type.Id,
                    Indexes = new List <SdsStreamIndex>()
                    {
                        measurementIndex
                    }
                };

                secondary = await metadataService.GetOrCreateStreamAsync(secondary);

                Console.WriteLine($"Secondary indexes on streams. {stream.Id}:{stream.Indexes?.Count()}. {secondary.Id}:{secondary.Indexes.Count()}. ");
                Console.WriteLine();


                // Modifying an existing stream with a secondary index.
                Console.WriteLine("Modifying a stream to have a secondary index.");


                stream = await metadataService.GetStreamAsync(stream.Id);

                type = await metadataService.GetTypeAsync(stream.TypeId);


                SdsStreamIndex measurementTargetIndex = new SdsStreamIndex()
                {
                    SdsTypePropertyId = type.Properties.First(p => p.Id.Equals("RadiansTarget")).Id
                };

                stream.Indexes = new List <SdsStreamIndex>()
                {
                    measurementTargetIndex
                };

                await metadataService.CreateOrUpdateStreamAsync(stream);

                stream = await metadataService.GetStreamAsync(stream.Id);


                // Modifying an existing stream to remove the secondary index
                Console.WriteLine("Removing a secondary index from a stream.");

                secondary.Indexes = null;

                await metadataService.CreateOrUpdateStreamAsync(secondary);

                secondary = await metadataService.GetStreamAsync(secondary.Id);

                Console.WriteLine($"Secondary indexes on streams. {stream.Id}:{stream.Indexes?.Count()}. {secondary.Id}:{secondary.Indexes?.Count()}. ");
                Console.WriteLine();



                // Step 18
                // Adding Compound Index Type
                Console.WriteLine("Creating an SdsType with a compound index");
                SdsType typeCompound = SdsTypeBuilder.CreateSdsType <WaveDataCompound>();
                typeCompound.Id = compoundTypeId;
                typeCompound    = await metadataService.GetOrCreateTypeAsync(typeCompound);

                // create an SdsStream
                Console.WriteLine("Creating an SdsStream off of type with compound index");
                var streamCompound = new SdsStream
                {
                    Id          = streamIdCompound,
                    Name        = "Wave Data Sample",
                    TypeId      = typeCompound.Id,
                    Description = "This is a sample SdsStream for storing WaveData type measurements"
                };
                streamCompound = await metadataService.GetOrCreateStreamAsync(streamCompound);

                // Step 19
                // insert compound data
                Console.WriteLine("Inserting data");
                await dataService.InsertValueAsync(streamCompound.Id, GetWaveMultiplier(1, 10));

                await dataService.InsertValueAsync(streamCompound.Id, GetWaveMultiplier(2, 2));

                await dataService.InsertValueAsync(streamCompound.Id, GetWaveMultiplier(3, 1));

                await dataService.InsertValueAsync(streamCompound.Id, GetWaveMultiplier(10, 3));

                await dataService.InsertValueAsync(streamCompound.Id, GetWaveMultiplier(10, 8));

                await dataService.InsertValueAsync(streamCompound.Id, GetWaveMultiplier(10, 10));

                var latestCompound = await dataService.GetLastValueAsync <WaveDataCompound>(streamCompound.Id);

                var firstCompound = await dataService.GetFirstValueAsync <WaveDataCompound>(streamCompound.Id);

                var data = await dataService.GetWindowValuesAsync <WaveDataCompound, int, int>(streamCompound.Id, Tuple.Create(2, 1), Tuple.Create(10, 8));

                Console.WriteLine($"First data: {firstCompound.ToString()}.  Latest data: {latestCompound.ToString()}.");

                Console.WriteLine();

                Console.WriteLine("Window Data:");

                foreach (var evnt in data)
                {
                    Console.WriteLine(evnt.ToString());
                }
            }
            catch (Exception ex)
            {
                success = false;
                Console.WriteLine(ex.Message);
                toThrow = ex;
            }
            finally
            {
                //step 20
                Console.WriteLine("Cleaning up");
                // Delete the stream, types and streamViews making sure
                Console.WriteLine("Deleting stream");
                await RunInTryCatch(metadataService.DeleteStreamAsync, streamId);
                await RunInTryCatch(metadataService.DeleteStreamAsync, streamIdSecondary);
                await RunInTryCatch(metadataService.DeleteStreamAsync, streamIdCompound);

                Console.WriteLine("Deleting streamViews");
                await RunInTryCatch(metadataService.DeleteStreamViewAsync, autoStreamViewId);
                await RunInTryCatch(metadataService.DeleteStreamViewAsync, manualStreamViewId);

                Console.WriteLine("Deleting types");
                await RunInTryCatch(metadataService.DeleteTypeAsync, typeId);
                await RunInTryCatch(metadataService.DeleteTypeAsync, compoundTypeId);
                await RunInTryCatch(metadataService.DeleteTypeAsync, targetTypeId);
                await RunInTryCatch(metadataService.DeleteTypeAsync, targetIntTypeId);

                Console.WriteLine("done");
                if (!test)
                {
                    Console.ReadKey();
                }
            }

            if (test && !success)
            {
                throw toThrow;
            }
            return(success);
        }
Exemple #45
0
        public static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddCommandLine(args)
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddEnvironmentVariables();

            Configuration = builder.Build();
            //IServiceCollection services = new ServiceCollection();

            Console.WriteLine("Hello World!");
            var service = new ServiceCollection();

            var dbkind = Configuration["Data:DefaultConnection:ConnectionDBString"];

            if (dbkind.Equals("sqlite"))
            {
                service.AddEntityFrameworkSqlite();
                service.AddDbContext <postgresContext>(options =>
                {
                    options.UseSqlite(Configuration["Data:DefaultConnection:ConnectionString"]);
                });
            }
            if (dbkind.Equals("sqlserver"))
            {
                service.AddEntityFrameworkSqlServer();
                service.AddDbContext <postgresContext>(options =>
                {
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]);
                });
            }
            if (dbkind.Equals("postgresql"))
            {
                service.AddEntityFrameworkNpgsql();
                service.AddDbContext <postgresContext>(options =>
                {
                    options.UseNpgsql(Configuration["Data:DefaultConnection:ConnectionString"]);
                });
            }
            if (dbkind.Equals("inmemory"))
            {
                service.AddEntityFrameworkInMemoryDatabase();
                service.AddDbContext <postgresContext>(options =>
                {
                    options.UseInMemoryDatabase();
                });
            }

            var serviceProvider = service.BuildServiceProvider();

            // Setup Databases
            using (var serviceScope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetService <postgresContext>();
                context.Database.EnsureCreated();
                //context.Database.EnsureDeleted();
                //context.Database.Migrate();
                //EnsureSeedData(serviceScope.ServiceProvider.GetService<CoreExampleContext>());
            }
        }
        public static void Run([QueueTrigger("EmailQueue", Connection = "EmailQueueConnection")] string myQueueItem,
                               [SendGrid(ApiKey = "SendgridApiKey")] out SendGridMessage message, ILogger log, ExecutionContext context)
        {
            try
            {
                var config = new ConfigurationBuilder()
                             .SetBasePath(context.FunctionAppDirectory)
                             .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                             .AddEnvironmentVariables()
                             .Build();

                AzureStorageAccount             = config["AzureStorageAccount"];
                AzureStorageConnectionSecretKey = config["AzureStorageConnectionSecretKey"];
                EmailTemplateContainer          = config["EmailTemplateContainer"];



                log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
                var emailObject = JsonConvert.DeserializeObject <OutgoingEmail>(myQueueItem);
                Azure.Storage.BlobStorage templateBlob = new Azure.Storage.BlobStorage(AzureStorageAccount, AzureStorageConnectionSecretKey, EmailTemplateContainer);

                // Azure.Storage.BlobStorage azureblobstorage = new Azure.Storage.BlobStorage(azureStorageAccountName, azureStorageAccountKey, azureContainerName);

                string blobpath = templateBlob._cloudBlobContainer.Uri + "/" + "emailRegistration.html";

                log.LogInformation($"Blob Path: {blobpath}");

                Uri uri = new Uri(blobpath, UriKind.Absolute);
                StorageCredentials configreaderstoragecredential = new StorageCredentials(AzureStorageAccount, AzureStorageConnectionSecretKey);
                CloudBlobClient    clb = new CloudBlobClient(uri, configreaderstoragecredential);

                var blobRefrence = clb.GetBlobReferenceFromServerAsync(uri).Result;

                var configuration = Helper.Azureblobhelper.DownloadBlockbBlob(uri, configreaderstoragecredential);

                if (configuration.Length > 0)
                {
                    log.LogInformation($"Blob Path: {blobpath}");
                }
                //{firstName} {lastName}

                log.LogInformation($"Blob Path: {emailObject.FirstName} and {emailObject.LastName}");

                string str       = configuration.Replace("{firstName}", emailObject.FirstName);
                string emailbody = str.Replace("{lastName}", emailObject.LastName);

                log.LogInformation($"emailbody body created");

                message = new SendGridMessage();
                message.AddTo(emailObject.EmailAddress);
                message.AddContent("text/html", emailbody);
                message.SetFrom(new EmailAddress("*****@*****.**"));
                message.SetSubject("Registration Confirmation email from notification system.");

                log.LogInformation($"execution done");
            }
            catch (Exception e)
            {
                log.LogInformation($"exception occoured {e.Message}");
                message = null;
            }
        }
Exemple #47
0
        public IJobAssembly Load(string jobsPath)
        {
            var dllFiles = Directory.GetFiles(jobsPath, "*.dll");

            var jobFilePath = "";

            foreach (var dllFile in dllFiles)
            {
                var tempAlc = new HostAssemblyLoadContext(dllFile);

                Assembly tempAssembly;
                using (var stream = File.OpenRead(dllFile))
                {
                    tempAssembly = tempAlc.LoadFromStream((Stream)stream);
                }

                var types    = tempAssembly.GetTypes();
                var jobClass = types.SingleOrDefault(x => x.GetInterfaces().Contains(typeof(IJob)));

                tempAlc.Unload();

                if (jobClass != null)
                {
                    jobFilePath = dllFile;
                    break;
                }
            }

            if (string.IsNullOrEmpty(jobFilePath))
            {
                return(null);
            }

            var alc        = new HostAssemblyLoadContext(jobFilePath);
            var alcWeakRef = new WeakReference(alc);

            Assembly assembly;

            using (var stream = File.OpenRead(jobFilePath))
            {
                assembly = alc.LoadFromStream((Stream)stream);
            }

            var jobType = assembly.GetTypes().SingleOrDefault(x => x.GetInterfaces().Contains(typeof(IJob)));

            if (jobType == null)
            {
                return(null);
            }

            var containerBuilder = new ContainerBuilder();

            var configurationBuilder = new ConfigurationBuilder()
                                       .SetBasePath(jobsPath)
                                       .AddJsonFile($"appsettings.json", true, true)
                                       .AddEnvironmentVariables();

            foreach (var appSettingFile in Directory.GetFiles(jobsPath, "appsettings.*.json"))
            {
                configurationBuilder.AddJsonFile(Path.GetFileName(appSettingFile));
            }
            var config = configurationBuilder.Build();

            containerBuilder.RegisterInstance((ConfigurationRoot)config);

            MethodInfo methodInfo = jobType.GetMethod("Register");

            if (methodInfo == null)
            {
                return(null);
            }

            methodInfo.Invoke(null, new object[] { containerBuilder });
            var container   = containerBuilder.Build();
            var jobInstance = (IJob)Instance(jobType, container);

            var jobAssembly = new JobAssembly()
            {
                Instance = jobInstance,
                UniqueId = Guid.NewGuid(),
                Assembly = assembly,
                HostAssemblyLoadContext = alc,
                WeakReference           = alcWeakRef,
                JobFullPath             = jobFilePath,
                FileMD5Hash             = _fileHelper.CalculateMD5(jobFilePath)
            };

            return(jobAssembly);
        }
Exemple #48
0
        public static async Task Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, ILogger log, ExecutionContext context)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            //Who did embed this? Oh that was me!
            List <string> rssEndPoints = new()
            {
                "https://daron.blog/index.xml",
                "http://ozaksut.com/feed/",
                "http://cihanyakar.com/rss",
                "https://feeds.feedburner.com/ilkayilknur"
            };

            List <FeedItem> feedItems = new();

            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();
            var storageConnectionString = config["AzureWebJobsStorage"];

            List <Task <Feed> > allDownloads = new();

            foreach (var rssEndPoint in rssEndPoints)
            {
                allDownloads.Add(FeedReader.ReadAsync(rssEndPoint));
            }
            Feed[] feeds = await Task.WhenAll(allDownloads);

            //Feeling proud!
            string FindAuthor(string Link)
            {
                if (Link.Contains("ozaksut"))
                {
                    return("Yiğit Özaksüt");
                }
                if (Link.Contains("daron"))
                {
                    return("Daron Yöndem");
                }
                if (Link.Contains("cihan"))
                {
                    return("Cihan Yakar");
                }
                if (Link.Contains("ilkay"))
                {
                    return("İlkay İlknur");
                }
                return(string.Empty);
            }

            var latestThreePosts = feeds.SelectMany(x => x.Items).
                                   OrderByDescending(x => x.PublishingDate).
                                   Take(3).
                                   Select(x => new { Author = FindAuthor(x.Link), x.Title, Url = x.Link });

            var jsonOutput = JsonConvert.SerializeObject(latestThreePosts);

            if (CloudStorageAccount.TryParse(storageConnectionString, out var storageAccount))
            {
                CloudBlobClient cloudBlobClient    = storageAccount.CreateCloudBlobClient();
                var             cloudBlobContainer = cloudBlobClient.GetContainerReference("json");
                CloudBlockBlob  cloudBlockBlob     = cloudBlobContainer.GetBlockBlobReference("lastposts.json");
                cloudBlockBlob.Properties.ContentType = "application/json";
                await cloudBlockBlob.UploadTextAsync(jsonOutput);
            }
        }
    }
Exemple #49
0
        private static void Main(string[] args)
        {
            Stopwatch stopWatch = Stopwatch.StartNew();

            // Set up configuration sources.
            IConfigurationRoot configuration = new ConfigurationBuilder()
           .SetBasePath(Directory.GetCurrentDirectory())
           .AddJsonFile("appsettings.json", optional: false).Build();
            System.Console.ForegroundColor = ConsoleColor.White;

            Dictionary<DatabaseProvider, string> connectionStrings =
            configuration.GetSection("ConnectionStrings").GetChildren().ToDictionary(e => Enum.Parse<DatabaseProvider>(e.Key), e => e.Value);
            bool warmUp = true;

            System.Console.WriteLine("ORM Benchmark");

            System.Console.WriteLine("Warm Up: " + warmUp);
            System.Console.WriteLine("Connection Strings");
            Dictionary<DatabaseProvider, string> connectionStateToBenchamrk = connectionStrings
                //.Where(e => e.Key == DatabaseType.MySql)
                .ToDictionary(e => e.Key, e => e.Value);

            foreach (var item in connectionStateToBenchamrk)
            {
                System.Console.WriteLine($"{item.Key}: {item.Value}");
            }

            var singleTestIterations = 500;
            var benchmarker = new Benchmarker(connectionStateToBenchamrk, singleTestIterations);

            benchmarker.RegisterOrmExecuter<PureAdoExecuter>();
            benchmarker.RegisterOrmExecuter<DapperBufferedExecuter>();
            benchmarker.RegisterOrmExecuter<DapperFirstOrDefaultExecuter>();
            benchmarker.RegisterOrmExecuter<DapperContribExecuter>();

            benchmarker.RegisterOrmExecuter<DevExpressQueryExecuter>();

            benchmarker.RegisterOrmExecuter<PetaPocoExecuter>();
            benchmarker.RegisterOrmExecuter<PetaPocoFastExecuter>();
            benchmarker.RegisterOrmExecuter<PetaPocoFetchExecuter>();
            benchmarker.RegisterOrmExecuter<PetaPocoFetchFastExecuter>();

            benchmarker.RegisterOrmExecuter<EntityFrameworkExecuter>();
            benchmarker.RegisterOrmExecuter<EntityFrameworkNoTrackingExecuter>();

            benchmarker.RegisterOrmExecuter<OrmLiteExecuter>();
            benchmarker.RegisterOrmExecuter<OrmLiteNoQueryExecuter>();

            benchmarker.RegisterOrmExecuter<RepoDbExecuter>();
            benchmarker.RegisterOrmExecuter<RepoDbQueryExecuter>();

            benchmarker.RegisterOrmExecuter<InsightDatabaseExecuter>();

            benchmarker.RegisterOrmExecuter<OrmToolkitExecuter>();
            benchmarker.RegisterOrmExecuter<OrmToolkitNoQueryExecuter>();
            benchmarker.RegisterOrmExecuter<OrmToolkitTestExecuter>();

            benchmarker.RegisterOrmExecuter<SqlSugarExecuter>();
            benchmarker.RegisterOrmExecuter<SqlSugarQueryableExecuter>();

            benchmarker.RegisterOrmExecuter<NHibernateExecutor>();
            benchmarker.RegisterOrmExecuter<NHibernateSqlQueryExecutor>();

            var ver = Assembly.GetEntryAssembly()?.GetCustomAttribute<TargetFrameworkAttribute>()?.FrameworkName;
            System.Console.WriteLine(ver);

            try
            {
                benchmarker.Run(warmUp);
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("Exception occured: " + ex);
                LogError(ex);

                
                throw;
            }


#if DEBUG
            Console.WriteLine($"\nPerformance of select and map a row to a POCO object over {singleTestIterations} iterations:");
            ShowResults(benchmarker.Results, true);

            Console.WriteLine("\nPerformance of mapping 5000 rows to POCO objects in one iteration:");
            ShowResults(benchmarker.ResultsForAllItems);

            Console.WriteLine($"\nPerformance of select and map a row to a Dynamic object over {singleTestIterations} iterations:");
            ShowResults(benchmarker.ResultsForDynamicItem, true);

            Console.WriteLine("\nPerformance of mapping 5000 rows to Dynamic objects in one iteration:");
            ShowResults(benchmarker.ResultsForAllDynamicItems);
#elif RELEASE
            SaveResults(benchmarker, connectionStrings);
#endif

            stopWatch.Stop();
            System.Console.WriteLine($"Test take {stopWatch.ElapsedMilliseconds}");
        }
Exemple #50
0
        private IServiceCollection BuildCommonServices(out AggregateException hostingStartupErrors)
        {
            hostingStartupErrors = null;

            _options = new WebHostOptions(_config);

            if (!_options.PreventHostingStartup)
            {
                var exceptions = new List <Exception>();

                // Execute the hosting startup assemblies
                foreach (var assemblyName in _options.HostingStartupAssemblies)
                {
                    try
                    {
                        var assembly = Assembly.Load(new AssemblyName(assemblyName));

                        foreach (var attribute in assembly.GetCustomAttributes <HostingStartupAttribute>())
                        {
                            var hostingStartup = (IHostingStartup)Activator.CreateInstance(attribute.HostingStartupType);
                            hostingStartup.Configure(this);
                        }
                    }
                    catch (Exception ex)
                    {
                        // Capture any errors that happen during startup
                        exceptions.Add(new InvalidOperationException($"Startup assembly {assemblyName} failed to execute. See the inner exception for more details.", ex));
                    }
                }

                if (exceptions.Count > 0)
                {
                    hostingStartupErrors = new AggregateException(exceptions);
                }
            }

            var contentRootPath = ResolveContentRootPath(_options.ContentRootPath, AppContext.BaseDirectory);
            var applicationName = _options.ApplicationName;

            // Initialize the hosting environment
            _hostingEnvironment.Initialize(applicationName, contentRootPath, _options);
            _context.HostingEnvironment = _hostingEnvironment;

            var services = new ServiceCollection();

            services.AddSingleton(_hostingEnvironment);
            services.AddSingleton(_context);

            var builder = new ConfigurationBuilder()
                          .SetBasePath(_hostingEnvironment.ContentRootPath)
                          .AddInMemoryCollection(_config.AsEnumerable());

            foreach (var configureAppConfiguration in _configureAppConfigurationBuilderDelegates)
            {
                configureAppConfiguration(_context, builder);
            }

            var configuration = builder.Build();

            services.AddSingleton <IConfiguration>(configuration);
            _context.Configuration = configuration;

            var listener = new DiagnosticListener("Microsoft.AspNetCore");

            services.AddSingleton <DiagnosticListener>(listener);
            services.AddSingleton <DiagnosticSource>(listener);

            services.AddTransient <IApplicationBuilderFactory, ApplicationBuilderFactory>();
            services.AddTransient <IHttpContextFactory, HttpContextFactory>();
            services.AddScoped <IMiddlewareFactory, MiddlewareFactory>();
            services.AddOptions();
            services.AddLogging();

            // Conjure up a RequestServices
            services.AddTransient <IStartupFilter, AutoRequestServicesStartupFilter>();
            services.AddTransient <IServiceProviderFactory <IServiceCollection>, DefaultServiceProviderFactory>();

            // Ensure object pooling is available everywhere.
            services.AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>();

            if (!string.IsNullOrEmpty(_options.StartupAssembly))
            {
                try
                {
                    var startupType = StartupLoader.FindStartupType(_options.StartupAssembly, _hostingEnvironment.EnvironmentName);

                    if (typeof(IStartup).GetTypeInfo().IsAssignableFrom(startupType.GetTypeInfo()))
                    {
                        services.AddSingleton(typeof(IStartup), startupType);
                    }
                    else
                    {
                        services.AddSingleton(typeof(IStartup), sp =>
                        {
                            var hostingEnvironment = sp.GetRequiredService <IHostingEnvironment>();
                            var methods            = StartupLoader.LoadMethods(sp, startupType, hostingEnvironment.EnvironmentName);
                            return(new ConventionBasedStartup(methods));
                        });
                    }
                }
                catch (Exception ex)
                {
                    var capture = ExceptionDispatchInfo.Capture(ex);
                    services.AddSingleton <IStartup>(_ =>
                    {
                        capture.Throw();
                        return(null);
                    });
                }
            }

            foreach (var configureServices in _configureServicesDelegates)
            {
                configureServices(_context, services);
            }

            return(services);
        }
        public InitializerTestBase(DefaultProjectsConfiguration defaultProjectsConfiguration)
        {
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", false)
                                .AddJsonFile("appsettings.Local.json", optional: true, reloadOnChange: true)
                                .AddEnvironmentVariables()
                                .AddForgeAlternativeEnvironmentVariables()
                                .Build();

            IServiceCollection services = new ServiceCollection();

            services.AddHttpClient();
            var serviceProvider = services.BuildServiceProvider();

            ForgeConfiguration            forgeConfiguration = configuration.GetSection("Forge").Get <ForgeConfiguration>();
            IOptions <ForgeConfiguration> forgeConfigOptions = Options.Create(forgeConfiguration);

            var httpClientFactory = serviceProvider.GetRequiredService <IHttpClientFactory>();

            forgeOSS = new ForgeOSS(httpClientFactory, forgeConfigOptions, new NullLogger <ForgeOSS>());

            var httpMessageHandler = new ForgeHandler(Options.Create(forgeConfiguration))
            {
                InnerHandler = new HttpClientHandler()
            };
            var forgeService           = new ForgeService(new HttpClient(httpMessageHandler));
            var designAutomationClient = new DesignAutomationClient(forgeService);

            projectsBucketKey = Guid.NewGuid().ToString();

            localCache = new LocalCache();
            var bucketPrefixProvider = new BucketPrefixProvider(forgeConfigOptions, configuration);
            var resourceProvider     = new ResourceProvider(forgeConfigOptions, designAutomationClient, configuration, bucketPrefixProvider, projectsBucketKey);
            var postProcessing       = new PostProcessing(httpClientFactory, new NullLogger <PostProcessing>(), localCache, Options.Create(new ProcessingOptions()));
            var publisher            = new Publisher(designAutomationClient, new NullLogger <Publisher>(), resourceProvider, postProcessing);

            var appBundleZipPathsConfiguration = new AppBundleZipPaths
            {
                EmptyExe          = "../../../../WebApplication/AppBundles/EmptyExePlugin.bundle.zip",
                DrawingsList      = "../../../../WebApplication/AppBundles/DrawingsListPlugin.bundle.zip",
                CreateSVF         = "../../../../WebApplication/AppBundles/CreateSVFPlugin.bundle.zip",
                CreateThumbnail   = "../../../../WebApplication/AppBundles/CreateThumbnailPlugin.bundle.zip",
                ExtractParameters = "../../../../WebApplication/AppBundles/ExtractParametersPlugin.bundle.zip",
                UpdateParameters  = "../../../../WebApplication/AppBundles/UpdateParametersPlugin.bundle.zip",
                CreateSAT         = "../../../../WebApplication/AppBundles/SatExportPlugin.bundle.zip",
                CreateRFA         = "../../../../WebApplication/AppBundles/RFAExportPlugin.bundle.zip",
                CreateBOM         = "../../../../WebApplication/AppBundles/ExportBOMPlugin.bundle.zip",
                ExportDrawing     = "../../../../WebApplication/AppBundles/ExportDrawingAsPdfPlugin.bundle.zip",
                UpdateDrawings    = "../../../../WebApplication/AppBundles/UpdateDrawingsPlugin.bundle.zip"
            };
            IOptions <AppBundleZipPaths> appBundleZipPathsOptions = Options.Create(appBundleZipPathsConfiguration);

            var fdaClient = new FdaClient(publisher, appBundleZipPathsOptions);
            IOptions <DefaultProjectsConfiguration> defaultProjectsOptions = Options.Create(defaultProjectsConfiguration);
            var profileProvider   = new ProfileProvider(forgeOSS);
            var bucketKeyProvider = new LoggedInUserBucketKeyProvider(forgeConfigOptions, profileProvider, bucketPrefixProvider, resourceProvider);
            var userResolver      = new UserResolver(resourceProvider, forgeOSS, bucketKeyProvider, localCache, NullLogger <UserResolver> .Instance, profileProvider);
            var arranger          = new Arranger(httpClientFactory, userResolver);

            // TODO: linkGenerator should be mocked
            var dtoGenerator = new DtoGenerator(linkGenerator: null, localCache);
            var projectWork  = new ProjectWork(new NullLogger <ProjectWork>(), arranger, fdaClient, dtoGenerator, userResolver);

            var projectService = new ProjectService(new NullLogger <ProjectService>(), userResolver, projectWork);

            initializer = new Initializer(new NullLogger <Initializer>(), fdaClient,
                                          defaultProjectsOptions, projectWork, userResolver, localCache,
                                          projectService, bucketPrefixProvider);

            testFileDirectory = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()));
            httpClient        = new HttpClient();
        }
Exemple #52
0
        public static async System.Threading.Tasks.Task <HttpResponseMessage> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, TraceWriter log, ExecutionContext context)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();
            string          connectionString       = config.GetConnectionString("IoTHubConnectionString");
            string          deviceConfigurationUrl = Environment.GetEnvironmentVariable("DEVICE_CONFIG_LOCATION");
            RegistryManager manager = RegistryManager.CreateFromConnectionString(connectionString);
            // parse query parameter
            var    queryStrings       = req.GetQueryParameterDictionary();
            string deviceName         = "";
            string publishingUserName = "";
            string publishingPassword = "";

            queryStrings.TryGetValue("deviceName", out deviceName);
            queryStrings.TryGetValue("publishingUserName", out publishingUserName);
            queryStrings.TryGetValue("publishingPassword", out publishingPassword);
            Console.WriteLine("un " + publishingUserName);
            //Get function facade key
            var    base64Auth = Convert.ToBase64String(Encoding.Default.GetBytes($"{publishingUserName}:{publishingPassword}"));
            var    apiUrl     = new Uri($"https://{Environment.GetEnvironmentVariable("WEBSITE_CONTENTSHARE")}.scm.azurewebsites.net/api");
            var    siteUrl    = new Uri($"https://{Environment.GetEnvironmentVariable("WEBSITE_CONTENTSHARE")}.azurewebsites.net");
            string JWT;

            Console.WriteLine("api " + apiUrl);
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Basic {base64Auth}");

                var result = client.GetAsync($"{apiUrl}/functions/admin/token").Result;
                JWT = result.Content.ReadAsStringAsync().Result.Trim('"'); //get  JWT for call funtion key
            }
            string facadeKey = "";

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + JWT);

                string  jsonResult = client.GetAsync($"{siteUrl}/admin/host/keys").Result.Content.ReadAsStringAsync().Result;
                dynamic resObject  = JsonConvert.DeserializeObject(jsonResult);
                facadeKey = resObject.keys[0].value;
            }


            Device edgeGatewayDevice = new Device(deviceName);

            edgeGatewayDevice.Capabilities = new DeviceCapabilities()
            {
                IotEdge = true
            };
            await manager.AddDeviceAsync(edgeGatewayDevice);

            string json = "";

            //todo correct
            using (WebClient wc = new WebClient())
            {
                json = wc.DownloadString(deviceConfigurationUrl);
            }
            ConfigurationContent spec = JsonConvert.DeserializeObject <ConfigurationContent>(json);
            await manager.AddModuleAsync(new Module(deviceName, "LoRaWanNetworkSrvModule"));

            await manager.ApplyConfigurationContentOnDeviceAsync(deviceName, spec);

            Twin twin = new Twin();

            twin.Properties.Desired = new TwinCollection(@"{FacadeServerUrl:'" + String.Format("https://{0}.azurewebsites.net/api/", GetEnvironmentVariable("FACADE_HOST_NAME")) + "',FacadeAuthCode: " +
                                                         "'" + facadeKey + "'}");
            var remoteTwin = await manager.GetTwinAsync(deviceName);

            await manager.UpdateTwinAsync(deviceName, "LoRaWanNetworkSrvModule", twin, remoteTwin.ETag);

            bool deployEndDevice = false;

            Boolean.TryParse(Environment.GetEnvironmentVariable("DEPLOY_DEVICE"), out deployEndDevice);

            //This section will get deployed ONLY if the user selected the "deploy end device" options.
            //Information in this if clause, is for demo purpose only and should not be used for productive workloads.
            if (deployEndDevice)
            {
                Device endDevice = new Device("47AAC86800430028");
                await manager.AddDeviceAsync(endDevice);

                Twin endTwin = new Twin();
                endTwin.Tags = new TwinCollection(@"{AppEUI:'BE7A0000000014E2',AppKey:'8AFE71A145B253E49C3031AD068277A1',GatewayID:''," +
                                                  "SensorDecoder:'DecoderValueSensor'}");

                var endRemoteTwin = await manager.GetTwinAsync(deviceName);

                await manager.UpdateTwinAsync("47AAC86800430028", endTwin, endRemoteTwin.ETag);
            }


            var template = @"{'$schema': 'https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#', 'contentVersion': '1.0.0.0', 'parameters': {}, 'variables': {}, 'resources': []}";
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

            Console.WriteLine(template);

            response.Content = new StringContent(template, System.Text.Encoding.UTF8, "application/json");

            return(response);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Sleeping for rabbitmq");

            // waiting for rabbit to up and running
            Task.Delay(20000).Wait();

            Console.WriteLine("Deliveggie server Running!");

            //building configurations
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");
            var configuration = builder.Build();

            MongoDbHelper mongoDbHelper = new MongoDbHelper(configuration);

            Func <ProductRequest, ProductsResponse> ProductList = request =>
            {
                try
                {
                    Console.WriteLine($"Message recieved for ProductList {request.Id }");
                    return(mongoDbHelper.GetProducts(request));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("ProductsResponse Error : " + ex.Message);
                    return(new ProductsResponse {
                    });
                }
            };

            Func <ProductDetailsRequest, ProductDetailsResponse> ProductDetails = request =>
            {
                try
                {
                    Console.WriteLine($"Message recieved for ProductDetails {request.Id }");
                    return(mongoDbHelper.GetProductDetails(request.Id));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("ProductDetailsResponse Error : " + ex.Message);
                    return(new ProductDetailsResponse {
                    });
                }
            };

            try
            {
                string connectionString = configuration["rabbittMQConnectionstring"];
                ////Console.WriteLine($"rabbittMQConnectionstring : {connectionString}");
                using (var bus = RabbitHutch.CreateBus(connectionString))
                {
                    bus.Rpc.Respond <ProductRequest, ProductsResponse>(ProductList);
                    bus.Rpc.Respond <ProductDetailsRequest, ProductDetailsResponse>(ProductDetails);
                    Console.WriteLine("Subscriber up");
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
            Console.WriteLine("Wait here");
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var daoASM = Assembly.Load(new AssemblyName("RuPengMessageHub.DAO"));

            foreach (Type serviceType in daoASM.GetTypes()
                     .Where(t => typeof(IDAOSupport).IsAssignableFrom(t) && !t.GetTypeInfo().IsAbstract))
            {
                /*
                 * var interfaceTypes = serviceType.GetInterfaces();
                 * foreach (var interfaceType in interfaceTypes)
                 * {
                 *  services.AddSingleton(interfaceType, serviceType);
                 * }*/
                services.AddSingleton(serviceType);
            }

            //注册所有Filter
            var currentASM = typeof(Startup).Assembly;

            foreach (Type serviceType in currentASM.GetTypes()
                     .Where(t => typeof(IFilterMetadata).IsAssignableFrom(t) && !t.GetTypeInfo().IsAbstract))
            {
                services.AddSingleton(serviceType);
            }

            var config = new ConfigurationBuilder()
                         .AddInMemoryCollection()                                               //load configurations into memory
                         .SetBasePath(Directory.GetCurrentDirectory())                          //指定配置文件所在的目录
                         .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) //指定加载的配置文件
                         .Build();                                                              //编译成对象

            //配置的注入https://www.cnblogs.com/skig/p/6079187.html
            services.AddOptions()
            .Configure <RedisSetting>(config.GetSection("Redis"))
            .Configure <BearerJWTSettings>(config.GetSection("BearerJWT"))
            .Configure <CorsSettings>(config.GetSection("Cors"));
            services.AddSingleton <IConfigurationRoot>(config);
            services.AddSingleton <RedisHelper>();
            services.AddHostedService <GroupMessageSenderService>();

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddDefaultTokenProviders();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                var sp                       = services.BuildServiceProvider();
                var jwtSetting               = sp.GetService <IOptions <BearerJWTSettings> >();
                string jwtSecret             = jwtSetting.Value.Secret;
                options.RequireHttpsMetadata = false;
                options.SaveToken            = true;

                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidIssuer      = jwtSetting.Value.Issuer,                                    //ValidIssuer、ValidAudience必须设置,要和验证方JwtSecurityToken的构造函数的前两个参数一致
                    ValidAudience    = jwtSetting.Value.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecret)) //Secret
                };
                //有些情况下JWT的值会放到queryString中的access_token,而不是在头的Authentication中,因此需要从querystring的access_token
                //读取出来设置到头上
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) &&
                            (path.StartsWithSegments("/messageHub")))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });
            services.AddCors();
            services.AddSignalR();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            //给SignalR的CallContext的UserIdentifier选择值用
            services.AddSingleton <IUserIdProvider, NameUserIdProvider>();

            services.BuildServiceProvider();
        }
Exemple #55
0
        public void AddConfigServer_JsonAppSettingsConfiguresClient()
        {
            // Arrange
            var appsettings = @"
                {
                    ""spring"": {
                        ""application"": {
                            ""name"": ""myName""
                    },
                      ""cloud"": {
                        ""config"": {
                            ""uri"": ""https://*****:*****@foo.com:9999"",
                            ""enabled"": false,
                            ""failFast"": false,
                            ""label"": ""myLabel"",
                            ""username"": ""myUsername"",
                            ""password"": ""myPassword"",
                            ""timeout"": 10000,
                            ""token"" : ""vaulttoken"",
                            ""retry"": {
                                ""enabled"":""false"",
                                ""initialInterval"":55555,
                                ""maxInterval"": 55555,
                                ""multiplier"": 5.5,
                                ""maxAttempts"": 55555
                            }
                        }
                      }
                    }
                }";

            var    path      = TestHelpers.CreateTempFile(appsettings);
            string directory = Path.GetDirectoryName(path);
            string fileName  = Path.GetFileName(path);
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.SetBasePath(directory);

            var csettings = new ConfigServerClientSettings();

            configurationBuilder.AddJsonFile(fileName);

            // Act and Assert
            configurationBuilder.AddConfigServer(csettings);
            var config = configurationBuilder.Build();

            ConfigServerConfigurationProvider configServerProvider =
                config.Providers.OfType <ConfigServerConfigurationProvider>().SingleOrDefault();

            Assert.NotNull(configServerProvider);

            ConfigServerClientSettings settings = configServerProvider.Settings;

            Assert.False(settings.Enabled);
            Assert.False(settings.FailFast);
            Assert.Equal("https://*****:*****@foo.com:9999", settings.Uri);
            Assert.Equal(ConfigServerClientSettings.DEFAULT_ENVIRONMENT, settings.Environment);
            Assert.Equal("myName", settings.Name);
            Assert.Equal("myLabel", settings.Label);
            Assert.Equal("myUsername", settings.Username);
            Assert.Equal("myPassword", settings.Password);
            Assert.False(settings.RetryEnabled);
            Assert.Equal(55555, settings.RetryAttempts);
            Assert.Equal(55555, settings.RetryInitialInterval);
            Assert.Equal(55555, settings.RetryMaxInterval);
            Assert.Equal(5.5, settings.RetryMultiplier);
            Assert.Equal(10000, settings.Timeout);
            Assert.Equal("vaulttoken", settings.Token);
        }
        public static void Main(string[] args)
        {
            // deprecated code
            return;

            if (args.Length <= 0)
            {
                Log2Console("\nUsage:", true);
                Log2Console("------", true);
                Log2Console("NinKode.Database.exe {param} [{options}]", true);
                Log2Console("\nPossible parameters....", true);
                Log2Console("\timport", true);
                Log2Console("\tdelete", true);
                Log2Console("\tconvert", true);
                Log2Console("\reset", true);
                Log2Console("\nOptions....", true);
                Log2Console("\n\t--url <url-to-raven>\n\t--name <ravendb name>", true);

                return;
            }

            if (args.Length > 1)
            {
                for (var i = 1; i < args.Length; i++)
                {
                    if (args[i].Equals("--url", StringComparison.OrdinalIgnoreCase) && args.Length >= (i + 1))
                    {
                        _dbUrl = args[++i];
                    }
                    else if (args[i].Equals("--name", StringComparison.OrdinalIgnoreCase) && args.Length >= (i + 1))
                    {
                        _dbName = args[++i];
                    }
                }
            }

            var config = new ConfigurationBuilder().AddEnvironmentVariables();

            _configuration = config.Build();

            var stopWatch = new Stopwatch();

            stopWatch.Start();

            //if (true)
            //{
            //    //CopyToServer();
            //    //ConvertDocuments();
            //    //ConvertVariasjonerDocuments();
            //    stopWatch.Stop();

            //    Thread.Sleep(10);
            //    Log2Console($"\n{AnyDocuments()} documents", true);

            //    Log2Console($"\nCommand executed in {stopWatch.Elapsed.TotalSeconds:##.00} seconds", true);

            //    return;
            //}

            switch (args[0].ToLowerInvariant())
            {
            case "delete":
                DeleteDocuments();
                break;

            case "import":
                ImportCsvIntoRavenDb();
                break;

            case "convert":
                ConvertDocuments();
                ConvertVariasjonerDocuments();
                break;

            case "reset":
                ImportCsvIntoRavenDb();
                ConvertDocuments();
                ConvertVariasjonerDocuments();
                break;
            }
            stopWatch.Stop();

            Thread.Sleep(10);
            Log2Console($"\n{AnyDocuments()} documents", true);

            Log2Console($"\nCommand executed in {stopWatch.Elapsed.TotalSeconds:##.00} seconds", true);
        }
Exemple #57
0
    public static Task Main(string[] args)
    {
        var scenarioName = "Unknown";
        var config       = new ConfigurationBuilder()
                           .AddCommandLine(args)
                           .Build();

        var builder = new HostBuilder()
                      .ConfigureWebHost(webHostBuilder =>
        {
            webHostBuilder
            .ConfigureLogging(loggingBuilder => loggingBuilder.AddConsole())
            .UseConfiguration(config)
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup <Startup>();

            if (string.Equals(webHostBuilder.GetSetting("server"), "Microsoft.AspNetCore.Server.HttpSys", System.StringComparison.Ordinal))
            {
                scenarioName = "HttpSysServer";
                Console.WriteLine("Using HttpSys server");
                webHostBuilder.UseHttpSys();
            }
            else if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_PORT")))
            {
                // ANCM is hosting the process.
                // The port will not yet be configured at this point, but will also not require HTTPS.
                scenarioName = "AspNetCoreModule";
                Console.WriteLine("Detected ANCM, using Kestrel");
                webHostBuilder.UseKestrel();
            }
            else
            {
                // Also check "server.urls" for back-compat.
                var urls = webHostBuilder.GetSetting(WebHostDefaults.ServerUrlsKey) ?? webHostBuilder.GetSetting("server.urls");
                webHostBuilder.UseSetting(WebHostDefaults.ServerUrlsKey, string.Empty);

                Console.WriteLine($"Using Kestrel, URL: {urls}");

                if (urls.Contains(";"))
                {
                    throw new NotSupportedException("This test app does not support multiple endpoints.");
                }

                var uri = new Uri(urls);

                webHostBuilder.UseKestrel(options =>
                {
                    options.Listen(IPAddress.Loopback, uri.Port, listenOptions =>
                    {
                        if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
                        {
                            scenarioName = "Kestrel(SSL)";
                            var certPath = Path.Combine(AppContext.BaseDirectory, "TestResources", "testCert.pfx");
                            Console.WriteLine($"Using SSL with certificate: {certPath}");
                            listenOptions.UseHttps(certPath, "testPassword");
                        }
                        else
                        {
                            scenarioName = "Kestrel(NonSSL)";
                        }
                    });
                });
            }
        });

        var host = builder.Build();

        AppDomain.CurrentDomain.UnhandledException += (_, a) =>
        {
            Console.WriteLine($"Unhandled exception (Scenario: {scenarioName}): {a.ExceptionObject.ToString()}");
        };

        Console.WriteLine($"Starting Server for Scenario: {scenarioName}");
        return(host.RunAsync());
    }
Exemple #58
0
        private static IWebHostBuilder CustomBuilder()
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(Directory.GetCurrentDirectory())

                         .Build();


            return(new WebHostBuilder()

                   // .UseUrls("http://wilsoft.site")
                   //.UseSetting("http_port", "80")
                   .UseUrls("http://*:12416")
                   //.UseSetting("http_port", "80")
                   .UseKestrel()
                   .UseIISIntegration()
                   .UseSerilog()
                   .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.AddConsole();
                logging.SetMinimumLevel(LogLevel.Warning);
                logging.AddEventLog();

                logging.AddEventSourceLogger();
                logging.AddFilter("System", LogLevel.Debug)
                .AddFilter <DebugLoggerProvider>("Microsoft", LogLevel.Trace);
            })
                   .UseConfiguration(config)
                   .UseContentRoot(Directory.GetCurrentDirectory())
                   .UseStartup <Startup>()

                   .UseHealthEndpoints(options =>
            {
            })
                   .ConfigureHealth(
                       builder =>
            {
                builder.OutputHealth.AsPlainText();
            })
                   .ConfigureHealthWithDefaults(
                       builder =>
            {
                builder.HealthChecks.AddCheck("DatabaseConnected", () => new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy("Database Connection OK")));
                builder.HealthChecks.AddPingCheck("google ping", "google.com", TimeSpan.FromSeconds(10));
            })
                   .ConfigureAppHealthHostingConfiguration(options =>
            {
                //options.AllEndpointsPort = 1111;
                //options.HealthEndpoint = "app-metrics-health";
            })
                   .UseMetricsEndpoints()
                   .UseHealth()
                   .UseMetricsWebTracking()
                   .UseMetrics()
                   .ConfigureKestrel((context, options) =>
            {
                //options.Listen(IPAddress.Any, 80);
                //options.Listen(IPAddress.Any, 1994);
                options.Limits.MaxConcurrentConnections = 100;
                options.Limits.MaxConcurrentUpgradedConnections = 100;
                //options.Limits.MaxRequestBodySize = 10 * 1024;
                //options.Limits.MinRequestBodyDataRate =
                //    new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
                //options.Limits.MinResponseDataRate =
                //    new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
                //options.Listen(IPAddress.Loopback, 1994);
                //options.Listen(IPAddress.Loopback, 5001, listenOptions =>
                //{
                //    listenOptions.UseHttps("testCert.pfx", "testPassword");
                //});
                //options.ConfigureHttpsDefaults(httpsOptions =>
                //{
                //    // certificate is an X509Certificate2
                //    //httpsOptions.ServerCertificate = certificate;
                //});
                //options.Configure(context.Configuration.GetSection("Kestrel"))
                // .Endpoint("HTTPS", opt =>
                // {
                //     opt.HttpsOptions.SslProtocols = SslProtocols.Tls12;
                // });

                //    options.ListenUnixSocket("/tmp/kestrel-test.sock");
                //    options.ListenUnixSocket("/tmp/kestrel-test.sock", listenOptions =>
                //    {
                //        listenOptions.UseHttps("testCert.pfx", "testpassword");
                //    });
                //options.ListenAnyIP(5005, listenOptions =>
                //{
                //        listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
                //        //listenOptions.ConnectionAdapters.Add(new TlsFilterAdapter());
                //        listenOptions.UseHttps(httpsOptions =>
                //        {
                //            //var localhostCert = CertificateLoader.LoadFromStoreCert(
                //            //    "localhost", "My", StoreLocation.CurrentUser,
                //            //    allowInvalid: true);
                //            //var exampleCert = CertificateLoader.LoadFromStoreCert(
                //            //    "example.com", "My", StoreLocation.CurrentUser,
                //            //    allowInvalid: true);
                //            //var subExampleCert = CertificateLoader.LoadFromStoreCert(
                //            //    "sub.example.com", "My", StoreLocation.CurrentUser,
                //            //    allowInvalid: true);
                //            //var certs = new Dictionary<string, X509Certificate2>(
                //            //    StringComparer.OrdinalIgnoreCase);
                //            //certs["localhost"] = localhostCert;
                //            //certs["example.com"] = exampleCert;
                //            //certs["sub.example.com"] = subExampleCert;

                //            //httpsOptions.ServerCertificateSelector = (connectionContext, name) =>
                //            //{
                //            //    if (name != null && certs.TryGetValue(name, out var cert))
                //            //    {
                //            //        return cert;
                //            //    }

                //            //    return exampleCert;
                //            //};
                //        });
                //});
                options.AllowSynchronousIO = true;
                //    options.Limits.Http2.InitialStreamWindowSize = 98304;
                //    options.Limits.Http2.InitialConnectionWindowSize = 131072;
                //    options.Limits.Http2.MaxFrameSize = 16384;
                //    options.Limits.Http2.MaxRequestHeaderFieldSize = 8192;
                //    options.Limits.Http2.HeaderTableSize = 4096;
                //    options.Limits.Http2.MaxStreamsPerConnection = 100;
                //options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(15);
                //options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(2);
            }));
        }
Exemple #59
0
        public Context()
        {
            IConfiguration context = new ConfigurationBuilder()
                                     .SetBasePath(Directory.GetCurrentDirectory())
                                     .AddJsonFile("context.json")
                                     .AddEnvironmentVariables("E2E_")
                                     .Build();

            string Get(string name) => context.GetValue <string>(name);

            IEnumerable <(string, string, string)> GetAndValidateRegistries()
            {
                var result = new List <(string, string, string)>();

                var registries = context.GetSection("registries").GetChildren().ToArray();

                foreach (var reg in registries)
                {
                    string address  = reg.GetValue <string>("address");
                    string username = reg.GetValue <string>("username");
                    // To specify a password as an environment variable instead of in the
                    // JSON file (so it's not stored in the clear on the filesystem), name
                    // the variable like this: E2E_REGISTRIES__<index>__PASSWORD, where
                    // <index> is the 0-based number corresponding to an element in the
                    // "registries" JSON array.
                    string password = reg.GetValue <string>("PASSWORD");

                    // If any container registry arguments (server, username, password)
                    // are given, then they must *all* be given, otherwise throw an error.
                    Preconditions.CheckNonWhiteSpace(address, nameof(address));
                    Preconditions.CheckNonWhiteSpace(username, nameof(username));
                    Preconditions.CheckNonWhiteSpace(password, nameof(password));

                    result.Add((address, username, password));
                }

                return(result);
            }

            Option <(string, string, string)> GetAndValidateRootCaKeys()
            {
                // If any root CA key materials (cert file, key file, password) are
                // given, then they must *all* be given, otherwise throw an error.
                string certificate = Get("rootCaCertificatePath");
                string key         = Get("rootCaPrivateKeyPath");
                string password    = Get("ROOT_CA_PASSWORD");

                if (!string.IsNullOrWhiteSpace(certificate) ||
                    !string.IsNullOrWhiteSpace(key) ||
                    !string.IsNullOrWhiteSpace(password))
                {
                    Preconditions.CheckNonWhiteSpace(certificate, nameof(certificate));
                    Preconditions.CheckNonWhiteSpace(key, nameof(key));
                    Preconditions.CheckNonWhiteSpace(password, nameof(password));
                    Preconditions.CheckArgument(File.Exists(certificate));
                    Preconditions.CheckArgument(File.Exists(key));
                    return(Option.Some((certificate, key, password)));
                }

                return(Option.None <(string, string, string)>());
            }

            string defaultId =
                $"e2e-{string.Concat(Dns.GetHostName().Take(14)).TrimEnd(new[] { '-' })}-{DateTime.Now:yyMMdd'-'HHmmss'.'fff}";

            this.CaCertScriptPath       = Option.Maybe(Get("caCertScriptPath"));
            this.ConnectionString       = Get("IOT_HUB_CONNECTION_STRING");
            this.DpsIdScope             = Option.Maybe(Get("dpsIdScope"));
            this.DpsGroupKey            = Option.Maybe(Get("DPS_GROUP_KEY"));
            this.EdgeAgentImage         = Option.Maybe(Get("edgeAgentImage"));
            this.EdgeHubImage           = Option.Maybe(Get("edgeHubImage"));
            this.EventHubEndpoint       = Get("EVENT_HUB_ENDPOINT");
            this.InstallerPath          = Option.Maybe(Get("installerPath"));
            this.LogFile                = Option.Maybe(Get("logFile"));
            this.MethodReceiverImage    = Option.Maybe(Get("methodReceiverImage"));
            this.MethodSenderImage      = Option.Maybe(Get("methodSenderImage"));
            this.OptimizeForPerformance = context.GetValue("optimizeForPerformance", true);
            this.PackagePath            = Option.Maybe(Get("packagePath"));
            this.Proxy                      = Option.Maybe(context.GetValue <Uri>("proxy"));
            this.Registries                 = GetAndValidateRegistries();
            this.RootCaKeys                 = GetAndValidateRootCaKeys();
            this.SetupTimeout               = TimeSpan.FromMinutes(context.GetValue("setupTimeoutMinutes", 5));
            this.TeardownTimeout            = TimeSpan.FromMinutes(context.GetValue("teardownTimeoutMinutes", 2));
            this.TempFilterFuncImage        = Option.Maybe(Get("tempFilterFuncImage"));
            this.TempFilterImage            = Option.Maybe(Get("tempFilterImage"));
            this.TempSensorImage            = Option.Maybe(Get("tempSensorImage"));
            this.MetricsValidatorImage      = Option.Maybe(Get("metricsValidatorImage"));
            this.TestResultCoordinatorImage = Option.Maybe(Get("testResultCoordinatorImage"));
            this.LoadGenImage               = Option.Maybe(Get("loadGenImage"));
            this.RelayerImage               = Option.Maybe(Get("relayerImage"));
            this.TestTimeout                = TimeSpan.FromMinutes(context.GetValue("testTimeoutMinutes", 5));
            this.Verbose                    = context.GetValue <bool>("verbose");
        }
Exemple #60
0
        private DBRep()
        {
            var configuration = new ConfigurationBuilder().AddJsonFile("DataBaseRepository.json").Build();

            Seri.InitConfig(configuration);
        }