private Task saveTweet(MatchedTweetReceivedEventArgs e) { Gof.Twitter.Tweet tweet = formatTweet(e); IPersistence persistence = ServiceExtensions.GetPersistenceService(e.Tweet.CreatedBy.Name); return(persistence.SaveRawTweetAsync(tweet)); }
public static ServiceExtensions AddControllersWithViews(this ServiceExtensions services) { var builder = services.Services.AddControllersWithViews(options => { // add the "feature" convention options.Conventions.Add(new FeatureConvention()); // Auto add [Area("areaName"] to controllers. options.Conventions.Add(new AutoAreaConvention()); }) .AddRazorOptions(options => { // using the "feature" convention, expand the paths options.ViewLocationExpanders.Add(new FeatureViewLocationExpander()); }) .AddFluentValidation(); if (services.Env.IsDevelopment()) { builder.AddRazorRuntimeCompilation(); } services.Services.Configure <RouteOptions>(options => { options.LowercaseUrls = true; }); return(services); }
private static void Main() { var conf = new Configuration(ExecutionEnvironment.Test); BootStrapDependencies(conf); HostFactory.Run(x => { RunAsExtensions.RunAs(x, conf.ServiceUserName, conf.ServiceUserPasswordEncrypted); x.SetDescription("Calculates and provides calendar and product info data."); StartModeExtensions.StartManually(x); x.SetDisplayName(conf.ServiceDisplayName); x.SetServiceName(conf.ServiceName); ServiceExtensions.Service <PricingService>(x, s => { s.ConstructUsing( name => new PricingService(ResolutionExtensions.Resolve <Configuration>(Container))); ServiceConfiguratorExtensions.WhenStarted <PricingService>(s, tc => tc.OnStart()); ServiceConfiguratorExtensions.WhenStopped <PricingService>(s, tc => tc.OnStop()); ServiceConfiguratorExtensions.WhenShutdown <PricingService>(s, tc => tc.OnStop()); }); InstallHostConfiguratorExtensions.BeforeInstall(x, () => NetShellCmdLineTool.RegisterHttpNamespace(conf)); UninstallHostConfiguratorExtensions.AfterUninstall(x, () => NetShellCmdLineTool.UnregisterHttpNamespace(conf)); }); }
private async Task saveTweet(MatchedTweetReceivedEventArgs e, string keyword) { var tweet = formatTweet(e); tweet.Keyword = keyword; //we use keyword hashcode as partition key, it is assumed to be sparse IPersistence persistence = ServiceExtensions.GetPersistenceService(keyword); try { if (e.Tweet.IsRetweet) { await persistence.SaveReTweetAsync(tweet); } else { await persistence.SaveTweetAsync(tweet); } } catch (Exception ex) { ServiceEventSource.Current.ServiceMessage(this, "Tweet store failed: {0}\r\n\t{1}", e.Tweet.Text, ex.Message); throw; } }
public void Setup() { Assembly assembly = typeof(TestImplementation).Assembly; result = ServiceExtensions .GetServiceDeclarations(new[] { assembly }) .ToArray(); }
public App() { if (!ServiceExtensions.IsStarted("MSSQLServer", true)) { Log.Write("Microsoft SQL Server is not started"); Application.Current.Shutdown(); } }
public static void AddValidators(this ServiceExtensions services, Assembly assembly) { // Add all of our validators foreach (var validator in ValidatorDiscovery.DiscoverValidators(assembly)) { services.Services.AddTransient(validator.Interface, validator.Implementation); } }
private bool PromptForPreviewOutOfBrowserToggle() { return(ServiceExtensions.MessageDisplayService(this.Services).ShowMessage(new MessageBoxArgs() { Message = StringTable.UsePlatformExtensionsCommandPreviewOutOfBrowserEnabledWarningMessage, Button = MessageBoxButton.YesNo, Image = MessageBoxImage.Exclamation }) == MessageBoxResult.Yes); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (MigrationConfiguration.IsBuildForMigrations) { IConfiguration configuration = MigrationConfiguration.Configuration; ServiceExtensions.ConfigureOptions(configuration) .Invoke(optionsBuilder); } }
public SilverlightAssemblyResolver(AppDomain appDomain, IServiceProvider serviceProvider) { this.projectManager = ServiceExtensions.ProjectManager(serviceProvider); this.platformService = ServiceExtensions.GetService <IPlatformService>(serviceProvider); this.satelliteAssemblyResolver = ServiceExtensions.GetService <ISatelliteAssemblyResolver>(serviceProvider); this.messageService = ServiceExtensions.GetService <IMessageDisplayService>(serviceProvider); this.appDomain = appDomain; this.appDomain.AssemblyLoad += new AssemblyLoadEventHandler(this.AppDomain_AssemblyLoad); }
//添加autofac的DI配置容器 public void ConfigureContainer(ContainerBuilder builder) { //注册IBaseService和IRoleService接口及对应的实现类 //builder.RegisterType<BaseService>().As<IBaseService>().InstancePerLifetimeScope(); //builder.RegisterType<RoleService>().As<IRoleService>().InstancePerLifetimeScope(); //注册aop拦截器 //将业务层程序集名称传了进去,给业务层接口和实现做了注册,也给业务层各方法开启了代理 builder.AddAopService(ServiceExtensions.GetAssemblyName()); }
private bool PromptForPlatformExtensionsToggle() { return(ServiceExtensions.MessageDisplayService(this.Services).ShowMessage(new MessageBoxArgs() { Message = StringTable.PreviewOutOfBrowserCommandUsePlatformExtensionsEnabledWarning, Button = MessageBoxButton.YesNo, Image = MessageBoxImage.Exclamation, AutomationId = "TogglePlatformExtensionsDialog" }) == MessageBoxResult.Yes); }
public void ConfigureServices(IServiceCollection services) { ServiceExtensions.ConfigureCors(services); ServiceExtensions.AddScoped(services); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddDbContext <PlanetDatabaseContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:PlanetDatabaseConnection"])); }
private static void SetupDependencies(IServiceCollection services) { var configurationBuilder = ServiceExtensions.BuildConfigurationBuilder(); var configuration = configurationBuilder.Build(); services.AddSingleton <IConfiguration>(configuration); ServiceExtensions.RegisterDependencyInjections(services, configuration); Provider = services.BuildServiceProvider(); }
//添加autofac的DI配置容器 public void ConfigureContainer(ContainerBuilder builder) { //注册IUserService和UserService接口及对应的实现类 builder.RegisterType <UserService>().As <IUserService>().InstancePerLifetimeScope(); builder.RegisterType <ColumnService>().As <IColumnService>().InstancePerLifetimeScope(); builder.RegisterType <ContentService>().As <IContentService>().InstancePerLifetimeScope(); //注册aop拦截器 //将业务层程序集名称传了进去,给业务层接口和实现做了注册,也给业务层各方法开启了代理 builder.AddAopService(ServiceExtensions.GetAssemblyName()); } //依赖注入
public void Setup() { IEnumerable <ServiceDescriptor> serviceDescriptors = new ServiceDescriptor[0]; subject = new Mock <IServiceCollection>(); subject .Setup(instance => instance.GetEnumerator()) .Returns(serviceDescriptors.GetEnumerator()); ServiceExtensions.RegisterServices(subject.Object, new[] { typeof(ITransientInterface).Assembly }); }
public void Setup() { ServiceCollection subject = new ServiceCollection(); ServiceDeclaration singletonOneDeclaration = new ServiceDeclaration(typeof(TestImplementation), typeof(TestImplementation), ServiceScope.Singleton); ServiceDeclaration singletonTwoDeclaration = new ServiceDeclaration(typeof(TestImplementation), typeof(TestImplementation), ServiceScope.Singleton); ServiceExtensions.AddService(subject, singletonOneDeclaration); ServiceExtensions.AddService(subject, singletonTwoDeclaration); result = subject.BuildServiceProvider(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } // app.UseHttpsRedirection (); if ((!env.IsEnvironment("Backend"))) { app.UseSpaStaticFiles(); } app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); app.UseResponseCaching(); app.UseRouting(); app.UseCors(MyAllowSpecificOrigins); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); if ((!env.IsEnvironment("Backend"))) { endpoints.MapToVueCliProxy( "{*path}", new SpaOptions { SourcePath = "ClientApp" }, npmScript: (env.IsEnvironment("Backend") ? null : "serve"), regex: "Compiled successfully", forceKill: true ); } }); ServiceExtensions.CreateDefaultRolesAndUser(serviceProvider).Wait(); }
public Function() { Services = ServiceExtensions.BuildServiceProvider(); var needsInjection = GetType().GetProperties() .Where(p => p.GetCustomAttribute <InjectAttribute>() != null); foreach (var prop in needsInjection) { prop.SetValue(this, Services.GetRequiredService(prop.PropertyType)); } }
public void RandomIntTest() { var list = new List <string>() { "1", "2", "3" }; for (int i = 0; i < 50; i++) { var ret = ServiceExtensions.RandomInt(list); Console.WriteLine(ret); } }
public void Setup() { IEnumerable <ServiceDescriptor> serviceDescriptors = new ServiceDescriptor[0]; services = new Mock <IServiceCollection>(); services .Setup(instance => instance.GetEnumerator()) .Returns(serviceDescriptors.GetEnumerator()); ServiceDeclaration declaration = new ServiceDeclaration(typeof(ITransientInterface), typeof(TestImplementation), declartionScope); ServiceExtensions.AddService(services.Object, declaration); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { ServiceExtensions.ConfigureRepositoryWrapper(services); ServiceExtensions.ConfigureBusinessWrapper(services); services.AddAutoMapper(typeof(Startup)); services.AddControllersWithViews(o => o.Filters.Add(new AuthorizeFilter())) .AddRazorRuntimeCompilation(); services.AddMemoryCache(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(); services.AddRazorPages(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //Dum: se agrega la inyeccion para el logger //services.AddSingleton<ILoggerManager, LoggerManager>(); services.ConfigureLoggerService(); //Dum: se realiza una clase que contiene la configuración y se inyecta la configuración para base de datos. //services.ConfiguracionSqlContext(Configuration); services.AddDbContext <NatilleraDBContext>(opcion => opcion.UseSqlServer(Configuration.GetValue <string>("ConnectionString:DataBaseConexion"))); //Dum: manejo del token. services.AddIdentity <ApplicationUser, IdentityRole>() .AddEntityFrameworkStores <NatilleraDBContext>() .AddDefaultTokenProviders(); //Dum: se inyecta el contenedor del repositorio //services.ConfiguracionRepositoryContenedor(); //Dum: se injectan los servicios de las capas de repositorio y servicios. ServiceExtensions.AddResgistro(services); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //DUM: Inicio configuración swagger, Install-Package Swashbuckle.AspNetCore services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "Swagger Api Natillera", Description = "Servicio para la administración de la información de natilleras", TermsOfService = "No Aplica", Contact = new Contact() { Name = "Talking Dotnet", Email = "*****@*****.**", Url = "www.talkingdotnet.com" } }); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.DocInclusionPredicate((docName, description) => true); c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); c.IncludeXmlComments(xmlPath); }); //DUM: Final Configuración Swagger }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { ServiceExtensions.ConfigureServices(services); ServiceExtensions.ConfigureCors(services); services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddApiExplorer(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Music World WebAPI", Description = "Music World API details", Version = "v1" }); }); }
public async Task <IActionResult> Index() { IEnumerable <string> influencers = null; try { IPersistence persistence = ServiceExtensions.GetPersistenceService(); influencers = await persistence.RetrieveInfluencerListAsync(); } catch (Exception ex) { //TODO:log influencers = new List <string>(); Trace.TraceError("{0}: {1}", ex.Message, ex.StackTrace); } return(View(influencers)); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerManager logger) { app.UseProblemDetails(); ////TODO: remove after testing //app.UseDeveloperExceptionPage(); //if (env.IsDevelopment()) //{ // app.UseDeveloperExceptionPage(); //} //else //{ // // added from book, what is that ? // app.UseHsts(); //} ServiceExtensions.UpdateDatabase(app); //TODO: remove after testing //app.ConfigureExceptionHandler(logger); app.UseHttpsRedirection(); // enables using static files for the request. If we don’t set a path to the static files directory, it will use a wwwroot folder in our project by default. app.UseStaticFiles(); app.UseCors("CorsPolicy"); // will forward proxy headers to the current request. This will help us during application deployment. app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.All }); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
protected static byte[] CHUIDFull(UInt16 fascnAgencyCode, UInt16 fascnSystemSiteCode, UInt32 fascnCredentialNumber, IEnumerable <byte> guid, byte[] expirationDate) { if (null == expirationDate) { throw new ArgumentNullException("expirationDate"); } if (8 != expirationDate.Count()) { throw new ArgumentException("expirationDate: array should be of size 8"); } ServiceExtensions.CheckCryptoLibary(); var value = buildTLV(0x30, FASCN(fascnAgencyCode, fascnSystemSiteCode, fascnCredentialNumber)).Concat(buildTLV(0x34, GUID(guid))) .Concat(buildTLV(0x35, expirationDate)); return(buildTLV(0xEE, value.Concat(buildTLV(0x3E, Crypto.CryptoUtils.SignCHUIDByRandomKeyPair(value))))); }
public static void Main(string[] args) { var services = new ServiceCollection(); ServiceExtensions.AddKeysToEnvironment(services); SetupDependencies(services); #pragma warning disable CS0612 // Type or member is obsolete AutoMapperConfig.Start(); #pragma warning restore CS0612 // Type or member is obsolete var handleCompList = Provider.GetService <HandleCompanyList>(); var handleFin = Provider.GetService <HandleFinacials>(); _logger = Provider.GetService <ILogger <Program> >(); _logger.LogDebug("Application Started"); var compDetailsLst = handleCompList.GetAllCompaniesFromDbAsync().Result; if (compDetailsLst == null || compDetailsLst.Count < 2357) { compDetailsLst = handleCompList.GetAllCompaniesAsync().Result; } _ = handleCompList.GetAllCompaniesAsync().Result; Console.WriteLine("Obtained list of companies"); //UpdateDataFromExternalFeed(compDetailsLst); try { var wav = Provider.GetService <WriteAnalyzedValues>(); var wavResult = wav.UpdateAnalysis(); wavResult.Wait(); } catch (Exception ex) { _logger.LogCritical($"Error parsing and writing s/s \n{ex.Message}"); } Console.WriteLine("Done"); _logger.LogDebug("Done"); //Provider.GetService() }
private IProject FindXapSourceProject(IProject targetProject, out DocumentReference xapDeploymentDirectory) { xapDeploymentDirectory = (DocumentReference)null; IProject project = (IProject)null; if (targetProject is SilverlightProject && targetProject.GetCapability <bool>("CanBeStartupProject")) { project = targetProject; if (project.FullTargetPath != null) { xapDeploymentDirectory = DocumentReference.Create(PathHelper.GetDirectoryNameOrRoot(project.FullTargetPath)); } } else { ISolution currentSolution = ServiceExtensions.ProjectManager(this.serviceProvider).CurrentSolution; IProjectOutputReferenceResolver referenceResolver = currentSolution as IProjectOutputReferenceResolver; if (currentSolution != null && referenceResolver != null) { foreach (IProject sourceProject in currentSolution.Projects) { Uri deploymentResolvedRoot = referenceResolver.GetDeploymentResolvedRoot(sourceProject); if (deploymentResolvedRoot != (Uri)null) { DocumentReference documentReference = DocumentReference.Create(deploymentResolvedRoot.LocalPath); if (documentReference.Path.StartsWith(targetProject.ProjectRoot.Path, StringComparison.OrdinalIgnoreCase)) { xapDeploymentDirectory = documentReference; project = sourceProject; break; } } } } } return(project); }
//This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public async void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // app.UseHsts(); } //exception handling for 401 and 500 app.UseExceptionHandler(appBuilder => { appBuilder.Use(async(context, next) => { var error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature; //when authorization has failed, should retrun a json message to client if (error != null && error.Error is SecurityTokenExpiredException) { context.Response.StatusCode = 401; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(new { status = 401, message = "Its either token has expired or incorrect", error = "Forbidden route" })); } //when orther error, retrun a error message json to client else if (error != null && error.Error != null) { context.Response.StatusCode = 500; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(new { status = 500, message = "Internal Server Error", error = error.Error.Message })); } //when no error, do next. else { await next(); } }); }); app.UseStaticFiles(); //add swagger middleware and ui app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "JK Api V1"); }); app.UseSecureHeadersMiddleware(ServiceExtensions.BuildDefaultConfiguration()); app.UseAuthentication(); //app.UseHttpsRedirection(); app.UseMvc(); app.UseCors(); }