public void Add(ModuleOptions pModuleType, Object pInstance) { if (!mCatalog.ContainsKey(pModuleType)) { mCatalog.Add(pModuleType, pInstance); } }
public PythonAst(Statement body, bool isModule, ModuleOptions languageFeatures, bool printExpressions, CompilerContext context) { ContractUtils.RequiresNotNull(body, "body"); _body = body; _isModule = isModule; _printExpressions = printExpressions; _languageFeatures = languageFeatures; _mode = ((PythonCompilerOptions)context.Options).CompilationMode ?? GetCompilationMode(context); _compilerContext = context; FuncCodeExpr = _functionCode; PythonCompilerOptions pco = context.Options as PythonCompilerOptions; Debug.Assert(pco != null); string name; if (!context.SourceUnit.HasPath || (pco.Module & ModuleOptions.ExecOrEvalCode) != 0) { name = "<module>"; } else { name = context.SourceUnit.Path; } _name = name; Debug.Assert(_name != null); PythonOptions po = ((PythonContext)context.SourceUnit.LanguageContext).PythonOptions; if (po.EnableProfiler && _mode != CompilationMode.ToDisk) { _profiler = Profiler.GetProfiler(PyContext); } _document = context.SourceUnit.Document ?? Ast.SymbolDocument(name, PyContext.LanguageGuid, PyContext.VendorGuid); }
private int RunFileWorker(string /*!*/ fileName) { ScriptCode compiledCode; ModuleOptions modOpt = ModuleOptions.Optimized | ModuleOptions.ModuleBuiltins; if (Options.SkipFirstSourceLine) { modOpt |= ModuleOptions.SkipFirstLine; } PythonModule module = PythonContext.CompileModule( fileName, "__main__", PythonContext.CreateFileUnit(String.IsNullOrEmpty(fileName) ? null : fileName, PythonContext.DefaultEncoding), modOpt, out compiledCode); PythonContext.PublishModule("__main__", module); Scope = module.Scope; try { compiledCode.Run(Scope); } catch (SystemExitException pythonSystemExit) { // disable introspection when exited: Options.Introspection = false; return(GetEffectiveExitCode(pythonSystemExit)); } return(0); }
public TotemAst(bool isModule, ModuleOptions languageFeatures, bool printExpressions, CompilerContext context) { _isModule = isModule; _printExpressions = printExpressions; _languageFeatures = languageFeatures; _mode = ((TotemCompilerOptions)context.Options).CompilationMode ?? GetCompilationMode(context); _compilerContext = context; FuncCodeExpr = _functionCode; TotemCompilerOptions tco = context.Options as TotemCompilerOptions; Debug.Assert(tco != null); string name; if (!context.SourceUnit.HasPath || (tco.Module & ModuleOptions.ExecOrEvalCode) != 0) { name = "<module>"; } else { name = context.SourceUnit.Path; } _name = name; Debug.Assert(_name != null); TotemOptions to = ((TotemContext)context.SourceUnit.LanguageContext).TotemOptions; _document = context.SourceUnit.Document ?? Expression.SymbolDocument(name, TotemContext.LanguageGuid, TotemContext.VendorGuid); }
/// <summary> /// Creates a new PythonAst without a body. ParsingFinished should be called afterwards to set /// the body. /// </summary> public PythonAst(bool isModule, ModuleOptions languageFeatures, bool printExpressions, CompilerContext context) { _isModule = isModule; _printExpressions = printExpressions; _languageFeatures = languageFeatures; _mode = ((PythonCompilerOptions)context.Options).CompilationMode ?? GetCompilationMode(context); _compilerContext = context; FuncCodeExpr = _functionCode; PythonCompilerOptions pco = context.Options as PythonCompilerOptions; Debug.Assert(pco != null); string name; if (!context.SourceUnit.HasPath || (pco.Module & ModuleOptions.ExecOrEvalCode) != 0) { name = "<module>"; } else { name = context.SourceUnit.Path; } _name = name; Debug.Assert(_name != null); PythonOptions po = ((PythonContext)context.SourceUnit.LanguageContext).PythonOptions; if (po.EnableProfiler && _mode != CompilationMode.ToDisk) { _profiler = Profiler.GetProfiler(PyContext); } _document = context.SourceUnit.Document ?? Ast.SymbolDocument(name, PyContext.LanguageGuid, PyContext.VendorGuid); }
private int RunCommandWorker(string command) { ScriptCode compiledCode; ModuleOptions trueDiv = (PythonContext.PythonOptions.DivisionOptions == PythonDivisionOptions.New) ? ModuleOptions.TrueDivision : ModuleOptions.None; ModuleOptions modOpt = ModuleOptions.Optimized | ModuleOptions.ModuleBuiltins | trueDiv; ; if (Options.SkipFirstSourceLine) { modOpt |= ModuleOptions.SkipFirstLine; } PythonModule module = PythonContext.CompileModule( "", // there is no file, it will be set to <module> "__main__", PythonContext.CreateSnippet(command, "-c", SourceCodeKind.File), modOpt, out compiledCode); PythonContext.PublishModule("__main__", module); Scope = module.Scope; try { compiledCode.Run(Scope); } catch (SystemExitException pythonSystemExit) { // disable introspection when exited: Options.Introspection = false; return(GetEffectiveExitCode(pythonSystemExit)); } return(0); }
public PythonAst(Statement body, bool isModule, ModuleOptions languageFeatures, bool printExpressions) { ContractUtils.RequiresNotNull(body, "body"); _body = body; _isModule = isModule; _printExpressions = printExpressions; _languageFeatures = languageFeatures; }
public static ModuleOptions AddCatalogsModule( this ModuleOptions options, string section = "naos:sample:catalogs") { EnsureArg.IsNotNull(options, nameof(options)); EnsureArg.IsNotNull(options.Context, nameof(options.Context)); options.Context.AddTag("catalogs"); var configuration = options.Context.Configuration?.GetSection($"{section}:sqlDocuments").Get <SqlDocumentsConfiguration>() ?? new SqlDocumentsConfiguration(); options.Context.Services.AddSingleton <IDocumentProvider <Product> >(sp => new SqlServerDocumentProvider <Product>(o => o .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .EnableSqlLogging() //.ConnectionString("Server=127.0.0.1;Database=naos_sample;User=sa;Password=Abcd1234!;Trusted_Connection=False;MultipleActiveResultSets=True;") // docker //.ConnectionString(configuration.ConnectionString ?? "Server=(localdb)\\mssqllocaldb;Database=naos_sample;Trusted_Connection=True;MultipleActiveResultSets=True;") .ConnectionString(configuration.ConnectionString) .Schema(configuration.SchemaName.EmptyToNull() ?? "catalogs") .AddIndex(p => p.Name) .AddIndex(p => p.Region) .AddIndex(p => p.Price) .AddIndex(p => p.HasStock))); options.Context.Services.AddScoped <IProductRepository>(sp => { return(new ProductRepository( //new RepositoryTracingDecorator<Product>( // sp.GetService<ILogger<ProductRepository>>(), // sp.GetService<ITracer>(), // new RepositoryLoggingDecorator<Product>( // sp.GetRequiredService<ILogger<ProductRepository>>(), #pragma warning disable SA1114 // Parameter list should follow declaration new DocumentRepository <Product>(o => o .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .Provider(sp.GetRequiredService <IDocumentProvider <Product> >()) .Mediator(sp.GetRequiredService <IMediator>())))); #pragma warning restore SA1114 // Parameter list should follow declaration }); //options.Context.Services.AddSingleton<IDocumentProvider<Product>>(sp => // new SqliteDocumentProvider<Product>(new SqliteDocumentProviderOptionsBuilder<Product>() // .LoggerFactory(sp.GetRequiredService<ILoggerFactory>()) // .EnableSqlLogging() // .ConnectionString(@"Data Source=c:\tmp\naos_sample_catalogs.db;Version=3;") // .AddIndex(p => p.Name) // .AddIndex(p => p.Region) // .AddIndex(p => p.Price) // .AddIndex(p => p.HasStock).Build())); options.Context.Messages.Add("naos services builder: catalogs service added"); options.Context.Services.AddHealthChecks() .AddSqlServer(configuration.ConnectionString, name: "Catalogs-sqlserver"); return(options); }
public PythonAst(Statement body, bool isModule, ModuleOptions languageFeatures, bool printExpressions, CompilerContext context, int[] lineLocations) : this(isModule, languageFeatures, printExpressions, context) { ContractUtils.RequiresNotNull(body, nameof(body)); _body = body; _lineLocations = lineLocations; }
public PythonAst(Statement body, bool isModule, ModuleOptions languageFeatures, bool printExpressions, CompilerContext context, int[] lineLocations) : this(isModule, languageFeatures, printExpressions, context) { ContractUtils.RequiresNotNull(body, "body"); _body = body; _lineLocations = lineLocations; }
public PythonAst(Statement body, bool isModule, ModuleOptions languageFeatures, bool printExpressions) { ContractUtils.RequiresNotNull(body, nameof(body)); _body = body; IsModule = isModule; _printExpressions = printExpressions; _languageFeatures = languageFeatures; }
public Object GetFactory(ModuleOptions pModuleType) { if (mCatalog.ContainsKey(pModuleType)) { return(mCatalog[pModuleType]); } else { return(null); } }
public T GetView <T>(ModuleOptions pModuleType) { if (mCatalog.ContainsKey(pModuleType)) { IViewFactory <T> factory = (IViewFactory <T>)mCatalog[pModuleType]; return(factory.Create()); } else { return(default(T)); } }
/// <summary> /// Called when parsing is complete, the body is built, the line mapping and language features are known. /// /// This is used in conjunction with the constructor which does not take a body. It enables creating /// the outer most PythonAst first so that nodes can always have a global parent. This lets an un-bound /// tree to still provide it's line information immediately after parsing. When we set the location /// of each node during construction we also set the global parent. When we name bind the global /// parent gets replaced with the real parent ScopeStatement. /// </summary> /// <param name="lineLocations">a mapping of where each line begins</param> /// <param name="body">The body of code</param> /// <param name="languageFeatures">The language features which were set during parsing.</param> public void ParsingFinished(int[] lineLocations, Statement body, ModuleOptions languageFeatures) { ContractUtils.RequiresNotNull(body, nameof(body)); if (_body != null) { throw new InvalidOperationException("cannot set body twice"); } _body = body; _lineLocations = lineLocations; _languageFeatures = languageFeatures; }
private Parser(Tokenizer tokenizer, ErrorSink errorSink, ParserSink parserSink, ModuleOptions languageFeatures) { ContractUtils.RequiresNotNull(tokenizer, "tokenizer"); ContractUtils.RequiresNotNull(errorSink, "errorSink"); ContractUtils.RequiresNotNull(parserSink, "parserSink"); tokenizer.ErrorSink = new TokenizerErrorSink(this); _tokenizer = tokenizer; _errors = errorSink; _sink = parserSink; Reset(tokenizer.SourceUnit, languageFeatures); }
protected override Scope /*!*/ CreateScope() { ModuleOptions trueDiv = (PythonContext.PythonOptions.DivisionOptions == PythonDivisionOptions.New) ? ModuleOptions.TrueDivision : ModuleOptions.None; var modCtx = new ModuleContext(new PythonDictionary(), PythonContext); modCtx.Features = trueDiv; modCtx.InitializeBuiltins(true); PythonContext.PublishModule("__main__", modCtx.Module); modCtx.Globals["__doc__"] = null; modCtx.Globals["__name__"] = "__main__"; return(modCtx.GlobalScope); }
/// <summary> /// 注入引用模块 /// </summary> /// <param name="services"></param> /// <param name="setupAction"></param> /// <returns></returns> public static IModuleBuilder AddDependenciesModule(this IServiceCollection services, Action <ModuleOptions> setupAction = null) { Check.NotNull(services, nameof(services)); var options = new ModuleOptions { }; setupAction?.Invoke(options); services.ScanModule(scan => scan.FromApplicationDependencies()); return(new ModuleBuilder(services)); }
private int RunFileWorker(string /*!*/ fileName) { try { // There is no PEP for this case, only http://bugs.python.org/issue1739468 object importer; if (Importer.TryImportMainFromZip(DefaultContext.Default, fileName, out importer)) { return(0); } if (importer != null && importer.GetType() != typeof(PythonImport.NullImporter)) { Console.WriteLine(String.Format("can't find '__main__' module in '{0}'", fileName), Style.Error); return(0); } } catch (SystemExitException pythonSystemExit) { // disable introspection when exited: Options.Introspection = false; return(GetEffectiveExitCode(pythonSystemExit)); } // classic file ScriptCode compiledCode; ModuleOptions modOpt = ModuleOptions.Optimized | ModuleOptions.ModuleBuiltins; if (Options.SkipFirstSourceLine) { modOpt |= ModuleOptions.SkipFirstLine; } PythonModule module = PythonContext.CompileModule( fileName, "__main__", PythonContext.CreateFileUnit(String.IsNullOrEmpty(fileName) ? null : fileName, PythonContext.DefaultEncoding), modOpt, out compiledCode); PythonContext.PublishModule("__main__", module); Scope = module.Scope; try { compiledCode.Run(Scope); } catch (SystemExitException pythonSystemExit) { // disable introspection when exited: Options.Introspection = false; return(GetEffectiveExitCode(pythonSystemExit)); } return(0); }
private Parser(CompilerContext context, Tokenizer tokenizer, ErrorSink errorSink, ParserSink parserSink, ModuleOptions languageFeatures) { ContractUtils.RequiresNotNull(tokenizer, "tokenizer"); ContractUtils.RequiresNotNull(errorSink, "errorSink"); ContractUtils.RequiresNotNull(parserSink, "parserSink"); tokenizer.ErrorSink = new TokenizerErrorSink(this); _tokenizer = tokenizer; _errors = errorSink; if (parserSink != ParserSink.Null) { _sink = parserSink; } _context = context; Reset(tokenizer.SourceUnit, languageFeatures); }
public static ModulesOptions ConfigureIdentityModule(this ModulesOptions modulesOptions, IConfiguration config) { var moduleName = typeof(IdentityModuleOptionsExtensions).GetTypeInfo().Assembly.GetName().Name; ModuleOptions moduleOptions = null; if (!modulesOptions.ModuleOptions.TryGetValue(moduleName, out moduleOptions)) { modulesOptions.ModuleOptions[moduleName] = new ModuleOptions(); } modulesOptions.ModuleOptions[moduleName].ConfigureServices.Add(services => { services.Configure <IdentityModuleOptions>(identityModuleOptions => { identityModuleOptions.ConnectionString = config.GetConnectionString("DefaultConnection"); }); }); return(modulesOptions); }
private static string GetAssemblyDirectory(ModuleOptions module, string[] workingDirectory) { var paths = new List <string> { AppContext.BaseDirectory }; foreach (var path in workingDirectory) { if (path == "@Id") { paths.Add(module.Id); } else { paths.Add(path); } } return(Path.Combine(paths.ToArray())); }
/// <summary> /// 添加Riven模块服务 /// </summary> /// <typeparam name="TModule"></typeparam> /// <param name="services"></param> /// <param name="configuration"></param> /// <param name="moduleOptionsConfiguration"></param> /// <returns></returns> public static IServiceCollection AddRivenModule <TModule>(this IServiceCollection services, IConfiguration configuration, Action <ModuleOptions> moduleOptionsConfiguration = null) where TModule : IAppModule { // 模块配置 var moduleOptions = new ModuleOptions(); moduleOptionsConfiguration?.Invoke(moduleOptions); // 创建模块管理器 var moduleManager = new ModuleManager(moduleOptions); // 启动模块 moduleManager.StartModule <TModule>(services); // 配置服务 moduleManager.ConfigurationService(services, configuration); services.TryAddSingleton <IModuleManager>(moduleManager); return(services); }
public PhysicalFileModuleStore(IOptions <ModuleOptions> options) { _options = options.Value; }
// 'from' relative_module 'import' identifier ['as' name] (',' identifier ['as' name]) * // 'from' relative_module 'import' '(' identifier ['as' name] (',' identifier ['as' name])* [','] ')' // 'from' module 'import' "*" private FromImportStatement ParseFromImportStmt() { Eat(TokenKind.KeywordFrom); var start = GetStart(); ModuleName dname = ParseRelativeModuleName(); Eat(TokenKind.KeywordImport); bool ateParen = MaybeEat(TokenKind.LeftParenthesis); string[] names; string[] asNames; bool fromFuture = false; if (MaybeEat(TokenKind.Multiply)) { names = (string[])FromImportStatement.Star; asNames = null; } else { List<string> l = new List<string>(); List<string> las = new List<string>(); if (MaybeEat(TokenKind.LeftParenthesis)) { ParseAsNameList(l, las); Eat(TokenKind.RightParenthesis); } else { ParseAsNameList(l, las); } names = l.ToArray(); asNames = las.ToArray(); } // Process from __future__ statement if (dname.Names.Count == 1 && dname.Names[0] == "__future__") { if (!_fromFutureAllowed) { ReportSyntaxError(IronPython.Resources.MisplacedFuture); } if (names == FromImportStatement.Star) { ReportSyntaxError(IronPython.Resources.NoFutureStar); } fromFuture = true; foreach (string name in names) { if (name == "division") { _languageFeatures |= ModuleOptions.TrueDivision; } else if (name == "with_statement") { _languageFeatures |= ModuleOptions.WithStatement; } else if (name == "absolute_import") { _languageFeatures |= ModuleOptions.AbsoluteImports; } else if (name == "print_function") { _languageFeatures |= ModuleOptions.PrintFunction; _tokenizer.PrintFunction = true; } else if (name == "unicode_literals") { _tokenizer.UnicodeLiterals = true; _languageFeatures |= ModuleOptions.UnicodeLiterals; } else if (name == "nested_scopes") { } else if (name == "generators") { } else { string strName = name; fromFuture = false; if (strName != "braces") { ReportSyntaxError(IronPython.Resources.UnknownFutureFeature + strName); } else { // match CPython error message ReportSyntaxError(IronPython.Resources.NotAChance); } } } } if (ateParen) { Eat(TokenKind.RightParenthesis); } FromImportStatement ret = new FromImportStatement(dname, (string[])names, asNames, fromFuture, AbsoluteImports); ret.SetLoc(_globalParent, start, GetEnd()); return ret; }
public static ModuleOptions AddCountriesModule( this ModuleOptions options) { EnsureArg.IsNotNull(options, nameof(options)); EnsureArg.IsNotNull(options.Context, nameof(options.Context)); options.Context.AddTag("countries"); // enqueue data and do nothing === MOVED TO STARTUP === //options.Context.Services.AddSingleton<IQueue<CountriesExportData>>(sp => // AddQueue<T>(sp => ....) //{ // return new InMemoryQueue<CountriesExportData>(o => o // .Mediator(sp.GetService<IMediator>()) // .Tracer(sp.GetService<ITracer>()) // .LoggerFactory(sp.GetService<ILoggerFactory>()) // .NoRetries()); //}); //options.Context.Services.AddSingleton<IQueue<CountriesExportData>>(sp => // AddQueue<T>(sp => ....) //{ // return new AzureServiceBusQueue<CountriesExportData>(o => o // .Mediator(sp.GetService<IMediator>()) // .Tracer(sp.GetService<ITracer>()) // .LoggerFactory(sp.GetService<ILoggerFactory>()) // .ConnectionString(............) // .NoRetries()); //}); // dequeue and process data //options.Context.Services.AddQueueProcessItemsStartupTask<CountriesExportData>(new TimeSpan(0, 0, 30)); //options.Context.Services.AddScoped<ICountryRepository>(sp => //{ // return new CountryRepository( // new RepositoryTracingDecorator<Country>( // sp.GetService<ILogger<CountryRepository>>(), // sp.GetService<ITracer>(), // new RepositoryLoggingDecorator<Country>( // sp.GetRequiredService<ILogger<CountryRepository>>(), // new RepositoryTenantDecorator<Country>( // "naos_sample_test", // new RepositoryOrderDecorator<Country>( // e => e.Name, // new InMemoryRepository<Country, DbCountry>(o => o // .LoggerFactory(sp.GetRequiredService<ILoggerFactory>()) // .Mediator(sp.GetRequiredService<IMediator>()) // .Context(sp.GetRequiredService<InMemoryContext<Country>>()) // .Mapper(new AutoMapperEntityMapper(MapperFactory.Create())), // singleton // e => e.Identifier)))))); //}); //options.Context.Services.AddSingleton(sp => new InMemoryContext<Country>(new[] //{ // new Country { Code = "de", LanguageCodes = new[] {"de-de" }, Name = "Germany", TenantId = "naos_sample_test", Id = "de" }, // new Country { Code = "nl", LanguageCodes = new[] {"nl-nl" }, Name = "Netherlands", TenantId = "naos_sample_test", Id = "nl" }, // new Country { Code = "be", LanguageCodes = new[] {"fr-be", "nl-be" }, Name = "Belgium", TenantId = "naos_sample_test", Id = "be" }, //}.ToList())); options.Context.Services .AddScoped <IGenericRepository <Country> >(sp => { return(new InMemoryRepository <Country, DbCountry>(o => o .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .Mediator(sp.GetRequiredService <IMediator>()) .Context(sp.GetRequiredService <InMemoryContext <Country> >()) .Mapper(new AutoMapperEntityMapper(MapperFactory.Create())), // singleton e => e.Identifier)); }) .Decorate <IGenericRepository <Country>, RepositoryTracingDecorator <Country> >() .Decorate <IGenericRepository <Country>, RepositoryLoggingDecorator <Country> >() .Decorate <IGenericRepository <Country> >((inner, sp) => new RepositoryTenantDecorator <Country>("naos_sample_test", inner)) //.Decorate<IGenericRepository<Country>>((inner, sp) => new RepositoryIncludeDecorator<Country>(c => c.State, inner)) .Decorate <IGenericRepository <Country> >((inner, sp) => new RepositoryOrderDecorator <Country>(i => i.Name, inner)) .AddSingleton(sp => new InMemoryContext <Country>(new[] { new Country { Code = "de", LanguageCodes = new[] { "de-de" }, Name = "Germany", TenantId = "naos_sample_test", Id = "de" }, new Country { Code = "nl", LanguageCodes = new[] { "nl-nl" }, Name = "Netherlands", TenantId = "naos_sample_test", Id = "nl" }, new Country { Code = "be", LanguageCodes = new[] { "fr-be", "nl-be" }, Name = "Belgium", TenantId = "naos_sample_test", Id = "be" }, }.ToList())); options.Context.Services.AddSeederStartupTask <Country, IGenericRepository <Country> >(new[] { new Country { Code = "us", LanguageCodes = new[] { "en-us" }, Name = "United States", TenantId = "naos_sample_test", Id = "us" }, }, delay: new TimeSpan(0, 0, 3)); options.Context.Messages.Add("naos services builder: countries service added"); return(options); }
public void Reset(SourceUnit sourceUnit, ModuleOptions languageFeatures) { ContractUtils.RequiresNotNull(sourceUnit, "sourceUnit"); _sourceUnit = sourceUnit; _languageFeatures = languageFeatures; _token = new TokenWithSpan(); _lookahead = new TokenWithSpan(); _fromFutureAllowed = true; _functions = null; _privatePrefix = null; _parsingStarted = false; _errorCode = 0; }
public static ModuleOptions AddCustomersModule( this ModuleOptions options, string section = "naos:sample:customers") { EnsureArg.IsNotNull(options, nameof(options)); EnsureArg.IsNotNull(options.Context, nameof(options.Context)); options.Context.AddTag("customers"); // TODO: discover (how?) alle aggregates for this module options.Context.AddServiceClient <UserAccountsClient>(); var configuration = options.Context.Configuration?.GetSection($"{section}:cosmosDb").Get <CosmosConfiguration>() ?? new CosmosConfiguration(); options.Context.Services.AddScoped <ICustomerRepository>(sp => { return(new CustomerRepository( new RepositoryTracingDecorator <Customer>( sp.GetService <ILogger <CustomerRepository> >(), sp.GetService <ITracer>(), new RepositoryLoggingDecorator <Customer>( sp.GetRequiredService <ILogger <CustomerRepository> >(), new RepositoryTenantDecorator <Customer>( "naos_sample_test", new CosmosSqlRepository <Customer>(o => o .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .Mediator(sp.GetRequiredService <IMediator>()) .Provider(sp.GetRequiredService <ICosmosSqlProvider <Customer> >()))))))); // v3 //.Provider(new CosmosDbSqlProviderV2<Customer>( // v2 // logger: sp.GetRequiredService<ILogger<CosmosDbSqlProviderV2<Customer>>>(), // client: CosmosDbClientV2.Create(cosmosDbConfiguration.ServiceEndpointUri, cosmosDbConfiguration.AuthKeyOrResourceToken), // databaseId: cosmosDbConfiguration.DatabaseId, // collectionIdFactory: () => cosmosDbConfiguration.CollectionId, // partitionKeyPath: cosmosDbConfiguration.CollectionPartitionKey, // throughput: cosmosDbConfiguration.CollectionOfferThroughput, // isMasterCollection: cosmosDbConfiguration.IsMasterCollection))))))); }).AddScoped <ICosmosSqlProvider <Customer> >(sp => { return(new CosmosSqlProviderV3 <Customer>(o => o .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .Account(configuration.ServiceEndpointUri, configuration.AuthKeyOrResourceToken) .Database(configuration.DatabaseId) .PartitionKey(e => e.Region))); }).AddHealthChecks() .AddDocumentDb(s => { s.UriEndpoint = configuration.ServiceEndpointUri; s.PrimaryKey = configuration.AuthKeyOrResourceToken; }, name: $"{typeof(Customer).Name.Pluralize()}-cosmosdb"); options.Context.Services.AddScoped <IOrderRepository>(sp => { return(new OrderRepository( new RepositoryTracingDecorator <Order>( sp.GetService <ILogger <OrderRepository> >(), sp.GetService <ITracer>(), new RepositoryLoggingDecorator <Order>( sp.GetRequiredService <ILogger <OrderRepository> >(), new RepositoryTenantDecorator <Order>( "naos_sample_test", new CosmosSqlRepository <Order, DtoOrder>(o => o .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .Mediator(sp.GetRequiredService <IMediator>()) .Provider(sp.GetRequiredService <ICosmosSqlProvider <DtoOrder> >()) .Mapper(new AutoMapperEntityMapper(MapperFactory.Create())))))))); // v3 }).AddScoped <ICosmosSqlProvider <DtoOrder> >(sp => { return(new CosmosSqlProviderV3 <DtoOrder>(o => o .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .Account(configuration.ServiceEndpointUri, configuration.AuthKeyOrResourceToken) .Database(configuration.DatabaseId) .Container(typeof(Order).Name.Pluralize().ToLower()) .PartitionKey(e => e.Location))); }).AddHealthChecks() .AddDocumentDb(s => { s.UriEndpoint = configuration.ServiceEndpointUri; s.PrimaryKey = configuration.AuthKeyOrResourceToken; }, name: $"{typeof(Order).Name.Pluralize()}-cosmosdb"); options.Context.Services.AddSeederStartupTask <Customer, ICustomerRepository>(new[] { new Customer() { Id = "100fb10f-2ad4-4bd1-9b33-6410a5ce1b25", Email = "*****@*****.**", TenantId = "naos_sample_test", Gender = "Male", CustomerNumber = "AB-10010", FirstName = "John", LastName = "Doe", Region = "East" }, new Customer() { Id = "100fb10f-2ad4-4bd1-9b33-6410a5ce1b26", Email = "*****@*****.**", TenantId = "naos_sample_test", Gender = "Female", CustomerNumber = "AB-10020", FirstName = "Lisa", LastName = "Doe", Region = "West" }, new Customer() { Id = "100fb10f-2ad4-4bd1-9b33-6410a5ce1b27", Email = "*****@*****.**", TenantId = "naos_sample_test", Gender = "Male", CustomerNumber = "AB-10030", FirstName = "Paul", LastName = "Doe", Region = "East" }, }, delay: new TimeSpan(0, 0, 10)); var queueStorageConfiguration = options.Context.Configuration?.GetSection($"{section}:queueStorage").Get <QueueStorageConfiguration>(); options.Context.Services.AddSingleton <IQueue <Customer> >(sp => { var queue = new AzureStorageQueue <Customer>( new AzureStorageQueueOptionsBuilder() .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .ConnectionString(queueStorageConfiguration.ConnectionString).Build()); // for testing enqueue some items _ = queue.EnqueueAsync(new Customer()).Result; _ = queue.EnqueueAsync(new Customer()).Result; return(queue); }); options.Context.Services.AddHealthChecks() .AddAzureQueueStorage( queueStorageConfiguration.ConnectionString, name: "Customers-azurequeuestorage"); //options.Context.Services.AddSingleton<IValidator<CreateCustomerCommand>>(new CreateCustomerCommandValidator()); options.Context.Messages.Add("naos services builder: customers service added"); return(options); }
public static ModuleOptions AddInventoryModule( this ModuleOptions options, string section = "naos:sample:inventory") { EnsureArg.IsNotNull(options, nameof(options)); EnsureArg.IsNotNull(options.Context, nameof(options.Context)); options.Context.AddTag("inventory"); var configuration = options.Context.Configuration?.GetSection($"{section}:mongo").Get <MongoConfiguration>() ?? new MongoConfiguration(); options.Context.Services.AddMongoClient("inventory", configuration); options.Context.Services.AddScoped <IInventoryRepository>(sp => { return(new InventoryRepository( new RepositoryTracingDecorator <ProductInventory>( sp.GetService <ILogger <InventoryRepository> >(), sp.GetService <ITracer>(), new RepositoryLoggingDecorator <ProductInventory>( sp.GetRequiredService <ILogger <InventoryRepository> >(), new MongoRepository <ProductInventory>(o => o //.Setup(sp, mongoConfiguration) .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .Mediator(sp.GetRequiredService <IMediator>()) .MongoClient(sp.GetServices <IMongoClient>() .FirstOrDefault(c => c.Settings.ApplicationName == "inventory")) //TODO: make nice extension to get a named mongoclient .DatabaseName(configuration.DatabaseName)))))); }); options.Context.Services.AddScoped <IReplenishmentRepository>(sp => { return(new ReplenishmentRepository( new RepositoryTracingDecorator <ProductReplenishment>( sp.GetService <ILogger <ReplenishmentRepository> >(), sp.GetService <ITracer>(), new RepositoryLoggingDecorator <ProductReplenishment>( sp.GetRequiredService <ILogger <ReplenishmentRepository> >(), new MongoRepository <ProductReplenishment, ProductReplenishmentDocument>(o => o //.Setup(sp, mongoConfiguration) .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .Mediator(sp.GetRequiredService <IMediator>()) .MongoClient(sp.GetServices <IMongoClient>() .FirstOrDefault(c => c.Settings.ApplicationName == "inventory")) .Mapper(new AutoMapperEntityMapper(MapperFactory.Create())) .DatabaseName(configuration.DatabaseName) .CollectionName("ProductReplenishments")))))); }); options.Context.Services.AddSeederStartupTask <ProductInventory, IInventoryRepository>(new[] { new ProductInventory { Id = "548fb10e-2ad4-4bd1-9b33-6414a5ce7b10", Number = "AA1234", Quantity = 199, Region = "East" }, new ProductInventory { Id = "558fb10e-2ad4-4bd1-9b33-6414a5ce7b11", Number = "AA1234", Quantity = 188, Region = "West" }, new ProductInventory { Id = "558fb10f-2ad4-4bd1-9b33-6414a5ce7b12", Number = "BB1234", Quantity = 177, Region = "East" } }, delay: new TimeSpan(0, 0, 15)); //options.Context.Services.AddStartupTask(sp => // new SeederStartupTask( // sp.GetRequiredService<ILoggerFactory>(), // sp.CreateScope().ServiceProvider.GetService(typeof(IInventoryRepository)) as IInventoryRepository)); options.Context.Services.AddHealthChecks() .AddMongoDb(configuration.ConnectionString, name: "Inventory-mongodb"); options.Context.Messages.Add("naos services builder: inventory service added"); return(options); }
public TotemModule InitializeModule(string fileName, ModuleContext moduleContext, ScriptCode scriptCode, ModuleOptions options) { moduleContext.InitializeBuiltins(); moduleContext.Features = options; if ((options & ModuleOptions.Initialize) != 0) { scriptCode.Run(moduleContext.GlobalScope); } return moduleContext.Module; }
public static void HelloWorld(this ModuleOptions moduleOptions) { Console.WriteLine("Hello World LLittle Arctic Fox,Current Datetime : " + DateTime.Now); }
public static ModuleOptions AddUserAccountsModule( this ModuleOptions options, string connectionString = null, string section = "naos:sample:userAccounts:entityFramework", UserAccountsDbContext dbContext = null) { EnsureArg.IsNotNull(options, nameof(options)); EnsureArg.IsNotNull(options.Context, nameof(options.Context)); options.Context.AddTag("useraccounts"); if (dbContext != null) { options.Context.Services.AddSingleton(dbContext); // cross wiring, warning this will be a singleton (not scoped) } var configuration = options.Context.Configuration?.GetSection(section).Get <EntityFrameworkConfiguration>(); options.Context.Services.AddScoped <IGenericRepository <UserAccount> >(sp => { return(new UserAccountRepository( new RepositoryTracingDecorator <UserAccount>( sp.GetService <ILogger <UserAccountRepository> >(), sp.GetService <ITracer>(), new RepositoryLoggingDecorator <UserAccount>( sp.GetRequiredService <ILogger <UserAccountRepository> >(), //new RepositoryTenantDecorator<UserAccount>( //"naos_sample_test", // TODO: resolve from runtime context //new RepositorySoftDeleteDecorator<UserAccount>( new EntityFrameworkRepository <UserAccount>(o => o .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .Mediator(sp.GetRequiredService <IMediator>()) .DbContext(sp.GetRequiredService <UserAccountsDbContext>())))))); }); options.Context.Services.AddScoped <IGenericRepository <UserVisit> >(sp => { return(new UserVisitRepository( new RepositoryTracingDecorator <UserVisit>( sp.GetService <ILogger <UserVisitRepository> >(), sp.GetService <ITracer>(), new RepositoryLoggingDecorator <UserVisit>( sp.GetRequiredService <ILogger <UserVisitRepository> >(), new RepositoryTenantDecorator <UserVisit>( "naos_sample_test", // TODO: resolve from runtime context new RepositoryStateSoftDeleteDecorator <UserVisit>( new EntityFrameworkRepository <UserVisit>(o => o .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .Mediator(sp.GetRequiredService <IMediator>()) .DbContext(sp.GetRequiredService <UserAccountsDbContext>()) .Mapper(new AutoMapperEntityMapper(MapperFactory.Create()))))))))); }); options.Context.Services.AddDbContext <UserAccountsDbContext>(o => o //.UseSqlServer("Server=127.0.0.1;Database=naos_sample;User=sa;Password=Abcd1234!;Trusted_Connection=False;MultipleActiveResultSets=True;", o => o // docker //.UseSqlServer(configuration.ConnectionString.EmptyToNull() ?? $"Server=(localdb)\\mssqllocaldb;Database={nameof(UserAccountsDbContext)};Trusted_Connection=True;MultipleActiveResultSets=True;", o => o .UseSqlServer(configuration.ConnectionString, o => o .MigrationsHistoryTable("__MigrationsHistory", "useraccounts") .EnableRetryOnFailure()) .UseLoggerFactory(options.Context.Services.BuildServiceProvider().GetRequiredService <ILoggerFactory>()) //.ConfigureWarnings(w => w.Throw(RelationalEventId.QueryClientEvaluationWarning)) .EnableSensitiveDataLogging() .EnableDetailedErrors()); options.Context.Services.AddStartupTask <ApplyPendingMigrationsTask <UserAccountsDbContext> >(); options.Context.Services.AddStartupTask <EchoStartupTask>(new TimeSpan(0, 0, 3)); options.Context.Services.AddSeederStartupTask <UserAccountsDbContext, UserAccount>(new[] { new UserAccount() { Id = Guid.Parse("100fb10f-2ad4-4bd1-9b33-6410a5ce7b25"), Email = "*****@*****.**", TenantId = "naos_sample_test", AdAccount = AdAccount.For("East\\admin"), Status = UserAccountStatus.Active }, new UserAccount() { Id = Guid.Parse("100fb10f-2ad4-4bd1-9b33-6410a5ce7b26"), Email = "*****@*****.**", TenantId = "naos_sample_test", AdAccount = AdAccount.For("East\\test26"), Status = UserAccountStatus.Active }, new UserAccount() { Id = Guid.Parse("100fb10f-2ad4-4bd1-9b33-6410a5ce7b27"), Email = "*****@*****.**", TenantId = "naos_sample_test", AdAccount = AdAccount.For("East\\test27"), Status = UserAccountStatus.Active }, }, delay: new TimeSpan(0, 0, 10)); //options.Context.Services.AddStartupTask(sp => // new SeederStartupTask( // sp.GetRequiredService<ILoggerFactory>(), // sp.CreateScope().ServiceProvider.GetService(typeof(IGenericRepository<UserAccount>)) as IGenericRepository<UserAccount>)); options.Context.Services.AddHealthChecks() .AddSqlServer(configuration.ConnectionString, name: "UserAccounts-sqlserver"); options.Context.Services.AddHealthChecks() // https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-3.1#entity-framework-core-dbcontext-probe .AddDbContextCheck <UserAccountsDbContext>(name: "UserAccounts-dbcontext"); options.Context.Messages.Add("naos services builder: useraccounts service added"); return(options); }
public TotemCompilerOptions(ModuleOptions features) { _module = features; }
/// <summary> /// Called when parsing is complete, the body is built, the line mapping and language features are known. /// /// This is used in conjunction with the constructor which does not take a body. It enables creating /// the outer most PythonAst first so that nodes can always have a global parent. This lets an un-bound /// tree to still provide it's line information immediately after parsing. When we set the location /// of each node during construction we also set the global parent. When we name bind the global /// parent gets replaced with the real parent ScopeStatement. /// </summary> /// <param name="lineLocations">a mapping of where each line begins</param> /// <param name="body">The body of code</param> /// <param name="languageFeatures">The language features which were set during parsing.</param> public void ParsingFinished(int[] lineLocations, Statement body, ModuleOptions languageFeatures) { ContractUtils.RequiresNotNull(body, "body"); if (_body != null) { throw new InvalidOperationException("cannot set body twice"); } _body = body; _lineLocations = lineLocations; _languageFeatures = languageFeatures; }
public void ProcessRequest(MigClientRequest request) { var migCommand = request.Command; string streamContent = ""; ProgramBlock currentProgram; ProgramBlock newProgram; string sketchFile = "", sketchFolder = ""; // request.ResponseData = new ResponseStatus(Status.Ok); if (homegenie.ExecuteAutomationRequest(migCommand)) { // TODO: should it just return if the request has been already processed? } if (migCommand.Command.StartsWith("Macro.")) { switch (migCommand.Command) { case "Macro.Record": homegenie.ProgramManager.MacroRecorder.RecordingEnable(); break; case "Macro.Save": newProgram = homegenie.ProgramManager.MacroRecorder.SaveMacro(migCommand.GetOption(1)); request.ResponseData = newProgram.Address.ToString(); break; case "Macro.Discard": homegenie.ProgramManager.MacroRecorder.RecordingDisable(); break; case "Macro.SetDelay": switch (migCommand.GetOption(0).ToLower()) { case "none": homegenie.ProgramManager.MacroRecorder.DelayType = MacroDelayType.None; break; case "mimic": homegenie.ProgramManager.MacroRecorder.DelayType = MacroDelayType.Mimic; break; case "fixed": double secs = double.Parse( migCommand.GetOption(1), System.Globalization.CultureInfo.InvariantCulture ); homegenie.ProgramManager.MacroRecorder.DelayType = MacroDelayType.Fixed; homegenie.ProgramManager.MacroRecorder.DelaySeconds = secs; break; default: request.ResponseData = new ResponseStatus(Status.Error); break; } break; case "Macro.GetDelay": request.ResponseData = "{ \"DelayType\" : \"" + homegenie.ProgramManager.MacroRecorder.DelayType + "\", \"DelayOptions\" : \"" + homegenie.ProgramManager.MacroRecorder.DelaySeconds + "\" }"; break; default: request.ResponseData = new ResponseStatus(Status.Error); break; } } else if (migCommand.Command.StartsWith("Scheduling.")) { switch (migCommand.Command) { case "Scheduling.Add": case "Scheduling.Update": var newSchedule = JsonConvert.DeserializeObject <SchedulerItem>(request.RequestText); var item = homegenie.ProgramManager.SchedulerService.AddOrUpdate( newSchedule.Name, newSchedule.CronExpression, newSchedule.Data, newSchedule.Description, newSchedule.Script ); if (newSchedule.BoundDevices != null) { item.BoundDevices = newSchedule.BoundDevices; } if (newSchedule.BoundModules != null) { item.BoundModules = newSchedule.BoundModules; } homegenie.UpdateSchedulerDatabase(); break; case "Scheduling.ModuleUpdate": var mod = homegenie.Modules.Find((m) => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); if (mod == null) { break; } var scheduling = JsonConvert.DeserializeObject <dynamic>(request.RequestText); for (int i = 0; i < scheduling.include.Count; i++) { string name = scheduling.include[i].Value.ToString(); var schedulerItem = homegenie.ProgramManager.SchedulerService.Get(name); if (schedulerItem != null) { schedulerItem.BoundModules.RemoveAll((mr) => mr.Domain == mod.Domain && mr.Address == mod.Address); schedulerItem.BoundModules.Add(new ModuleReference() { Domain = mod.Domain, Address = mod.Address }); } } for (int i = 0; i < scheduling.exclude.Count; i++) { string name = scheduling.exclude[i].Value.ToString(); var schedulerItem = homegenie.ProgramManager.SchedulerService.Get(name); if (schedulerItem != null) { schedulerItem.BoundModules.RemoveAll((mr) => mr.Domain == mod.Domain && mr.Address == mod.Address); } } homegenie.UpdateSchedulerDatabase(); break; case "Scheduling.Get": request.ResponseData = homegenie.ProgramManager.SchedulerService.Get(migCommand.GetOption(0)); break; case "Scheduling.Enable": homegenie.ProgramManager.SchedulerService.Enable(migCommand.GetOption(0)); homegenie.UpdateSchedulerDatabase(); break; case "Scheduling.Disable": homegenie.ProgramManager.SchedulerService.Disable(migCommand.GetOption(0)); homegenie.UpdateSchedulerDatabase(); break; case "Scheduling.Delete": homegenie.ProgramManager.SchedulerService.Remove(migCommand.GetOption(0)); homegenie.UpdateSchedulerDatabase(); break; case "Scheduling.ListOccurrences": int hours = 24; int.TryParse(migCommand.GetOption(0), out hours); DateTime dateStart = DateTime.Today.ToUniversalTime(); string startFrom = migCommand.GetOption(1); if (!String.IsNullOrWhiteSpace(startFrom)) { dateStart = Utility.JavascriptToDate(long.Parse(startFrom)); } string cronExpression = migCommand.GetOption(2); List <dynamic> nextList = new List <dynamic>(); if (!String.IsNullOrEmpty(cronExpression)) { var evt = new { CronExpression = cronExpression, Occurrences = new List <double>() }; var d = dateStart; var dateEnd = dateStart.AddHours(hours); var occurs = homegenie.ProgramManager.SchedulerService.GetScheduling(dateStart, dateEnd, cronExpression); occurs.Sort(); foreach (var dt in occurs) { evt.Occurrences.Add(Utility.DateToJavascript(dt.ToUniversalTime())); } if (evt.Occurrences.Count > 0) { nextList.Add(evt); } } else { for (int s = 0; s < homegenie.ProgramManager.SchedulerService.Items.Count; s++) { var ce = homegenie.ProgramManager.SchedulerService.Items[s]; if (!ce.IsEnabled) { continue; } var evt = new { ce.Name, ce.Description, RunScript = !String.IsNullOrWhiteSpace(ce.Script), Occurrences = new List <double>() }; var d = dateStart; var dateEnd = dateStart.AddHours(hours); var occurs = homegenie.ProgramManager.SchedulerService.GetScheduling(dateStart, dateEnd, ce.CronExpression); occurs.Sort(); foreach (var dt in occurs) { evt.Occurrences.Add(Utility.DateToJavascript(dt.ToUniversalTime())); } if (evt.Occurrences.Count > 0) { nextList.Add(evt); } } } request.ResponseData = nextList; break; case "Scheduling.List": homegenie.ProgramManager.SchedulerService .Items.Sort((s1, s2) => String.Compare(s1.Name, s2.Name, StringComparison.Ordinal)); request.ResponseData = homegenie.ProgramManager.SchedulerService.Items; break; case "Scheduling.Describe": var cronDescription = ""; try { cronDescription = ExpressionDescriptor.GetDescription(migCommand.GetOption(0).Trim()); cronDescription = Char.ToLowerInvariant(cronDescription[0]) + cronDescription.Substring(1); } catch { } request.ResponseData = new ResponseText(cronDescription); break; case "Scheduling.SolarTimes": var solarTimes = new SolarTimes(DateTime.Now, homegenie.ProgramManager.SchedulerService.Location["latitude"].Value, homegenie.ProgramManager.SchedulerService.Location["longitude"].Value); request.ResponseData = solarTimes; break; default: request.ResponseData = new ResponseStatus(Status.Error); break; } } else if (migCommand.Command.StartsWith("Programs.")) { if (migCommand.Command != "Programs.Import") { streamContent = request.RequestText; } // switch (migCommand.Command) { case "Programs.Import": string archiveName = "homegenie_program_import.hgx"; if (File.Exists(archiveName)) { File.Delete(archiveName); } MIG.Gateways.WebServiceUtility .SaveFile(request.RequestData, archiveName); int newPid = homegenie.ProgramManager.GeneratePid(); newProgram = homegenie.PackageManager.ProgramImport(newPid, archiveName, migCommand.GetOption(0)); homegenie.UpdateProgramsDatabase(); request.ResponseData = new ResponseText(newProgram.Address.ToString()); break; case "Programs.Export": currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0))); string filename = currentProgram.Address + "-" + currentProgram.Name.Replace(" ", "_"); // var writerSettings = new System.Xml.XmlWriterSettings(); writerSettings.Indent = true; writerSettings.Encoding = Encoding.UTF8; var programSerializer = new XmlSerializer(typeof(ProgramBlock)); var builder = new StringBuilder(); var writer = System.Xml.XmlWriter.Create(builder, writerSettings); programSerializer.Serialize(writer, currentProgram); writer.Close(); // (request.Context.Data as HttpListenerContext).Response.AddHeader( "Content-Type", "application/octet-stream; charset=utf-8" ); // if (currentProgram.Type.ToLower() == "arduino") { string arduinoBundle = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "export", filename + ".zip"); if (File.Exists(arduinoBundle)) { File.Delete(arduinoBundle); } else if (!Directory.Exists(Path.GetDirectoryName(arduinoBundle))) { Directory.CreateDirectory(Path.GetDirectoryName(arduinoBundle)); } string mainProgramFile = Path.Combine(Path.GetDirectoryName(arduinoBundle), "program.hgx"); File.WriteAllText( mainProgramFile, builder.ToString() ); Utility.AddFileToZip(arduinoBundle, mainProgramFile, "program.hgx"); sketchFolder = Path.Combine("programs", "arduino", currentProgram.Address.ToString()); foreach (string f in Directory.GetFiles(sketchFolder)) { if (!Path.GetFileName(f).StartsWith("sketch_")) { Utility.AddFileToZip( arduinoBundle, Path.Combine(sketchFolder, Path.GetFileName(f)), Path.Combine( "src", Path.GetFileName(f) ) ); } } // byte[] bundleData = File.ReadAllBytes(arduinoBundle); (request.Context.Data as HttpListenerContext).Response.AddHeader( "Content-Disposition", "attachment; filename=\"" + filename + ".zip\"" ); (request.Context.Data as HttpListenerContext).Response.OutputStream.Write(bundleData, 0, bundleData.Length); } else { (request.Context.Data as HttpListenerContext).Response.AddHeader( "Content-Disposition", "attachment; filename=\"" + filename + ".hgx\"" ); request.ResponseData = builder.ToString(); } break; case "Programs.List": var programList = new List <ProgramBlock>(homegenie.ProgramManager.Programs); programList.Sort(delegate(ProgramBlock p1, ProgramBlock p2) { string c1 = p1.Name + " " + p1.Address; string c2 = p2.Name + " " + p2.Address; return(c1.CompareTo(c2)); }); request.ResponseData = programList; break; case "Programs.Get": try { var prg = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0))); var settings = new JsonSerializerSettings { Formatting = Formatting.Indented }; request.ResponseData = JsonConvert.SerializeObject(prg, settings); } catch (Exception ex) { request.ResponseData = new ResponseText("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Programs.Add": try { // This works with HG > 1.4.x newProgram = JsonConvert.DeserializeObject <ProgramBlock>(streamContent); } catch (Exception e) { // this is for backward compatibility with HG v1.3.x newProgram = new ProgramBlock() { Group = migCommand.GetOption(0), Name = streamContent, Type = "CSharp" }; } newProgram.Address = homegenie.ProgramManager.GeneratePid(); homegenie.ProgramManager.ProgramAdd(newProgram); homegenie.UpdateProgramsDatabase(); request.ResponseData = new ResponseText(newProgram.Address.ToString()); break; case "Programs.Clone": var copy = homegenie.ProgramManager .ProgramClone(int.Parse(migCommand.GetOption(0)), migCommand.GetOption(1)); homegenie.UpdateProgramsDatabase(); request.ResponseData = new ResponseText(copy.Address.ToString()); break; case "Programs.Delete": currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0))); if (currentProgram != null) { // TODO: remove groups associations as well homegenie.ProgramManager.ProgramRemove(currentProgram); homegenie.UpdateProgramsDatabase(); // remove associated module entry homegenie.Modules.RemoveAll(m => m.Domain == Domains.HomeAutomation_HomeGenie_Automation && m.Address == currentProgram.Address.ToString()); homegenie.UpdateModulesDatabase(); } break; case "Programs.Compile": case "Programs.Update": newProgram = JsonConvert.DeserializeObject <ProgramBlock>(streamContent); currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == newProgram.Address); // if (currentProgram == null) { newProgram.Address = homegenie.ProgramManager.GeneratePid(); homegenie.ProgramManager.ProgramAdd(newProgram); currentProgram = newProgram; } else { bool typeChanged = !string.Equals(currentProgram.Type, newProgram.Type, StringComparison.CurrentCultureIgnoreCase); currentProgram.Type = newProgram.Type; currentProgram.Group = newProgram.Group; currentProgram.Name = newProgram.Name; currentProgram.Description = newProgram.Description; currentProgram.AutoRestartEnabled = newProgram.AutoRestartEnabled; currentProgram.Cloneable = newProgram.Cloneable; if (typeChanged) { currentProgram.Engine.SetHost(homegenie); } currentProgram.IsEnabled = newProgram.IsEnabled; currentProgram.ScriptSetup = newProgram.ScriptSetup; currentProgram.ScriptSource = newProgram.ScriptSource; } // if (migCommand.Command == "Programs.Compile") { // reset previous error status currentProgram.IsEnabled = false; currentProgram.Engine.StopProgram(); currentProgram.ScriptErrors = ""; homegenie.ProgramManager.RaiseProgramModuleEvent( currentProgram, Properties.RuntimeError, "" ); // List <ProgramError> errors = homegenie.ProgramManager .ProgramCompile(currentProgram); currentProgram.IsEnabled = newProgram.IsEnabled && errors.Count == 0; currentProgram.ScriptErrors = JsonConvert.SerializeObject(errors); request.ResponseData = currentProgram.ScriptErrors; } else { request.ResponseData = new ResponseStatus(Status.Ok); } homegenie.UpdateProgramsDatabase(); // homegenie.modules_RefreshPrograms(); homegenie.modules_RefreshVirtualModules(); //homegenie.modules_Sort(); break; case "Programs.Arduino.FileLoad": sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0))); sketchFile = migCommand.GetOption(1); if (sketchFile == "main") { // "main" is a special keyword to indicate the main program sketch file sketchFile = ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0)); } sketchFile = Path.Combine(sketchFolder, Path.GetFileName(sketchFile)); request.ResponseData = new ResponseText(File.ReadAllText(sketchFile)); break; case "Programs.Arduino.FileSave": sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0))); sketchFile = Path.Combine(sketchFolder, Path.GetFileName(migCommand.GetOption(1))); File.WriteAllText(sketchFile, streamContent); break; case "Programs.Arduino.FileAdd": sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0))); if (!Directory.Exists(sketchFolder)) { Directory.CreateDirectory(sketchFolder); } sketchFile = Path.Combine(sketchFolder, Path.GetFileName(migCommand.GetOption(1))); if (File.Exists(sketchFile)) { request.ResponseData = new ResponseText("EXISTS"); } else if (!ArduinoAppFactory.IsValidProjectFile(sketchFile)) { request.ResponseData = new ResponseText("INVALID_NAME"); } else { StreamWriter sw = File.CreateText(sketchFile); sw.Close(); sw.Dispose(); sw = null; request.ResponseData = new ResponseText("OK"); } break; case "Programs.Arduino.FileDelete": sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0))); sketchFile = Path.Combine(sketchFolder, Path.GetFileName(migCommand.GetOption(1))); if (!File.Exists(sketchFile)) { request.ResponseData = new ResponseText("NOT_FOUND"); } else { File.Delete(sketchFile); request.ResponseData = new ResponseText("OK"); } break; case "Programs.Arduino.FileList": sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0))); List <string> files = new List <string>(); foreach (string f in Directory.GetFiles(sketchFolder)) { if (ArduinoAppFactory.IsValidProjectFile(f)) { files.Add(Path.GetFileName(f)); } } request.ResponseData = files; break; case "Programs.Run": currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0))); if (currentProgram != null) { // clear any runtime errors before running currentProgram.ScriptErrors = ""; homegenie.ProgramManager.RaiseProgramModuleEvent( currentProgram, Properties.RuntimeError, "" ); currentProgram.IsEnabled = true; System.Threading.Thread.Sleep(500); ProgramRun(migCommand.GetOption(0), migCommand.GetOption(1)); } break; case "Programs.Toggle": currentProgram = ProgramToggle(migCommand.GetOption(0), migCommand.GetOption(1)); break; case "Programs.Break": currentProgram = ProgramBreak(migCommand.GetOption(0)); break; case "Programs.Restart": currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0))); if (currentProgram != null) { currentProgram.IsEnabled = false; try { currentProgram.Engine.StopProgram(); } catch { } currentProgram.IsEnabled = true; homegenie.UpdateProgramsDatabase(); } break; case "Programs.Enable": currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0))); if (currentProgram != null) { currentProgram.IsEnabled = true; homegenie.UpdateProgramsDatabase(); } break; case "Programs.Disable": currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0))); if (currentProgram != null) { currentProgram.IsEnabled = false; try { currentProgram.Engine.StopProgram(); } catch { } homegenie.UpdateProgramsDatabase(); } break; case "Programs.OptionsGet": var programModule = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); if (programModule != null) { var options = new List <OptionField>(); var programOptions = new ModuleOptions() { id = programModule.Address, name = programModule.Name, description = programModule.Description, items = options }; programModule.Properties.ForEach((o) => { if (o.Name.StartsWith("ConfigureOptions.")) { var fieldType = o.FieldType.Split(':'); options.Add(new OptionField() { pid = programModule.Address, type = new OptionFieldType() { id = fieldType[0], options = fieldType.Skip(1).ToList <object>() }, name = o.Name, description = o.Description, field = new ModuleField() { key = o.Name, value = o.Value, timestamp = o.UpdateTime.ToString("o") } }); } }); options.Sort((o1, o2) => (o1.description).CompareTo(o2.description)); request.ResponseData = JsonConvert.SerializeObject(programOptions); } break; default: request.ResponseData = new ResponseStatus(Status.Error); break; } } else { request.ResponseData = new ResponseStatus(Status.Error); } }
public void Configure(ModuleOptions options, string section = "naos:sample:customers") { CompositionRoot.AddCustomersModule(options, section); }
public ModularityModule(ModuleOptions options, string[] contentDirectory) { Options = options; PhysicalFileDirectory = Path.GetFullPath(Path.Combine(Path.Combine(contentDirectory), options.Id)); }
/// <summary> /// 开启EF /// </summary> /// <param name="moduleOptions"></param> /// <param name="services"></param> /// <returns></returns> public static ModuleOptions AddEFCore <TDbContext>(this ModuleOptions moduleOptions, IServiceCollection services) where TDbContext : DbContext { services.AddSingleton(typeof(LAFDbContext), typeof(TDbContext)); services.AddScoped(typeof(IRepository <,>), typeof(Repository <,>)); return(moduleOptions); }
/// <summary> /// Creates a new PythonCompilerOptions with the specified language features enabled. /// </summary> public PythonCompilerOptions(ModuleOptions features) { _module = features; }
public Module(ModuleOptions options) { this.Code = options.Code; //etc... }
public static void InitializeModule(CodeContext/*!*/ context, ModuleOptions features) { context.ModuleContext.Features |= features; }
public LightModulePresenterBase CreateBase(ModuleOptions pModuleType, LightState pState) { return(Create(pState)); }