public async Task <IVehicleState> SendEvent(IVehicleState state, string IMEI, string Vin = null) { var simulatedEvent = _container.Resolve <IMachineRequest>(); simulatedEvent.IMEI = IMEI; simulatedEvent.DeviceTime = DateTimeOffset.UtcNow; simulatedEvent.Vehicle = state.Vehicle; simulatedEvent.TelematicDevice = state?.TelematicDevice; if (simulatedEvent.TelematicDevice == null) { simulatedEvent.TelematicDevice = _container.Resolve <IMachineTelematicDevice>(); } simulatedEvent.Vehicle.VIN = Vin; simulatedEvent.TelematicDevice.IMEI = IMEI; var result = await Client.Simulate(simulatedEvent); if (result.Success) { var id = Guid.Empty; Guid.TryParse(result.Response, out id); state.MessageId = id; } return(state); }
public Type GetType(string actorName) { if (_container.IsRegistered <IActorRef>(actorName)) { return(_container.Resolve <IActorRef>(actorName)?.GetType()); } return(null); }
public async Task ExecutePostRegistrationStep(IDIContainer container, CancellationToken cancellationToken = default(CancellationToken)) { var config = container.Resolve <IConfiguration>(); var appData = config.AppDataDirectory; var log = container.Resolve <ILogFactory>().CreateLog(this.GetType()); if (!System.IO.Directory.Exists(appData.FullName)) { System.IO.Directory.CreateDirectory(appData.FullName); } await LoadUsersAsync(log, container, config); }
public async Task ExecutePostRegistrationStep(IDIContainer container, CancellationToken cancellationToken = default(CancellationToken)) { var config = container.Resolve <IConfiguration>(); var enabled = config.GetValueOrDefault("MQTT:Server:Enabled", true); if (enabled) { var port = config.GetValueOrDefault("MQTT:Server:Port", 1889); var broker = new MqttBroker(); await broker.StartAsync(container.Resolve <IAccountManager>(), port); container.RegisterInstance(broker); } }
private object[] ResolveConstructorParameters(ConstructorInfo ctor) { var result = new List <object>(); var parameters = ctor.GetParameters(); if (!parameters.Any()) { return(null); } try { foreach (var param in parameters) { if (param.DefaultValue != null && _container.IsBound(param.ParameterType) == false) { result.Add(param.DefaultValue); } else { result.Add(_container.Resolve(param.ParameterType)); } } } catch (Exception) { throw new ResolverException(Resources.Exception_UnresolvedCtorParams); } return(result.ToArray()); }
public DashboardViewModel(IDIContainer container, IAuthorizationManager authManager, INavigationService navigationService, ILocationHelper locationHelper, ILog log) { _authManager = authManager; _navigationService = navigationService; _locationHelper = locationHelper; _log = log; Client.Me().ContinueWith(t => { Me = t.Result.Response; }); Client.Vehicles().ContinueWith(t => { foreach (var v in t?.Result?.Response?.Data) { OnNext(v); } }); _vehicleObservable = Client.WatchVehicles(); _vehicleObservable.Subscribe(this); LogoutCommand = container.Resolve <IRelayCommand <object> >(); LogoutCommand.ExecuteAction = async b => { await authManager.Logout(); _navigationService.Navigate(this, "Logout", null); }; MapZoomLevel = 7; }
public ILocation FindCenter(IList <ILocation> locations) { if (locations.Count == 1) { return(locations.Single()); } double x = 0, y = 0, z = 0; foreach (var geoCoordinate in locations) { if (geoCoordinate != null) { var latitude = geoCoordinate.Lat * Math.PI / 180; var longitude = geoCoordinate.Lng * Math.PI / 180; x += Math.Cos(latitude) * Math.Cos(longitude); y += Math.Cos(latitude) * Math.Sin(longitude); z += Math.Sin(latitude); } } var total = locations.Count; x = x / total; y = y / total; z = z / total; var centralLongitude = Math.Atan2(y, x); var centralSquareRoot = Math.Sqrt(x * x + y * y); var centralLatitude = Math.Atan2(z, centralSquareRoot); var newLocation = _container.Resolve <ILocation>(); newLocation.Lat = centralLatitude * 180 / Math.PI; newLocation.Lng = centralLongitude * 180 / Math.PI; return(newLocation); }
private async Task LoadUsersAsync(ILog log, IDIContainer container, IConfiguration configuration) { var accountManager = container.Resolve <IAccountManager>(); var serializer = container.Resolve <IDeserialize>(); await LoadConfigForType <List <IUser> >(log, serializer, configuration, "Users", async users => { if (users != default(List <IUser>)) { foreach (var user in users) { await accountManager.RegisterUser(user); } } }); }
public async Task <IAuthorization> LoadAuthorization() { if (_cache != null) { if (await _cache.Exists(KnownCacheKeys.AuthenticationToken)) { var auth = await _cache.Get <IAuthorization>(KnownCacheKeys.AuthenticationToken); if (!string.IsNullOrEmpty(auth?.Item?.AccessToken)) { if (auth.Item.HasExpired) { await _cache.Delete(KnownCacheKeys.AuthenticationToken); return(null); } _container.RegisterInstance <IAuthorization>(auth.Item, "Session"); var client = _container.Resolve <IClient>(); client.Authorization = auth.Item; _container.RegisterInstance <IClient>(client, "Session"); auth.Item.Refreshed = false; _log.Debug("Authorization was loaded"); return(auth.Item); } } } return(null); }
public bool Navigate(object sender, string completedAction, object state) { rootFrame.BackStack.Clear(); IPage page = null; switch (completedAction) { case "LoginComplete": page = _container.Resolve <IPage>("Dashboard"); break; default: //Login, Logout page = _container.Resolve <IPage>("Login"); break; } return(rootFrame.Navigate(page.GetType(), state)); }
public Task ExecutePostRegistrationStep(IDIContainer container, CancellationToken cancellationToken = default(CancellationToken)) { var config = container.Resolve <IConfiguration>(); var server = container.Resolve <IServer>(); server.Location = container.Resolve <ILocation>(); server.Location.Lat.Point = config.GetValueOrDefault("Server:Location:Lat", 0.0); server.Location.Lon.Point = config.GetValueOrDefault("Server:Location:Lon", 0.0); if (server.Location.Lat.Point != 0 && server.Location.Lon.Point != 0) { var ss = container.Resolve <ISunriseSunset>(); server.Sunrise = ss.GetSunrise(server.Location.Lat.Point, server.Location.Lon.Point); server.Sunrset = ss.GetSunset(server.Location.Lat.Point, server.Location.Lon.Point); } if (container.IsRegistered <IScheduler>()) { var scheduler = container.Resolve <IScheduler>(); var updateJob = container.Resolve <IUpdateServerPropertiesJob>(); var cron = container.Resolve <ICronExpressions>(); scheduler.RecurringJobAddOrUpdate(() => updateJob.UpdateServerProperties(), cron.Daily(12), TimeZoneInfo.Local); } return(Task.CompletedTask); }
private async Task ExecutePostRegistrationStep(IDIContainer container) { var defaultInstance = container.Resolve <IPostRegistrationStep>("DefaultDeploymentRegistrationContainer"); if (defaultInstance != null) { await defaultInstance.ExecutePostRegistrationStep(container, CancellationToken.None); } }
private void SetupVersion() { var versionProvider = _container.Resolve <IVersionProvider>(); Version = versionProvider.GetVersion(); #if TRACE Trace.WriteLine(EntryPoint + ": " + Version); #endif }
public void Register(IDIContainer container) { if (!container.IsRegistered <IConfiguration>()) { container.Register <IConfiguration, Configuration>(); var config = container.Resolve <IConfiguration>(); config.Build(); container.RegisterInstance(config, typeof(IConfiguration)); } }
public ICache <TKey, TValue> CreateCache <TKey, TValue>(string name) { KnownCaches cacheName; if (Enum.TryParse(name, true, out cacheName)) { return(CreateCache <TKey, TValue>(cacheName)); } var cache = GetCache <TKey, TValue>(name); if (cache == null) { cache = _container.Resolve <ICache <TKey, TValue> >("DEFAULT"); _container.RegisterInstance(cache, typeof(ICache <TKey, TValue>), name); } return(cache); }
public void Report(string message, double progress) { if (Progress != null) { var p = _container.Resolve <ISDKProgress>(); p.Message = message; p.CorrelationId = Id; p.Progress = progress; p.Timing = stopWatch.ElapsedMilliseconds; Progress.Report(p); } }
public Task ExecutePostRegistrationStep(IDIContainer container, CancellationToken cancellationToken = default(CancellationToken)) { Dictionary <string, string> loggingContext; if (container.IsRegistered <Dictionary <string, string> >("LoggingContext")) { loggingContext = container.Resolve <Dictionary <string, string> >("LoggingContext"); } else { loggingContext = new Dictionary <string, string>(); container.RegisterInstance(loggingContext, "LoggingContext"); } loggingContext["Command Line"] = Environment.CommandLine; loggingContext["Current Directory"] = Environment.CurrentDirectory; loggingContext["User Domain Name"] = Environment.UserDomainName; loggingContext["User Name"] = Environment.UserName; loggingContext["OS Version"] = Environment.OSVersion.ToString(); loggingContext["Machine Name"] = Environment.MachineName; var host = Environment.GetEnvironmentVariable("Host"); loggingContext["Host"] = host; if (container.IsRegistered <IConfiguration>()) { var config = container.Resolve <IConfiguration>(); loggingContext["Host Environment"] = config.HostEnvironment; loggingContext["Entry Point"] = config.EntryPoint; loggingContext["Environment"] = config.Environment; loggingContext["Version"] = config.Version; loggingContext["App Data Directory"] = config.AppDataDirectory.ToString(); loggingContext["Debug Mode"] = config.DebugMode.ToString().ToLowerInvariant(); loggingContext["Root Directory"] = config.RootDirectory.ToString(); } return(Task.CompletedTask); }
private void RegisterUIComponents() { DiContainer = DIContainer.Current; var uiRegistration = new UIRegistrationContainer(); uiRegistration.Register(DiContainer); var sharedRegistration = new SharedRegistrationContainer(); sharedRegistration.Register(DiContainer); DiContainer.RegisterInstance(Window.Current.CoreWindow.Dispatcher); _log = DiContainer.Resolve <ILog>(); }
public Task ExecutePostRegistrationStep(IDIContainer container, CancellationToken cancellationToken = default(CancellationToken)) { var configuration = container.Resolve <IConfiguration>(); var knownCaches = configuration.GetValues <IKnownCacheSetup>("Cache:KnownCaches"); if (knownCaches != null) { IDictionary <KnownCaches, IKnownCacheSetup> configValues = new Dictionary <KnownCaches, IKnownCacheSetup>(); foreach (var k in knownCaches) { configValues.Add(k.CacheName, k); } var knownConfig = container.Resolve <IKnownCacheConfiguration>(); knownConfig.CacheSetups = configValues.ToImmutableDictionary(); container.RegisterInstance(knownConfig, typeof(IKnownCacheConfiguration)); } return(Task.CompletedTask); }
public async Task ExecutePostRegistrationStep(IDIContainer container, CancellationToken cancellationToken = default(CancellationToken)) { var metrics = new Dictionary <string, double>(); var timer = new InlineEventTimer("DefaultDeployment", "InjectRegistrationModule"); var postRegistrationSteps = container.ResolveAllInstances <IPostRegistrationStep>(); if (postRegistrationSteps != null) { var orderedSteps = new SortedDictionary <int, IPostRegistrationStep>(); var count = 1000; foreach (var s in from p in postRegistrationSteps where p.GetType() != GetType() select p) { var step = s.GetType().GetCustomAttribute(typeof(RegistrationStepOrderAttribute)); if (step == null) { orderedSteps.Add(count, s); } else { var order = (step as RegistrationStepOrderAttribute)?.Order; if (order.HasValue) { orderedSteps.Add(order.Value, s); } else { orderedSteps.Add(count, s); } } count++; } foreach (var step in orderedSteps) { if (step.Value != null) { timer.Reset(); await step.Value.ExecutePostRegistrationStep(container, cancellationToken); metrics.Add(step.Value.GetType().Name, timer.Elapsed.TotalMilliseconds); } } } container.Resolve <ILogFactory>()?.CreateLog("DefaultDeployment", "Start")?.Event("Startup Performance", null, metrics); }
public Task ExecutePostRegistrationStep(IDIContainer container, CancellationToken cancellationToken = default(CancellationToken)) { var config = container.Resolve <IConfiguration>(); var actorSystemName = config.GetValueOrDefault("Actor:System:Name", "NeonTetra"); var actorCore = new ActorSystemCore(container, actorSystemName); var resolver = new NeonTetraDIBridge(container, actorCore); actorCore.RootActorSystem.AddDependencyResolver(resolver); container.RegisterInstance(resolver, typeof(IDependencyResolver)); container.RegisterInstance(actorCore); container.RegisterInstance(actorCore.RootActorSystem); var _userManagerActorRef = actorCore.RootActorSystem.ActorOf(actorCore.RootActorSystem.DI().Props(typeof(IUserManagerActor)), "UserManagerActor"); container.RegisterInstance(_userManagerActorRef, "UserManagerActor"); return(Task.CompletedTask); }
public void Register(IDIContainer container) { container.Register <IAttachment, Attachment>(); container.Register <IBotClient, BotClient>(); container.Register <IChannelAccount, ChannelAccount>(); container.Register <ILocation, Location>(); container.Register <IMention, Mention>(); container.Register <IMessage, Message>(); container.Register <IMojioConversationData, MojioConversationData>(); container.Register <IEntity, Entity>(); container.Register <IIntent, Intent>(); var botAccount = container.Resolve <IChannelAccount>(); botAccount.Id = "kitt-mojio-1"; botAccount.Address = "1080 Howe Street, Vancouver, BC Canada"; botAccount.IsBot = true; botAccount.Name = "Kitt"; container.RegisterInstance(botAccount, "bot"); }
public override JsonContract ResolveContract(Type type) { if (type.GetTypeInfo().IsInterface) { if (_container.IsRegistered(type)) { var t = _container.Resolve(type); if (t != null) { var i = t.GetType(); return(base.ResolveContract(i)); } } else { _log.Error("JSON contract resolver failed to resolve type {0}.", type.FullName); } } return(base.ResolveContract(type)); }
public override JsonContract ResolveContract(Type type) { if (type.GetTypeInfo().IsInterface) { try { var t = _container.Resolve(type); if (t == null) { throw new NotImplementedException(type.FullName); } var i = t.GetType(); return(base.ResolveContract(i)); } catch (Exception) { //somethig went wrong, lets let the bsae resolver give it a try... } } return(base.ResolveContract(type)); }
private static void Main(string[] args) { //IBattery battery = new SamsungBattery(); //MobilePhone phone = new AsusPhone(battery); //phone.TryReplaceBattery(); //Console.WriteLine(" "); //phone = new IPhoneX(battery); //phone.TryReplaceBattery(); IBattery battery = _dIContainer.Resolve <ISamsungBattery>(); MobilePhone phone = new AsusPhone(battery); phone.TryReplaceBattery(); Console.WriteLine(" "); phone = new IPhoneX(battery); phone.TryReplaceBattery(); }
public async Task Set <T>(string key, T value) { try { if ((await Exists(key))) { _storage.DeleteFile(Path(key)); } } catch (Exception) { } await consistencyLock.WaitAsync(); try { var cacheItem = _container.Resolve <ICacheItem <T> >(); cacheItem.Item = value; cacheItem.StoredDateTime = DateTime.Now; var json = _serializer.SerializeToString(cacheItem); if (!string.IsNullOrEmpty(json)) { using (var isoStream = new IsolatedStorageFileStream(Path(key), FileMode.CreateNew, _storage)) { using (var writer = new StreamWriter(isoStream)) { await writer.WriteAsync(json); } } } } catch (Exception) { } consistencyLock.Release(); }
public DefaultNavigationService(IDIContainer container) { _container = container; rootFrame = container.Resolve <Frame>("RootFrame"); }
public async Task <IPlatformResponse <T> > Request <T>(ApiEndpoint endpoint, string relativePath, CancellationToken cancellationToken, IProgress <ISDKProgress> progress = null, HttpMethod method = null, string body = null, byte[] rawData = null, string contentType = "application/json", IDictionary <string, string> headers = null) { var monitor = _container.Resolve <IProgressMonitor>(); if (progress != null) { monitor.Progress = progress; monitor.Start(); } monitor.Report("Initializing Http Request", 0); var _method = HttpMethod.Get; if (method != null) { _method = method; } var platformResponse = new PlatformResponse <T> { Success = false }; if (headers != null && headers.Count > 0) { if (headers.ContainsKey("Authorization")) { var h = headers["Authorization"]; if (h.IndexOf(" ", StringComparison.Ordinal) > 0) { var type = h.Substring(0, h.IndexOf(" ", StringComparison.Ordinal)).Trim(); var token = h.Substring(h.IndexOf(" ", StringComparison.Ordinal)).Trim(); AuthorizationType = type; Authorization.MojioApiToken = token; headers.Remove("Authorization"); } } } HttpClient client; switch (endpoint) { case ApiEndpoint.Accounts: client = AccountsClient(contentType); break; case ApiEndpoint.Images: client = ImagesClient(contentType); break; case ApiEndpoint.Push: client = PushClient(contentType); break; default: client = ApiClient(contentType); break; } var request = new HttpRequestMessage(_method, relativePath); monitor.Report("Setting HttpContent Body", 0.1); if (!string.IsNullOrEmpty(body)) { Debug.WriteLine($"Request Content:{body}"); request.Content = new StringContent(body, Encoding.UTF8, contentType); } monitor.Report("Set HttpContent Body", 0.2); if (rawData != null) { monitor.Report("Creating MultiPart Form Content", 0.2); var requestContent = new MultipartFormDataContent(); //"Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)); var imageContent = new ByteArrayContent(rawData); var fileName = "image.png"; var type = "image/png"; if (headers != null && headers.Count > 0) { type = (from x in headers where x.Key == "Content-Type" select x.Value).FirstOrDefault(); fileName = (from x in headers where x.Key == "Filename" select x.Value).FirstOrDefault(); if (!string.IsNullOrEmpty(type)) { headers.Remove("Content-Type"); } if (!string.IsNullOrEmpty(fileName)) { headers.Remove("Filename"); } } imageContent.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse("form-data"); imageContent.Headers.ContentDisposition.Name = "\"file\""; imageContent.Headers.ContentDisposition.FileName = fileName; imageContent.Headers.ContentDisposition.Size = rawData.Length; imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse(type); requestContent.Add(imageContent); request.Content = requestContent; monitor.Report("Created MultiPart Form Content", 0.3); } monitor.Report("Adding Headers", 0.4); if (headers != null && headers.Count > 0) { foreach (var h in headers) { request.Headers.Add(h.Key, h.Value); } } request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate")); if (DisableSessionAffinity) { request.Headers.Add("Arr-Disable-Session-Affinity", "True"); } monitor.Report("Added Headers", 0.4); if (cancellationToken.IsCancellationRequested) { platformResponse.WasCancelled = true; monitor.Report("Operation Cancelled", 0.5); return(platformResponse); } monitor.Report("Sending Http Request", 0.6); var requestSw = new Stopwatch(); requestSw.Start(); Debug.WriteLine($"Pre-flight request URL: {request.RequestUri}"); using (var sendResult = await client.SendAsync(request, cancellationToken)) { platformResponse.RequestDurationMS = requestSw.ElapsedMilliseconds; monitor.Report("Received Response from Http Request", 0.7); requestSw.Stop(); platformResponse.Url = sendResult.RequestMessage.RequestUri.ToString(); Debug.WriteLine($"Post-flight request URL: {platformResponse.Url}"); platformResponse.Timestamp = DateTimeOffset.UtcNow; platformResponse.HttpStatusCode = sendResult.StatusCode; Debug.WriteLine($"Status Code: {platformResponse.HttpStatusCode}"); try { var cookie = (from h in sendResult.Headers where h.Key == "Set-Cookie" select h.Value.FirstOrDefault()).FirstOrDefault(); if (cookie != null) { platformResponse.ARRAffinityInstance = (from c in cookie.Split(';') where c.StartsWith("") select c.Split('=').LastOrDefault()).FirstOrDefault(); } } catch (Exception) { } if (sendResult.IsSuccessStatusCode) { monitor.Report("Received Successful StatusCode", 0.8); if (cancellationToken.IsCancellationRequested) { platformResponse.WasCancelled = true; monitor.Report("Operation Cancelled", 0.9); return(platformResponse); } monitor.Report("Reading data from Response", 0.9); var json = await sendResult.Content.ReadAsStringAsync(); monitor.Report("Deserializing data", 0.95); try { platformResponse.Response = _serializer.Deserialize <T>(json); if (platformResponse.Response != null) { platformResponse.Success = true; } } catch (Exception e) { _log.Error(e, "Invalid response from the server. Received:{0}, expected:{1}. Will continue.", json, typeof(T)); } if (typeof(T) == typeof(IAuthorization)) { monitor.Report("Setting internal auth token", 0.99); Authorization.MojioApiToken = (platformResponse.Response as IAuthorization).AccessToken; _container.RegisterInstance(Authorization, "Session"); } } else { monitor.Report("Received Unsuccessful StatusCode", 0.8); platformResponse.Success = false; platformResponse.ErrorCode = sendResult.StatusCode.ToString(); platformResponse.ErrorMessage = sendResult.ReasonPhrase; monitor.Report("Reading data from Response", 0.9); var content = await sendResult.Content.ReadAsStringAsync(); Debug.WriteLine(content); Debug.WriteLine(_serializer.SerializeToString(request)); if (!string.IsNullOrEmpty(content)) { try { monitor.Report("Deserializing data", 0.95); dynamic result = _serializer.Deserialize(content); if (result != null) { if (result.Message != null) { platformResponse.ErrorMessage = platformResponse.ErrorMessage + ", " + result.Message; } else { platformResponse.ErrorMessage = platformResponse.ErrorMessage + ", " + content; } } } catch (Exception) { } } } } monitor.Report("Finished", 1); monitor.Stop(); return(platformResponse); }
public ContractResolver(IDIContainer container) { _container = container; _log = _container.Resolve <ILogFactory>().CreateLog(GetType()); }
public Task ExecutePostRegistrationStep(IDIContainer container, CancellationToken cancellationToken = default(CancellationToken)) { container.Resolve <IResourceCompiler>().Compile(); return(Task.CompletedTask); }