private string GetDeviceId() { IDeviceService deviceService = ServiceFinder.Resolve <IDeviceService>(); string deviceId = deviceService.GetDeviceId(); return(deviceId); }
/// <summary> /// Check if a session token exists /// </summary> /// <returns></returns> public bool Exists() { var data = ServiceFinder.Resolve <IDataService>(); var saved = data.GetData(SessionTokenKey); return(null != saved); }
/// <summary> /// Initializes a new instance of the <see cref="T:AeroGear.Mobile.Auth.AuthService"/> class. /// </summary> /// <param name="mobileCore">Mobile core.</param> /// <param name="serviceConfig">Service configuration.</param> public AuthService(MobileCore mobileCore = null, ServiceConfiguration serviceConfig = null) : base(mobileCore, serviceConfig) { Core.Logger.Info("AuthService construct start"); Core.Logger.Info("AuthService construct storage"); CredentialManager = new CredentialManager(ServiceFinder.Resolve <IPlatformBridge>().GetUserPreferences("AeroGear.Mobile.Auth.Credentials")); Core.Logger.Info("AuthService construct credential manager"); }
/// <summary> /// Return the saved session token value /// </summary> /// <returns></returns> public string GetToken() { var data = ServiceFinder.Resolve <IDataService>(); var saved = data.GetData(SessionTokenKey); return(saved); }
/// <summary> /// Get default storage path. /// </summary> /// <param name="dataId"></param> /// <returns></returns> public static string GetDefaultDataDir(string dataId) { IIOService ioService = ServiceFinder.Resolve <IIOService> (); string dirName = "com_feedhenry_sync"; string dataDirPath = Path.Combine(ioService.GetDataPersistDir(), dataId, dirName); return(dataDirPath); }
/// <summary> /// Gnerate SHA1 hash. /// </summary> /// <param name="pObject"></param> /// <returns></returns> public static string GenerateSHA1Hash(object pObject) { JArray sorted = SortObj(pObject); string strVal = sorted.ToString(Formatting.None); IHashService hasher = ServiceFinder.Resolve <IHashService> (); return(hasher.GenerateSha1Hash(strVal)); }
public T WithDeviceCheck(params IDeviceCheckType[] checkTypes) { foreach (var checkType in NonNull(checkTypes, "checkTypes")) { IDeviceCheck check = ServiceFinder.Resolve <IDeviceCheckFactory>().create(checkType); CheckList.Add(check); } return((T)this); }
public InMemoryDataStoreTest() { FHClient.Init(); _ioService = ServiceFinder.Resolve <IIOService>(); var dataDir = _ioService.GetDataPersistDir(); var dataPersistDir = Path.Combine(dataDir, "syncTestDir"); _dataPersistFile = Path.Combine(dataPersistDir, ".test_data_file"); }
public AppMetrics() { ApplicationRuntimeInfo appInfo = ServiceFinder.Resolve <IPlatformBridge>().ApplicationRuntimeInfo; this.appId = appInfo.Identifier; this.appVersion = appInfo.Version; this.sdkVersion = typeof(MobileCore).GetTypeInfo().Assembly.GetName().Version.ToString(); this.framework = appInfo.Framework; }
private IDeviceCheckFactory GetSecurityCheckFactory() { IDeviceCheckFactory factory = ServiceFinder.Resolve <IDeviceCheckFactory>(); if (factory == null) { throw new Exception("Security check factory has not been registered"); } return(factory); }
/// <summary> /// Clear the local session and delete from remote too. /// </summary> /// <returns></returns> public async Task Clear() { var dataService = ServiceFinder.Resolve <IDataService>(); var saved = GetToken(); if (null != saved) { dataService.DeleteData(SessionTokenKey); await CallRemote(RevokePath, saved); } }
public void TestStringHash() { var text = "test"; var hasher = ServiceFinder.Resolve <IHashService>(); var nativeHashed = hasher.GenerateSha1Hash(text); Debug.WriteLine("native hashed value = {0}", nativeHashed); var expected = "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"; Debug.WriteLine("got hash value {0}", nativeHashed); Assert.IsTrue(expected.Equals(nativeHashed)); }
public async Task TestStringHash() { //given await FHClient.Init(); const string text = "test"; var hasher = ServiceFinder.Resolve <IHashService>(); //when var nativeHashed = hasher.GenerateSha1Hash(text); Assert.AreEqual("a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", nativeHashed); }
/// <summary> /// Return the singleton instance of the class /// </summary> /// <returns></returns> public static FHConfig GetInstance() { if (null != _instance) { return(_instance); } var deviceService = ServiceFinder.Resolve <IDeviceService>(); var props = deviceService.ReadAppProps(); var dest = deviceService.GetDeviceDestination(); var uuid = deviceService.GetDeviceId(); _instance = new FHConfig(props, dest, uuid); return(_instance); }
public void SetUp() { FHClient.Init(); _ioService = ServiceFinder.Resolve <IIOService>(); var dataDir = _ioService.GetDataPersistDir(); _dataPersistDir = Path.Combine(dataDir, "syncTestDir"); if (Directory.Exists(_dataPersistDir)) { Directory.Delete(_dataPersistDir); } _dataPersistFile = Path.Combine(_dataPersistDir, ".test_data_file"); Debug.WriteLine("Data persist path = {0}", _dataPersistFile); }
/// <summary> /// Save permentently the storage. /// </summary> public void Save() { IIOService ioService = ServiceFinder.Resolve <IIOService> (); ILogService logger = ServiceFinder.Resolve <ILogService> (); Monitor.Enter(this); try { ioService.WriteFile(this.PersistPath, FHSyncUtils.SerializeObject(memoryStore)); } catch (Exception ex) { logger.e("FHSyncClient.InMemoryDataStore", "Failed to save file " + this.PersistPath, ex); throw; } finally { Monitor.Exit(this); } }
public void SaveData(string dataId, string dataValue) { try { DoSave(dataId, dataValue); } catch (Exception ex) { var logger = ServiceFinder.Resolve <ILogService>(); if (null != logger) { logger.e(TAG, "Failed to save data", ex); } } }
/// <summary> /// Get or create the client ID that identifies a device as long as the user doesn't reinstall /// the app or delete the app storage. A random UUID is created and stored in the application /// shared preferences. /// </summary> /// <returns>Client ID.</returns> private static String GetClientId() { IUserPreferences preferences = ServiceFinder.Resolve <IPlatformBridge>().GetUserPreferences(STORAGE_NAME); String clientId = preferences.GetString(STORAGE_KEY, null); if (clientId == null) { clientId = System.Guid.NewGuid().ToString(); LOGGER.Info("Generated a new client ID: " + clientId); preferences.PutString(STORAGE_KEY, clientId); } return(clientId); }
public async Task TestReadPushConfig() { // given await FHClient.Init(); var deviceService = ServiceFinder.Resolve <IDeviceService>(); // when var config = deviceService.ReadPushConfig(); // then Assert.AreEqual("*****@*****.**", config.Alias); var cat = config.Categories; Assert.AreEqual(2, cat.Count); Assert.IsTrue(cat.Contains("one")); }
public string GetData(string dataId) { string data = null; try { data = DoRead(dataId); } catch (Exception ex) { var logger = ServiceFinder.Resolve <ILogService>(); if (null != logger) { logger.e(TAG, "Failed to read data", ex); } } return(data); }
/// <summary> /// Load in-memory storage from file. /// </summary> /// <typeparam name="X"></typeparam> /// <param name="fullFilePath"></param> /// <returns></returns> public static InMemoryDataStore <X> Load <X>(string fullFilePath) { InMemoryDataStore <X> dataStore = new InMemoryDataStore <X>(); dataStore.PersistPath = fullFilePath; IIOService ioService = ServiceFinder.Resolve <IIOService> (); ILogService logger = ServiceFinder.Resolve <ILogService> (); if (ioService.Exists(fullFilePath)) { try { string fileContent = ioService.ReadFile(fullFilePath); dataStore.memoryStore = (Dictionary <string, X>)FHSyncUtils.DeserializeObject(fileContent, typeof(Dictionary <string, X>)); } catch (Exception ex) { logger.e("FHSyncClient.InMemoryDataStore", "Failed to load file " + fullFilePath, ex); dataStore.memoryStore = new Dictionary <string, X> (); } } return(dataStore); }
public PushConfig ReadPushConfig() { var configName = FHConfig.GetInstance().IsLocalDevelopment ? Constants.LocalConfigFileName : Constants.ConfigFileName; var appProps = ReadAppProps(); var configLocation = Path.Combine(GetPackageDir(), configName); var json = ServiceFinder.Resolve <IIOService>().ReadFile(configLocation); var config = (JObject)JsonConvert.DeserializeObject(json); var configWindows = config["windows"]; var pushConfig = new PushConfig { Alias = (string)config["Alias"], Categories = config["Categories"]?.ToObject <List <string> >(), UnifiedPushUri = new Uri(appProps.host + "/api/v2/ag-push"), VariantId = (string)(configWindows != null ? configWindows["variantID"] : config["variantID"]), VariantSecret = (string)(configWindows != null ? configWindows["variantSecret"] : config["variantSecret"]) }; return(pushConfig); }
/// <summary> /// Check if the device is online /// </summary> /// <returns></returns> private static async Task <bool> IsOnlineAsync() { var networkServiceProvider = ServiceFinder.Resolve <INetworkService>(); return(await networkServiceProvider.IsOnlineAsync()); }
/// <summary> /// Send request to the remote uri /// </summary> /// <param name="uri">The remote uri</param> /// <param name="requestMethod">The http request method</param> /// <param name="headers">The http reqeust headers</param> /// <param name="requestData">The request data</param> /// <param name="timeout">Timeout in milliseconds</param> /// <returns>Server response</returns> public static async Task <FHResponse> SendAsync(Uri uri, string requestMethod, IDictionary <string, string> headers, object requestData, TimeSpan timeout) { var timer = new Stopwatch(); var logger = ServiceFinder.Resolve <ILogService>(); var online = await IsOnlineAsync(); FHResponse fhres; if (!online) { var exception = new FHException("offline", FHException.ErrorCode.NetworkError); fhres = new FHResponse(exception); return(fhres); } Contract.Assert(null != uri, "No request uri defined"); Contract.Assert(null != requestMethod, "No http request method defined"); var httpClient = FHHttpClientFactory.Get(); try { logger.d(LogTag, "Send request to " + uri, null); httpClient.DefaultRequestHeaders.Add("User-Agent", "FHSDK/DOTNET"); httpClient.MaxResponseContentBufferSize = BufferSize; httpClient.Timeout = timeout; var requestMessage = new HttpRequestMessage(new HttpMethod(requestMethod), BuildUri(uri, requestMethod, requestData)); if (null != headers) { foreach (var item in headers) { requestMessage.Headers.Add(item.Key, item.Value); } } if (requestMethod != null && ("POST".Equals(requestMethod.ToUpper()) || "PUT".Equals(requestMethod.ToUpper()))) { if (null != requestData) { var requestDataStr = JsonConvert.SerializeObject(requestData); requestMessage.Content = new StringContent(requestDataStr, Encoding.UTF8, "application/json"); } } timer.Start(); var responseMessage = await httpClient.SendAsync(requestMessage, CancellationToken.None); timer.Stop(); logger.d(LogTag, "Reqeust Time: " + timer.ElapsedMilliseconds + "ms", null); var responseStr = await responseMessage.Content.ReadAsStringAsync(); logger.d(LogTag, "Response string is " + responseStr, null); if (responseMessage.IsSuccessStatusCode) { fhres = new FHResponse(responseMessage.StatusCode, responseStr); } else { var ex = new FHException("ServerError", FHException.ErrorCode.ServerError); fhres = new FHResponse(responseMessage.StatusCode, responseStr, ex); } } catch (HttpRequestException he) { logger.e(LogTag, "HttpRequestException", he); var fhexception = new FHException("HttpError", FHException.ErrorCode.HttpError, he); fhres = new FHResponse(fhexception); } catch (Exception e) { logger.e(LogTag, "Exception", e); var fhexception = new FHException("UnknownError", FHException.ErrorCode.UnknownError, e); fhres = new FHResponse(fhexception); } httpClient.Dispose(); return(fhres); }
/// <summary> /// Read a config file for a given rgistration. Defaulted to fhconfig.json. /// In development mode, fhconfig.local.json overrides default config file. /// </summary> /// <returns>The push config</returns> internal static PushConfig ReadConfig() { return(ServiceFinder.Resolve <IDeviceService>().ReadPushConfig()); }
/// <summary> /// Default constructor. /// </summary> protected PushBase() { _logger = ServiceFinder.Resolve <ILogService>(); }
/// <summary> /// Set the log levels. /// VERBOSE=1 /// DEBUG=2 /// INFO=3 /// WARNING=4 /// ERROR=5 /// NONE=Int16.MaxValue /// </summary> /// <param name="level">One of the options above</param> public static void SetLogLevel(int level) { var logService = ServiceFinder.Resolve <ILogService>(); logService.SetLogLevel(level); }
private static IDataService GetDataService() { return(ServiceFinder.Resolve <IDataService>()); }
/// <summary> /// Constructor /// </summary> public FHAuthRequest(CloudProps cloudProps) { _cloudProps = cloudProps; _oauthClient = ServiceFinder.Resolve <IOAuthClientHandlerService>(); }
/// <summary> /// Save the session token /// </summary> /// <param name="sessionToken"></param> internal static void SaveSession(string sessionToken) { var data = ServiceFinder.Resolve <IDataService>(); data.SaveData(SessionTokenKey, sessionToken); }