/// <summary> /// Initializes a new instance of the <see cref="View" /> class. /// </summary> public View() { InitializeGlobalFontStyle(); InitializeComponent(); var traceMonitor = new TraceMonitor(traceViewer, Dispatcher, traceQueue); traceMonitor.StartToMonitor(); Loaded += (s, e) => { scope.Add(ShowErrorNotificationKey, AppScope.Get(ShowErrorNotificationKey)); UserVisibleTrace = traceQueue.AddMessage; ClearUserVisibleTrace = traceMonitor.CleanAllMessages; scope.Update(Keys.Trace, traceQueue.AddMessage); historyPanel.Connect(scope); currentInvocationInfo.Connect(scope); historyPanel.Refresh(); scenarioEditor.Connect(scope); Title = "ApiInspector - " + AuthenticationUserName; }; ShutdownApplicationWhenClosed(this); }
public void AppScopeTest() { var builder = new ContainerBuilder(); builder.RegisterType <TestClass1>().AsSelf().SingleInstance(); builder.RegisterType <TestClass2>().AsSelf().InstancePerLifetimeScope(); IContainer cont = builder.Build(); using (var scope = new AppScope(cont)) { object r1 = scope.Resolve(typeof(TestClass1)); var r2 = scope.Resolve <TestClass1>(); Assert.AreSame(r1, r2); Assert.AreSame(cont, scope.Scope); var t1 = scope.Resolve <TestClass2>(); using (AppScope inner = scope.BeginScope()) { var t2 = inner.Resolve <TestClass2>(); Assert.AreNotSame(t1, t2); var resolvedScope = inner.Resolve <IAppScope>(); Assert.AreSame(inner, resolvedScope); } } }
/// <summary> /// Inicializa una nueva instancia de la clase <see cref="AspenRequest" />. /// </summary> /// <param name="appScope">Alcance de la aplicación solicitante.</param> /// <param name="url">URL del recurso solicitado.</param> /// <param name="method">Método o verbo HTTP para invocar el recurso.</param> /// <param name="deviceInfo">Información del dispositivo que envía la petición.</param> private AspenRequest(AppScope appScope, string url, Method method, IDeviceInfo deviceInfo) : base($"{(appScope == AppScope.Autonomous ? Routes.AutonomousRoot : Routes.DelegatedRoot)}{url}", method, DataFormat.Json) { Throw.IfNullOrEmpty(url, nameof(url)); const string ContentType = "application/json; charset=utf-8"; this.AddHeader("Accept", "application/json"); this.AddHeader("Content-Type", ContentType); this.Timeout = 15000; this.JsonSerializer = new RestSharp.Serialization.Json.JsonSerializer { ContentType = ContentType }; if (deviceInfo == null) { deviceInfo = CacheStore.GetDeviceInfo() ?? new DeviceInfo(); } switch (appScope) { case AppScope.Delegated: this.AddHeader("X-PRO-Request-DeviceInfo", deviceInfo.ToJson()); CacheStore.SetDeviceInfo(deviceInfo); break; case AppScope.Autonomous: break; default: throw new ArgumentOutOfRangeException(nameof(appScope), appScope, null); } }
public void AppCoreBuilderTest() { AppCoreBuilder.Create(new ContainerBuilder()).Build().Dispose(); using ( AppCore core = AppCoreBuilder.Create() .AddModule(new TestModule()) .AddModule <TestModule1>() .Configure(b => b.RegisterType <TestClass1>().AsSelf().SingleInstance()) .Build()) { using (AppScope scope = core.BeginScope()) { object r1 = scope.Resolve(typeof(TestClass1)); var r2 = scope.Resolve <TestClass1>(); Assert.AreSame(r1, r2); var t1 = scope.Resolve <TestClass2>(); using (AppScope inner = scope.BeginScope()) { var t2 = inner.Resolve <TestClass2>(); Assert.AreNotSame(t1, t2); } } } }
protected RouteStop(Route route, RouteStopKind kind, string codeName, Place defaultPlace = null) : this(route) { Kind = kind; var place = AppScope.GetPlace(codeName) ?? defaultPlace; Place = place ?? throw new ProgramError($"Unknown Place CodeName=\"{codeName ?? string.Empty}\""); }
/// <summary> /// Inicializa una nueva instancia de la clase <see cref="DefaultSettings"/> /// </summary> public DefaultSettings(AppScope appScope = AppScope.Autonomous) { this.AppScope = appScope; this.NonceGenerator = new GuidNonceGenerator(); this.EpochGenerator = new UnixEpochGenerator(); this.JsonSerializer = new JsonNetSerializer(); this.CustomHeaderManager = new CustomHeaderManager(); this.DeviceInfo = new DeviceInfo(); this.Proxy = null; this.Timeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds; }
public void Start() { if (_scope == null) { _core1 = AppCoreBuilder .Create() .AddModule(new RavenEmbeededDataStoreModule("Data") {RunInMemory = true}) .AddModule<RavenRepositoriesModule>() .Configure(b => { // Необходимо для работы AutofacCreationConverter b.RegisterType<TestObject>().PropertiesAutowired(); //b.RegisterType<TestObject1>(); }) .Build(); _scope = _core1.BeginScope(); //AutofacCreationConverter.Container = _core.Scope; } }
public RefrenceSession <TRefObject> GetRefrenceSession() { // Если _sessionFactory == null то создаем временый скоуп с продолжительностью жизни, // равной продолжительности жизни создаваемой сессии. Из этого скоупа временно резолвим _sessionFactory // и зануляем его после получения сессии. AppScope localScope = null; try { if (_sessionFactory == null || RepositoryFactory == null) { localScope = AppCore.Instance.BeginScope(); _sessionFactory = localScope.Resolve <Func <IDocumentSession> >(); RepositoryFactory = localScope.Resolve <Func <IDocumentSession, IRepository <TRefObject> > >(); } using (var rootSession = _sessionFactory()) { IDocumentSession session = rootSession.Advanced.DocumentStore.OpenSession(); IRepository <TRefObject> repository = RepositoryFactory(session); if (localScope != null) { _sessionFactory = null; RepositoryFactory = null; } return(new RefrenceSession <TRefObject>(repository, session, localScope)); } } catch { if (localScope != null) { localScope.Dispose(); } throw; } }
public void Start() { if (_scope == null) { _core1 = AppCoreBuilder .Create() .AddModule(new RavenEmbeededDataStoreModule("Data") { RunInMemory = true }) .AddModule <RavenRepositoriesModule>() .Configure(b => { // Необходимо для работы AutofacCreationConverter b.RegisterType <TestObject>().PropertiesAutowired(); //b.RegisterType<TestObject1>(); }) .Build(); _scope = _core1.BeginScope(); //AutofacCreationConverter.Container = _core.Scope; } }
//static readonly string _DriverA = AppModeString(AppMode.Driver, "Car A"); //static readonly string _DriverB = AppModeString(AppMode.Driver, "Car B"); async Task ChooseAppMode(Page page, SettingsSection section) { var modes = new List <string>() { _Market }; foreach (var _car in Car.List) { modes.Add(AppModeString(AppMode.Driver, _car)); } var result = await page.DisplayActionSheet("Application Mode", "Cancel", null, modes.ToArray()); AppMode mode; Car car = null; if (result == _Market) { mode = AppMode.Market; } else if (result.StartsWith("Driver, ")) { mode = AppMode.Driver; car = Car.ByName(result.Substring(8)); } else { return; } section.Value = AppModeString(mode, car); AppScope appScope = AppScope.Instance; appScope.ClearData(); appScope.Configure(mode, car); await appScope.ReloadData(); }
public async Task LoadInvoices(string carId) { var query = new QyeryBuilder(); query.SetSortByField(InvoiceRecord.SEQ); if (string.IsNullOrEmpty(carId)) { query.FilterByFormula = "{Date} >= TODAY()"; } else { query.FilterByFormula = $"And({{Date}} = TODAY(), {{Car}}=\"{carId}\")"; } //var records = await InvoicesTable.ListRecords(sortField: InvoiceRecord.SEQ); var result = await InvoicesTable.List(query); var records = result?.Records; if (records == null) { Debug.Print("InvoicesTable.List() returned no records"); return; } var invoices = AppScope.Instance.Invoices; int ord = 0; foreach (var rec in records) { var customer = AppScope.GetCustomer(rec.Customer); if (customer == null) { Debug.Print($"## AirStorage.LoadInvoices(): Unknown Customer {Dw.ToString(rec.Customer)}"); continue; } var invoice = new Invoice { RecordId = rec.Id, Seq = rec.Seq, Ordinal = ++ord, Date = rec.Date, CarId = rec.Car, Number = rec.Number, Customer = customer, Notes = rec.Notes }; var list = await ArticlesTable.FilterRecords($"{{{ArticleRecord.INVOICE_SEQ}}} = {invoice.Seq}"); foreach (var art in list.Records) { var produce = AppScope.GetProduce(art.Produce); if (produce == null) { Debug.Print($"## AirStorage.LoadInvoices(): Unknown Produce {Dw.ToString(art.Produce)}"); continue; } var article = new Article { RecordId = art.Id, Produce = produce, Quantity = art.Quantity, Unit = art.Unit, UnitPrice = art.UnitPrice, TotalPrice = art.TotalPrice, Note = art.Note }; invoice.Articles.Add(article); } invoices.Add(invoice); } }
public RefrenceSession(IRepository <TRefObject> repository, IDocumentSession session, AppScope scope = null) { _repository = repository; _session = session; _scope = scope; }
public void Start() { var services = _knownServices.ToArray(); Log.InfoFormat("Запуск WCF-хоста для {0} сервисов", services.Length); var hostName = _config.GetAppSettingString("Zen/Hostname"); if (string.IsNullOrEmpty(hostName)) { hostName = "localhost"; } var port = _config.GetAppSettingString("Zen/Port"); if (string.IsNullOrEmpty(port)) { port = "8080"; } foreach (var knownService in services) { Log.DebugFormat("Запуск хостов для типа: {0}", knownService.GetType().Name); IWebService service = knownService; var scope = AppScope.BeginScope(b => b.Register(ctx => this).As <WebserviceHostApplication>()); _hostScopes.Add(scope); _hostThreads.Add(new Thread(() => { var uriStr = string.Format("http://{0}:{1}/{2}", hostName, port, service.GetWebserviceName()); Uri address = new Uri(uriStr); foreach ( var webService in service.GetType() .GetInterfaces() .Where(i => i.GetCustomAttributes(typeof(ServiceContractAttribute), true).Any() && i != typeof(IWebService))) { try { Log.DebugFormat("Запуск хостов для типа: {0} по контракту {1}", service.GetType().Name, webService.Name); ServiceHost host = new ServiceHost(service.GetType(), address); host.AddServiceEndpoint(webService, new BasicHttpBinding(), string.Empty); host.AddDependencyInjectionBehavior(webService, scope.Scope); host.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true, HttpGetUrl = address }); _hosts.Add(host); host.Open(); var sb = new StringBuilder(); foreach (var ep in host.Description.Endpoints) { sb.AppendFormat( "Для контракта: {1} сервиса {2} производится прослушивание по адресу {0}", ep.Address.Uri.AbsoluteUri, ep.Contract.Name, service.GetType().Name) .AppendLine(); } Log.Info(sb.ToString()); var enumService = scope.Resolve <EnumeratorWebservice>(); if (enumService != null) { enumService.RegisterService(service); } } catch (Exception ex) { Log.Error(string.Format("Ошибка инициализации веб-сервиса {1}:{0}", webService.Name, service.GetType().Name), ex); } } })); } foreach (var hostThread in _hostThreads) { hostThread.Start(); } }
/// <summary> /// Obtiene el último token de autenticación generado o <see langword="null" /> si no se ha obtenido ninguno. /// </summary> /// <returns>Instancia que implementa <see cref="IAuthToken"/> con el valor del último token generado.</returns> internal static IAuthToken GetCurrentToken(AppScope scope) { string cacheKey = $"{scope.ToString()}|{TokenCacheKey}"; return(AppDomain.CurrentDomain.GetData(cacheKey) as IAuthToken); }
/// <summary> /// Guarda el último token de autenticación generado. /// </summary> /// <param name="authToken">Instancia del token que se debe guardar.</param> internal static void SetCurrentToken(IAuthToken authToken, AppScope scope) { string cacheKey = $"{scope.ToString()}|{TokenCacheKey}"; AppDomain.CurrentDomain.SetData(cacheKey, authToken); }
/// <summary> /// Inicializa un objeto que permite la conexión con el sistema Aspen. /// </summary> /// <param name="appScope">Alcance de la aplicación que se está conectando.</param> /// <returns>Instancia de <see cref="IEndPointSettings" /> que permite establecer la configuración de conexión.</returns> public static IEndPointSettings Initialize(AppScope appScope = AppScope.Autonomous) { ISettings customSettings = new DefaultSettings(appScope); return(new AspenClient(customSettings)); }
public override void Initialize() { EnableSsl = GetBool("EnableSsl", false); EnableIndexConfiguration = GetBool("EnableIndexConfiguration", true); EnableApplyDataSourceResources = GetBool("EnableApplyDataSourceResources", true); if (AppScope == null) { AppScope = String.Empty; } AppMode = GetEnum <AppMode>("AppMode", AppMode.Local); AppScope = GetString("AppScope", String.Empty); ApiUrl = GetString("ApiUrl", "http://*****:*****@foundatio.com"); AllowedOutboundAddresses = GetStringList("AllowedOutboundAddresses", "foundatio.com,slideroom.com,mailinator.com").Select(v => v.ToLower()).ToList(); RunJobsInProcess = GetBool("RunJobsInProcess", true); LogJobLocks = GetBool("LogJobLocks", false); LogJobEvents = GetBool("LogJobEvents", false); LogJobCompleted = GetBool("LogJobCompleted", false); EnableSignalR = GetBool("EnableSignalR", true); ApiThrottleLimit = GetInt("ApiThrottleLimit", Int32.MaxValue); MetricsServer = GetString("MetricsServer"); MetricsServerPort = GetInt("MetricsServerPort", 8125); string environment = !AppScope.IsNullOrEmpty() ? AppScope : (AppMode == AppMode.Production ? "prod" : "qa"); MetricsPrefix = GetString("MetricsPrefix", environment + "-" + Environment.MachineName); EnableMetricsReporting = GetBool("EnableMetrics", true); IntercomAppId = GetString("IntercomAppId"); IntercomAppSecret = GetString("IntercomAppSecret"); EnableAccountCreation = GetBool("EnableAccountCreation", true); EnableAccountInvites = GetBool("EnableAccountInvites", true); GoogleAppId = GetString("GoogleAppId"); GoogleAppSecret = GetString("GoogleAppSecret"); MicrosoftAppId = GetString("MicrosoftAppId"); MicrosoftAppSecret = GetString("MicrosoftAppSecret"); FacebookAppId = GetString("FacebookAppId"); FacebookAppSecret = GetString("FacebookAppSecret"); GitHubAppId = GetString("GitHubAppId"); GitHubAppSecret = GetString("GitHubAppSecret"); TwitterAuthorizationToken = GetString("TwitterAuthorizationToken", "AAAAAAAAAAAAAAAAAAAAAJfGewAAAAAA2W0TL6w2eO%2B7eJvzsM5e%2BDaSt3A%3DRVa0RVBzDwu3NhRz6cDWEaoT5t97fqjCFH2TgD2rcIUC6BPJkL"); ClearbitToken = GetString("ClearbitToken", "8eb88fc4c70a0635e70bdc776f7d68c1"); StripeApiKey = GetString("StripeApiKey"); GeocodeApiKey = GetString("GeocodeApiKey"); EnableGeocoding = GetBool("EnableGeocoding", !String.IsNullOrEmpty(GeocodeApiKey)); StripePublishableApiKey = GetString("StripePublishableApiKey"); StorageFolder = GetString("StorageFolder", "|DataDirectory|\\storage"); PublicStorageUrlPrefix = GetString("PublicStorageUrlPrefix", "http://localhost:51000/" + AppScopePrefix + "public"); if (PublicStorageUrlPrefix.EndsWith("/")) { PublicStorageUrlPrefix = PublicStorageUrlPrefix.TrimEnd('/'); } MailUser = GetString("MailUser"); MailPassword = GetString("MailPassword"); PassPhrase = GetString("PassPhrase"); BulkBatchSize = GetInt("BulkBatchSize", 1000); ExceptionlessApiKey = GetString("ExceptionlessApiKey", "gUgqSb34oNAW80wKje6cDFRQnLynUz4idSSjuUPD"); RedisConnectionString = GetConnectionString("RedisConnectionString"); EnableRedis = GetBool("EnableRedis", !String.IsNullOrEmpty(RedisConnectionString)); PrivateAzureStorageConnectionString = GetConnectionString("PrivateAzureStorageConnectionString"); PrivateAzureStorageContainerName = GetString("PrivateAzureStorageContainerName") ?? AppScopePrefix + "private"; PublicAzureStorageConnectionString = GetConnectionString("PublicAzureStorageConnectionString", PrivateAzureStorageConnectionString); PublicAzureStorageContainerName = GetString("PublicAzureStorageContainerName") ?? AppScopePrefix + "public"; EnableAzureStorage = GetBool("EnableAzureStorage", !String.IsNullOrEmpty(PrivateAzureStorageConnectionString)); PrivateS3StorageConnectionString = GetConnectionString("PrivateS3StorageConnectionString"); PublicS3StorageConnectionString = GetConnectionString("PublicS3StorageConnectionString", PrivateS3StorageConnectionString); bool isSingleS3 = PrivateS3StorageConnectionString == PublicS3StorageConnectionString; PrivateS3StorageFolder = GetString("PrivateS3StorageFolder") ?? (isSingleS3 ? "private/" + AppScope : AppScope); if (PrivateS3StorageFolder.EndsWith("/")) { PrivateS3StorageFolder = PrivateS3StorageFolder.TrimEnd('/'); } PublicS3StorageFolder = GetString("PublicS3StorageFolder") ?? (isSingleS3 ? "public/" + AppScope : AppScope); if (PublicS3StorageFolder.EndsWith("/")) { PublicS3StorageFolder = PublicS3StorageFolder.TrimEnd('/'); } EnableS3Storage = GetBool("EnableS3Storage", !String.IsNullOrEmpty(PrivateS3StorageConnectionString)); ElasticSearchConnectionString = GetConnectionString("ElasticSearchConnectionString", "http://localhost:9200"); try { var versionInfo = FileVersionInfo.GetVersionInfo(typeof(Settings).Assembly.Location); Version = versionInfo.FileVersion; InformationalVersion = versionInfo.ProductVersion; } catch { } }
public void AppScopeTest() { var builder = new ContainerBuilder(); builder.RegisterType<TestClass1>().AsSelf().SingleInstance(); builder.RegisterType<TestClass2>().AsSelf().InstancePerLifetimeScope(); IContainer cont = builder.Build(); using (var scope = new AppScope(cont)) { object r1 = scope.Resolve(typeof (TestClass1)); var r2 = scope.Resolve<TestClass1>(); Assert.AreSame(r1, r2); Assert.AreSame(cont, scope.Scope); var t1 = scope.Resolve<TestClass2>(); using (AppScope inner = scope.BeginScope()) { var t2 = inner.Resolve<TestClass2>(); Assert.AreNotSame(t1, t2); var resolvedScope = inner.Resolve<IAppScope>(); Assert.AreSame(inner,resolvedScope); } } }
public IList<App> GetAppList(AppScope scope) { Tuple<DataTable> appsTuple = AppsDbInteractor.Instance.GetAppList((int)scope); List<App> appsList = new List<App>(); DataTable appTable = appsTuple.Item1; foreach (DataRow row in appTable.Rows) { appsList.Add(ConvertToApp(appTable, row)); } return appsList; }
public AutofacCreationConverter(AppScope scope) { Container = (AppScope)scope; }
public HardCodedSettings(INonceGenerator nonceGenerator = null, IEpochGenerator epochGenerator = null, AppScope appScope = AppScope.Autonomous) { this.AppScope = appScope; if (nonceGenerator != null) { this.NonceGenerator = nonceGenerator; } if (epochGenerator != null) { this.EpochGenerator = epochGenerator; } }