示例#1
0
        public void UiSave(AppConfigurationModel model)
        {
            var savedModel = Get();

            _model = model;
            _api.Post2($"http://localhost:{savedModel.AntdPort}/config", _model.ToDictionary());
        }
        public static void ConfigureServices(AppConfigurationModel appConfiguration, IServiceCollection services, IHostingEnvironment environment)
        {
            // Custom services
            // The configuration is split into 2 parts.
            // - AppConfigurationService has the strongly typed configuration and filesystem.
            // - AppConfiguration is the strongly typed configuration only.
            services.AddSingleton <IAppConfigurationService>(new Northwind.BLL.Services.AppConfigurationService(environment));
            services.AddSingleton <IAppConfiguration>(new Northwind.BLL.Services.AppConfigurationService(environment));

            // Application Data - this is a dependant of business logic so we start it here
            Northwind.DAL.Startup.ConfigureServices(appConfiguration, services);

            // AspNetCore Identity
            Northwind.DAL.Startup.ConfigureIdentityServices(appConfiguration, services);
            services.AddSingleton <IdentityService, IdentityService>();

            services.AddTransient <RetailInventoryService, RetailInventoryService>();
            services.AddTransient <CategoryService, CategoryService>();
            services.AddTransient <IGenericWorker <Product, ProductRowApiO, int>, ProductRowWorker>();
            services.AddTransient <IGenericWorker <Customer, CustomerRowApiO, string>, CustomerRowWorker>();
            services.AddTransient <IGenericWorker <CustomerDemographic, CustomerDemographicRowApiO, string>, CustomerDemographicRowWorker>();
            services.AddTransient <IGenericWorker <Employee, EmployeeRowApiO, int>, EmployeeRowWorker>();
            services.AddTransient <IGenericWorker <EmployeeTerritory, EmployeeTerritoryRowApiO, int>, EmployeeTerritoryRowWorker>();
            services.AddTransient <IGenericWorker <Order, OrderRowApiO, int>, OrderRowWorker>();
            services.AddTransient <IGenericWorker <OrderDetail, OrderDetailRowApiO, int>, OrderDetailRowWorker>();
            services.AddTransient <IGenericWorker <Region, RegionRowApiO, int>, RegionRowWorker>();
            services.AddTransient <IGenericWorker <Shipper, ShipperRowApiO, int>, ShipperRowWorker>();
            services.AddTransient <IGenericWorker <Supplier, SupplierRowApiO, int>, SupplierRowWorker>();
            services.AddTransient <IGenericWorker <Territory, TerritoryRowApiO, int>, TerritoryRowWorker>();
        }
        public static void Configure(AppConfigurationModel appConfiguration, IApplicationBuilder app)
        {
            // Application Data
            Northwind.DAL.Startup.Configure(app);

            // AspNetCore Identity
            Northwind.DAL.Startup.ConfigureIdentity(appConfiguration, app);
        }
示例#4
0
 private void IsLicenseInDBValid()
 {
     using (var db = new DataAccessor())
     {
         AppConfigurationModel config = db.Configurations.ToList().First();
         string serialNumberInDb      = config.SerialNumber;
     }
 }
示例#5
0
 public IdentityWorker(AppConfigurationModel appConfiguration, UserManager <UserProfileModel> userManager,
                       SignInManager <UserProfileModel> signInManager, RoleManager <IdentityRole> roleManager)
 {
     this.UserManager   = userManager;
     this.SignInManager = signInManager;
     this.RoleManager   = roleManager;
     this.DefaultRole   = appConfiguration.SeedData.DefaultRole;
 }
示例#6
0
 public void Save(AppConfigurationModel model)
 {
     _model = model;
     if (File.Exists(_file))
     {
         File.Copy(_file, $"{_file}.bck", true);
     }
     File.WriteAllText(_file, JsonConvert.SerializeObject(_model, Formatting.Indented));
 }
 public static void ConfigureServices(AppConfigurationModel appConfiguration, IServiceCollection services)
 {
     services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(appConfiguration.ConnectionStrings.Content)); // Application data
     services.AddTransient <IRepository <FoodParcel>, FoodParcelRepository>();
     services.AddTransient <IRepository <FoodItem>, FoodItemRespository>();
     services.AddTransient <IRepository <TestResult>, TestResultRepository>();
     services.AddTransient <IRepository <TestResultItem>, TestResultItemsRepository>();
     services.AddTransient <IRepository <TestItemCategory>, TestItemCategoriesRepository>();
 }
示例#8
0
 protected override void OnCreate(Bundle savedInstanceState)
 {
     TabLayoutResource = Resource.Layout.Tabbar;
     ToolbarResource   = Resource.Layout.Toolbar;
     base.OnCreate(savedInstanceState);
     Rg.Plugins.Popup.Popup.Init(this, savedInstanceState);
     global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
     CrossCurrentActivity.Current.Init(this, savedInstanceState);
     AppConfigurationModel.Init();
     LoadApplication(new App());
 }
        public static void ConfigureServices(AppConfigurationModel appConfiguration, IServiceCollection services, IHostingEnvironment environment)
        {
            // Custom services
            services.AddSingleton <IAppConfigurationService>(new QAFood.BLL.Services.AppConfigurationService(environment)); // provides strongly typed access to appsettings.json.

            // Application Data - this is a dependant of business logic so we start it here
            QAFood.DAL.Startup.ConfigureServices(appConfiguration, services);

            // AspNetCore Identity
            QAFood.DAL.Startup.ConfigureIdentityServices(appConfiguration, services);

            services.AddTransient <IdentityService, IdentityService>();
            services.AddTransient <ReviewService, ReviewService>();
            services.AddTransient <TestResultService, TestResultService>();
        }
        public override void LoadJsonConfig()
        {
            base.LoadJsonConfig();
            string configPath = base.ContentRootPath + base.ConfigFileName;

            // In dev mode, load a different file.
            if (base.IsDevelopment == true)
            {
                configPath = base.ContentRootPath + "appsettings.Development.json";
            }

            using (JSONSerialiser js = new JSONSerialiser())
            {
                this.AppConfiguration = js.Deserialize <AppConfigurationModel>(new Uri(configPath));
            }
        }
示例#11
0
        public static void ConfigureIdentity(AppConfigurationModel appConfiguration, IApplicationBuilder app)
        {
            // Create and update the database automatically (like doing Update-Database)
            // https://stackoverflow.com/questions/42355481/auto-create-database-in-entity-framework-core
            using (IServiceScope serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                AuthenticationDbContext authenticationDbContext = serviceScope.ServiceProvider.GetRequiredService <AuthenticationDbContext>();
                authenticationDbContext.Database.Migrate();
            }

            // Seed data
            AuthenticationDbContext.CreateDefaultRoles(app.ApplicationServices, appConfiguration).Wait();
            AuthenticationDbContext.CreateAdminAccount(app.ApplicationServices, appConfiguration).Wait();

            app.UseAuthentication();
        }
示例#12
0
        public static void ConfigureIdentityServices(AppConfigurationModel appConfiguration, IServiceCollection services)
        {
            services.AddDbContext <AuthenticationDbContext>(options => options.UseSqlServer(appConfiguration.ConnectionStrings.Authentication)); // The user database

            // Setup the password validation requirements eg: Password1!
            services.AddIdentity <UserProfileModel, IdentityRole>(
                opts => {
                opts.User.RequireUniqueEmail = true;

                opts.Password.RequiredLength         = 9;
                opts.Password.RequireNonAlphanumeric = false;
                opts.Password.RequireLowercase       = true;
                opts.Password.RequireUppercase       = true;
                opts.Password.RequireDigit           = true;
            }
                ).AddEntityFrameworkStores <AuthenticationDbContext>(); // The model
        }
示例#13
0
 public async Task InitializePluginsAsync(AppConfigurationModel configurationObject)
 {
     _log.LogDebug("Initializing plugins");
     foreach (var configuration in configurationObject.DevicePluginConfigurations)
     {
         try
         {
             _log.LogTrace("Initializing plugin " + configuration.Type + " with name " + configuration.Name);
             var deviceInstance = (IPlugin)ServiceLocator.Current.GetService(_deviceTypes[configuration.Type.ToLower()]);
             _deviceList.Add(configuration.Name.ToLower(), deviceInstance);
             await deviceInstance.InitializeAsync(configuration);
         }
         catch (Exception ex)
         {
             _log.LogError(ex, "Error while initializing plugin " + configuration.Name);
         }
     }
     _log.LogDebug("Initializing plugins done");
 }
        public async void Initialize(AppConfigurationModel configuration)
        {
            if (configuration.DeviceFunctionIds == null)
            {
                return;
            }
            foreach (var functionId in configuration.DeviceFunctionIds)
            {
                var functionInstance = await SetupFunction(functionId);

                if (functionInstance != null)
                {
                    _functions.Add(functionInstance);
                }
            }
            _cancellationTokenSource = new CancellationTokenSource();
            // setup message receiver loop
            MessageReceiverLoop(_cancellationTokenSource.Token);
        }
示例#15
0
        public static void ConfigureServices(AppConfigurationModel appConfiguration, IServiceCollection services)
        {
            Startup.AppConfiguration = appConfiguration;

            services.AddDbContext <NorthwindContext>(options => options.UseSqlServer(appConfiguration.ConnectionStrings.Content)); // Application data

            services.AddTransient <IRepository <Category, int>, CategoryRepository>();
            services.AddTransient <IRepository <CustomerDemographic, string>, CustomerDemographicRepository>();
            services.AddTransient <IRepository <CustomerCustomerDemo, string>, CustomerCustomerDemoRepository>();
            services.AddTransient <IRepository <Customer, string>, CustomerRepository>();
            services.AddTransient <IRepository <Employee, int>, EmployeeRepository>();
            services.AddTransient <IRepository <EmployeeTerritory, int>, EmployeeTerritoryRepository>();
            services.AddTransient <IRepository <OrderDetail, int>, OrderDetailRepository>();
            services.AddTransient <IRepository <Order, int>, OrderRepository>();
            services.AddTransient <IRepository <Product, int>, ProductRepository>();
            services.AddTransient <IRepository <Region, int>, RegionRepository>();
            services.AddTransient <IRepository <Shipper, int>, ShipperRepository>();
            services.AddTransient <IRepository <Supplier, int>, SupplierRepository>();
            services.AddTransient <IRepository <Territory, string>, TerritoryRepository>();
        }
示例#16
0
 public AppConfiguration()
 {
     if (!File.Exists(_file))
     {
         _model = new AppConfigurationModel();
         var text = JsonConvert.SerializeObject(_model, Formatting.Indented);
         File.WriteAllText(_file, text);
     }
     else
     {
         try {
             var text = File.ReadAllText(_file);
             var obj  = JsonConvert.DeserializeObject <AppConfigurationModel>(text);
             _model = obj;
         }
         catch (Exception) {
             _model = new AppConfigurationModel();
         }
     }
 }
示例#17
0
        public AntdAppConfigurationModule()
        {
            Get["/config"] = _ => {
                var list = _appConfiguration.UiGet();
                return(JsonConvert.SerializeObject(list));
            };

            Post["/config"] = _ => {
                int    antdPort     = Request.Form.AntdPort;
                int    antdUiPort   = Request.Form.AntdUiPort;
                string databasePath = Request.Form.DatabasePath;
                var    model        = new AppConfigurationModel {
                    AntdPort     = antdPort,
                    AntdUiPort   = antdUiPort,
                    DatabasePath = databasePath
                };
                _appConfiguration.UiSave(model);
                return(HttpStatusCode.OK);
            };
        }
示例#18
0
        public async Task <AppConfigurationModel> Get(string deviceId)
        {
            var deviceFunctions = await _deviceFunctionService.GetFunctionsAsync(deviceId);

            var result = new AppConfigurationModel
            {
                DeviceId                   = deviceId,
                ServiceBaseUrl             = _configuration["ExternalBaseUrl"],
                DevicePluginConfigurations = new List <DevicePluginConfigurationModel>
                {
                    new DevicePluginConfigurationModel // default iot hub configuration for tpm
                    {
                        Name       = "iothub",
                        Type       = "IAzureIoTHubPlugin",
                        Properties = new Dictionary <string, string>()
                    }
                },
                DeviceFunctionIds = deviceFunctions.Select(a => a.RowKey).ToList()
            };

            // add device plugin configurations from database
            var devicePlugins = await _devicePluginService.GetAsync(deviceId);

            foreach (var devicePlugin in devicePlugins.Where(p => p.Enabled)) // only the enabled plugins are reported to the device
            {
                var props = await _devicePluginPropertyService.GetAsync(devicePlugin.RowKey);

                result.DevicePluginConfigurations.Add(new DevicePluginConfigurationModel
                {
                    Name       = devicePlugin.RowKey,
                    Type       = devicePlugin.Type,
                    Properties = props.ToDictionary(k => k.RowKey, k => k.Value)
                });
            }
            return(result);
        }
示例#19
0
 public void SetConfiguration(AppConfigurationModel model)
 {
     _model = model;
 }
        /// <summary>
        /// Create an admin account on application startup.
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <param name="configurationModel"></param>
        /// <returns></returns>
        public static async Task CreateAdminAccount(IServiceProvider serviceProvider, AppConfigurationModel configurationModel)
        {
            UserManager <UserProfileModel> userManager = serviceProvider.GetRequiredService <UserManager <UserProfileModel> >();
            RoleManager <IdentityRole>     roleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >();

            SeedDataUserModel adminUser = configurationModel.SeedData.AdminUser;

            if (await userManager.FindByNameAsync(adminUser.Name) == null)
            {
                // Setup the role for the user if it does not exist.
                foreach (string item in adminUser.Roles)
                {
                    if (await roleManager.FindByNameAsync(item) == null)
                    {
                        await roleManager.CreateAsync(new IdentityRole(item));
                    }
                }

                UserProfileModel newUser = new UserProfileModel()
                {
                    UserName = adminUser.Name, Email = adminUser.Email
                };

                IdentityResult identityResult = await userManager.CreateAsync(newUser, adminUser.Password);

                if (identityResult.Succeeded == true)
                {
                    foreach (string item in adminUser.Roles)
                    {
                        await userManager.AddToRoleAsync(newUser, item);
                    }
                }
            }
        }
        /// <summary>
        /// Create default roles on application startup.
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <param name="configurationModel"></param>
        /// <returns></returns>
        public static async Task CreateDefaultRoles(IServiceProvider serviceProvider, AppConfigurationModel configurationModel)
        {
            RoleManager <IdentityRole> roleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >(); //serviceProvider.GetService<RoleManager<IdentityRole>>();
            List <string> roles = configurationModel.SeedData.CreateDefaultRoles;

            foreach (string item in roles)
            {
                // Setup the role for the user if it does not exist.
                if (await roleManager.FindByNameAsync(item) == null)
                {
                    await roleManager.CreateAsync(new IdentityRole(item));
                }
            }
        }
示例#22
0
 public void Save(AppConfigurationModel model)
 {
     _model = model;
     FileWithAcl.WriteAllText(_file, JsonConvert.SerializeObject(_model, Formatting.Indented), "644", "root", "wheel");
 }
示例#23
0
 public AppConfigurationModel UiGet()
 {
     _model = _api.Get <AppConfigurationModel>($"http://localhost:{_model.AntdPort}/config");
     return(_model);
 }
示例#24
0
        public async Task RunAsync()
        {
            _log.LogTrace("Run");

            // Build configuration object to configure all devices
            AppConfigurationModel configurationObject = new AppConfigurationModel();

            // first try to load the configuration file from the LocalFolder
            var localStorage = ApplicationData.Current.LocalFolder;
            var file         = await localStorage.TryGetItemAsync("configuration.json");

            if (file != null)         // file exists, continue to deserialize into actual configuration object
            {
                // local file content
                var configFileContent = await FileIO.ReadTextAsync((IStorageFile)file);

                configurationObject = JsonConvert.DeserializeObject <AppConfigurationModel>(configFileContent);
            }
            else         // there is not yet a configuration file, tell AzureIoTHubDevice to load it from the cloud and then restart
            {
                configurationObject.DevicePluginConfigurations = new List <DevicePluginConfigurationModel>(new[]
                {
                    // by default iot hub configuration now uses TPM chip
                    new DevicePluginConfigurationModel()
                    {
                        Name       = "iothub",
                        Type       = "IAzureIoTHubPlugin",
                        Properties = new Dictionary <string, string>()
                        {
                            { "TryLoadConfiguration", "true" }
                            //{ "ConnectionString", "IOT_HUB_CONNECTION_STRING_ONLY_FOR_DEBUGGING"}
                        }
                    }
                });
            }

            #region manual scripting

            //configurationObject.DeviceConfigurations = new List<DeviceConfiguration>(new[]
            //{
            //	// by default iot hub configuration now uses TPM chip
            //	new DeviceConfiguration
            //	{
            //		Name = "iothub",
            //		Type = "AzureIoTHubDevice",
            //		Properties = new Dictionary<string, string>()
            //		{
            //			//{ "ConnectionString", ""}
            //		}
            //	},
            //	//new DeviceConfiguration()
            //	//{
            //	//	Name = "secvest",
            //	//	Type = "SecVestDevice",
            //	//	Properties = new Dictionary<string, string>()
            //	//	{
            //	//		{"ConnectionString", "https://192.168.0.22:4433/" },
            //	//		{"Username", "1234" },
            //	//		{"Password", "1234" }
            //	//	}
            //	//},
            //	//new DeviceConfiguration()
            //	//{
            //	//	Name = "cam1",
            //	//	Type = ""
            //	//}
            //});
            //configurationObject.Functions = new List<FunctionDeclaration>(new FunctionDeclaration[]
            //{
            //	//new FunctionDeclaration()
            //	//{
            //	//	TriggerType = FunctionTriggerType.RecurringIntervalTimer,
            //	//	Name = "PollSecvestEveryMinute",
            //	//	Interval = 10*1000, // polling interval measured in miliseconds
            //	//	Code = @"
            //	//	function run()
            //	//		-- get status from secvest every minute
            //	//		secvest = registry.getDevice(""secvest"");
            //	//		statusChannel = secvest.getChannel(""status"");
            //	//		statusValue = statusChannel.read();
            //	//		if(statusValue != nil) then
            //	//			-- send status to iothub queue
            //	//			queue.enqueue(""iothub"", ""status@secvest"", statusValue, ""json"");
            //	//			end;
            //	//		return 0;
            //	//	end;
            //	//	"
            //	//},
            //	new FunctionDeclaration()
            //	{
            //		TriggerType = FunctionTriggerType.MessageQueue,
            //		Name = "WindSensorQueueHandler",
            //		QueueName = "windsensor",
            //		Code = @"
            //		function run(message)
            //			if(message.Key == ""Wind"") then
            //				message.Key = ""windspeed@windsensor"";
            //				message.Tag = ""windspeed_kmh""
            //			end;
            //			if(message.Key == ""Temperature"") then
            //				message.Key = ""temperature@windsensor"";
            //				message.Tag = ""temperature_celsius""
            //			end;

            //			queue.enqueue(""iothub"", message); -- simply forward to iot hub message queue
            //			return 0;
            //		end;
            //		"
            //	},
            //	new FunctionDeclaration()
            //	{
            //		TriggerType = FunctionTriggerType.MessageQueue,
            //		Name = "SecvestOutputSwitchHandler",
            //		QueueName = "secvestoutput",
            //		Code = @"
            //		function run(message)
            //			secvest = registry.getDevice(""secvest"");
            //			statusChannel = secvest.getChannel(""status"");
            //			statusChannel.setOutput(message.Key, message.Value);
            //			return 0;
            //		end;
            //		"
            //	}
            //});

            #endregion

            var configString = JsonConvert.SerializeObject(configurationObject, Formatting.Indented);
            Debug.WriteLine(configString);

            _configurationProvider.SetConfiguration(configurationObject);

            // configure devices
            await _pluginRegistry.InitializePluginsAsync(configurationObject);

            // start lua engine
            _functionsEngine.Initialize(configurationObject);

            // define cron timers
            //_everySecondTimer = new Timer(EverySecondTimerCallback, null, 1000, 1000);
            _everyMinuteTimer = new Timer(EveryMinuteTimerCallbackAsync, null, 60 * 1000, 60 * 1000);

            await StartWebserverAsync();
        }