public static async void ClearCookies(LoginOptions loginOptions)
        {
            var frame = Window.Current.Content as Frame;

            if (frame != null)
            {
                await frame.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    var loginUri = new Uri(ComputeAuthorizationUrl(loginOptions));
                    var myFilter = new HttpBaseProtocolFilter();
                    HttpCookieManager cookieManager = myFilter.CookieManager;
                    try
                    {
                        PlatformAdapter.SendToCustomLogger("OAuth.ClearCookies - attempting at clearing cookies", LoggingLevel.Verbose);
                        HttpCookieCollection cookies = cookieManager.GetCookies(loginUri);
                        foreach (HttpCookie cookie in cookies)
                        {
                            cookieManager.DeleteCookie(cookie);
                        }
                        PlatformAdapter.SendToCustomLogger("OAuth2.ClearCookies - done", LoggingLevel.Verbose);
                    }
                    catch (ArgumentException ex)
                    {
                        PlatformAdapter.SendToCustomLogger("OAuth2.ClearCookies - Exception occurred when clearing cookies:", LoggingLevel.Critical);
                        PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Critical);
                        Debug.WriteLine("Error clearing cookies");
                    }
                });
            }
        }
        /// <summary>
        ///     Async method for refreshing the token, persisting the data in the encrypted settings and returning the updated
        ///     account
        ///     with the new access token.
        /// </summary>
        /// <param name="account"></param>
        /// <returns>Boolean based on if the refresh auth token succeeded or not</returns>
        public static async Task <Account> RefreshAuthToken(Account account)
        {
            if (account != null)
            {
                try
                {
                    AuthResponse response =
                        await RefreshAuthTokenRequest(account.GetLoginOptions(), account.RefreshToken);

                    account.AccessToken = response.AccessToken;
                    AuthStorageHelper.GetAuthStorageHelper().PersistCredentials(account);
                }
                catch (WebException ex)
                {
                    PlatformAdapter.SendToCustomLogger(
                        "OAuth2.RefreshAuthToken - Exception occurred when refreshing token:", LoggingLevel.Critical);
                    PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Critical);
                    Debug.WriteLine("Error refreshing token");
                    throw new OAuthException(ex.Message, ex.Status);
                }
                catch (Exception ex)
                {
                    PlatformAdapter.SendToCustomLogger(
                        "OAuth2.RefreshAuthToken - Exception occurred when refreshing token:", LoggingLevel.Critical);
                    PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Critical);
                    Debug.WriteLine("Error refreshing token");
                    throw new OAuthException(ex.Message, ex.InnerException);
                }
            }
            return(account);
        }
Exemple #3
0
        /// <summary>
        ///     Called when bringing up page and user is authenticated but web view has not been loaded yet
        /// </summary>
        protected void OnResumeLoggedInNotLoaded()
        {
            PlatformAdapter.SendToCustomLogger("HybridMainPage.OnResumeLoggedInNotLoaded called", LoggingLevel.Verbose);

            // Local
            if (_bootConfig.IsLocal)
            {
                Log("Success:Loading local application");
                LoadLocalStartPage();
            }
            // Remote
            else
            {
                // Online
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    Log("Success:Loading remote application");
                    LoadRemoteStartPage();
                }
                // Offline
                else
                {
                    // Has cached version
                    if (false /* FIXME */)
                    {
                        Log("Success:Loading cached version of remote application because offline");
                    }
                    // No cached version
                    Log("Error:Can't load remote application offline without cached version");
                    LoadErrorPage();
                }
            }
        }
Exemple #4
0
        public static void RefreshCookies()
        {
            PlatformAdapter.SendToCustomLogger("OAuth.RefreshCookies - attempting at refreshing cookies", LoggingLevel.Verbose);
            Account account = AccountManager.GetAccount();

            if (account != null)
            {
                var loginUri    = new Uri(account.LoginUrl);
                var instanceUri = new Uri(account.InstanceUrl);
                var filter      = new HttpBaseProtocolFilter();

                var cookie = new HttpCookie("salesforce", loginUri.Host, "/");
                cookie.Secure = true;
                cookie.Value  = account.AccessToken;
                filter.CookieManager.SetCookie(cookie, false);

                var instance = new HttpCookie("salesforceInstance", instanceUri.Host, "/");
                instance.Secure = true;
                instance.Value  = account.AccessToken;
                filter.CookieManager.SetCookie(instance, false);

                var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, instanceUri);
                var web = new WebView();
                web.NavigateWithHttpRequestMessage(httpRequestMessage);
            }
            PlatformAdapter.SendToCustomLogger("OAuth.RefreshCookies - done", LoggingLevel.Verbose);
        }
Exemple #5
0
        public App()
        {
            // SfdcSDK
            InitializeSfdcConfig();

            SDKManager.CreateClientManager(false);
            SDKManager.RootApplicationPage = typeof(VisualBrowserPage);
            SDKManager.EndLoginCallBack    = () => { Messenger.Default.Send(new UserLogInMessage()); };

            PlatformAdapter.Resolve <ISFApplicationHelper>().Initialize();

            // Set up the Logging Service and the custom log action function in the PlatformAdapter
            var target = new LogFileTarget();

            target.RetainDays = 10;
            LoggingServices.DefaultConfiguration.AddTarget(LoggingLevel.Information, target);
            PlatformAdapter.SetCustomLoggerAction(LoggingServices.LogAction);

            // Continue App setup
            InitializeComponent();
            Suspending += OnSuspending;
            Resuming   += OnResuming;

            // Setup the global crash handler
            GlobalCrashHandler.Configure();
        }
Exemple #6
0
        /// <summary>
        /// Initialize Visual Browser
        /// Load all necessary data
        /// </summary>
        protected override async Task Initialize()
        {
            try
            {
                _currentMobileConfiguration = await _mobileConfigurationDataService.GetCurrentMobileConfiguration();

                Buttons             = VisualBrowserViewModelBuilder.CreateButtonsViewModel(_currentMobileConfiguration, ShowCategory).ToList();
                TopCategories       = VisualBrowserViewModelBuilder.CreateCategoriesViewModel(_currentMobileConfiguration.TopCategories, _navigateToMediaCommand, IsInternalModeEnable, SubCategorySelectionAction);
                ControlBarViewModel = new ControlBarViewModel(_dialogService, SettingsDataService, _mobileAppConfigDataService, _currentMobileConfiguration, _userSessionService, _contactsService, _presentationDataService, _syncLogService);
                ExpandedCategories  = new ObservableCollection <CategoryViewModel>();
                SearchViewModel     = new SearchControlViewModel(_documentInfoDataService, _searchContentDataService, _navigationService, _navigateToMediaCommand);

                if (_orientation.HasValue)
                {
                    RefreshButtons(_orientation.Value);
                    GetAllCategoryContent().ForEach(c => c.HandleOrientation(_orientation.Value));
                }

                await LoadBackgroundImage();

                if (_orientation.HasValue)
                {
                    BackgroundImage = ResolveBackgroundImage(_orientation.Value);
                }
            }
            catch (Exception e)
            {
                PlatformAdapter.SendToCustomLogger(e, LoggingLevel.Error);
                // Report error here
            }
        }
Exemple #7
0
        public AutomapperRegistry()
        {
            var platformSpecificRegistry = PlatformAdapter.Resolve <IPlatformSpecificMapperRegistry>();

            platformSpecificRegistry.Initialize();

            For <ConfigurationStore>().Singleton().Use <ConfigurationStore>()
            .Ctor <IEnumerable <IObjectMapper> >().Is(MapperRegistry.Mappers);

            For <IConfigurationProvider>().Use(ctx => ctx.GetInstance <ConfigurationStore>());

            For <IConfiguration>().Use(ctx => ctx.GetInstance <ConfigurationStore>());

            For <ITypeMapFactory>().Use <TypeMapFactory>();

            For <IMappingEngine>().Singleton().Use <MappingEngine>()
            .SelectConstructor(() => new MappingEngine(null));

            this.Scan(scanner =>
            {
                scanner.AssemblyContainingType <PostProfile>();
                scanner.AddAllTypesOf <Profile>().NameBy(item => item.Name);

                //scanner.AssemblyContainingType<CommentProfile>();
                //scanner.AddAllTypesOf<Profile>().NameBy(item => item.Name);
                //scanner.AssembliesFromApplicationBaseDirectory();

                scanner.ConnectImplementationsToTypesClosing(typeof(ITypeConverter <,>))
                .OnAddedPluginTypes(t => t.HybridHttpOrThreadLocalScoped());

                //scanner.ConnectImplementationsToTypesClosing(typeof(ValueResolver<,>))
                //    .OnAddedPluginTypes(t => t.HybridHttpOrThreadLocalScoped());
            });
        }
        public async Task PushToStreamAsync(
            Func <IOutputStream, IAsyncOperationWithProgress <ulong, ulong> > writeToStreamAsync,
            IHttpContent content)
        {
            if (content == null)
            {
                throw new NullReferenceException("Parameter content is null");
            }
            if (writeToStreamAsync == null)
            {
                throw new NullReferenceException("Parameter writeToStreamAsync is null");
            }

            var attFolderMgr = AttachmentsFolder.Instance;

            var attFolder = await attFolderMgr.CreateOrGetFolderForAttachmentId(_meta.Id, _syncId);

            try
            {
                StorageFile newFile = await attFolder.CreateFileAsync(_meta.Name, CreationCollisionOption.ReplaceExisting);

                using (var sfw = await newFile.OpenStreamForWriteAsync())
                {
                    using (var outStream = sfw.AsOutputStream())
                    {
                        ulong x = await content.WriteToStreamAsync(outStream);
                    }
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Error);
                Debug.WriteLine($"Exception Opening Attachment File For Write { _meta.Name } ");
            }
        }
Exemple #9
0
        private void RefreshSession(SalesforceOAuthPlugin plugin)
        {
            PlatformAdapter.SendToCustomLogger("HybridMainPage.RefreshSession - Making a REST call to refresh session", LoggingLevel.Verbose);

            // Cheap REST call to refresh session
            _client.SendAsync(RestRequest.GetRequestForResources(ApiVersion), response =>
            {
                if (plugin != null)
                {
                    if (!response.Success)
                    {
                        PlatformAdapter.SendToCustomLogger(
                            string.Format("HybridMainPage.RefreshSession - Error = {0}", response.Error.ToString()), LoggingLevel.Verbose);

                        plugin.OnAuthenticateError(response.Error.Message);
                    }
                    else
                    {
                        PlatformAdapter.SendToCustomLogger("HybridMainPage.RefreshSession - refresh successful", LoggingLevel.Verbose);

                        plugin.OnAuthenticateSuccess(GetJSONCredentials());
                    }
                }
            });
        }
        private IEnumerable <PasswordCredential> SafeRetrieveResource(string resource)
        {
            try
            {
                PlatformAdapter.SendToCustomLogger(
                    string.Format(
                        "AuthStorageHelper.SafeRetrieveResource - Attempting to retrieve resource {0}",
                        resource), LoggingLevel.Verbose);

                var list = _vault.RetrieveAll();
                return(from item in list where resource.Equals(item.Resource) select item);
            }
            catch (Exception ex)
            {
                PlatformAdapter.SendToCustomLogger(
                    string.Format(
                        "AuthStorageHelper.SafeRetrieveResource - Exception occured when retrieving vault data for resource {0}",
                        resource), LoggingLevel.Critical);

                PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Critical);

                Debug.WriteLine("Failed to retrieve vault data for resource " + resource);
            }
            return(new List <PasswordCredential>());
        }
Exemple #11
0
        public static async Task <bool> SwitchToAccount(Account account)
        {
            if (account != null && account.UserId != null)
            {
                AuthStorageHelper.GetAuthStorageHelper().PersistCredentials(account);
                RestClient client = SDKManager.GlobalClientManager.PeekRestClient();
                if (client != null)
                {
                    OAuth2.ClearCookies(account.GetLoginOptions());
                    IdentityResponse identity = await OAuth2.CallIdentityService(account.IdentityUrl, client);

                    if (identity != null)
                    {
                        account.UserId   = identity.UserId;
                        account.UserName = identity.UserName;
                        account.Policy   = identity.MobilePolicy;
                        AuthStorageHelper.GetAuthStorageHelper().PersistCredentials(account);
                    }
                    OAuth2.RefreshCookies();
                    PlatformAdapter.SendToCustomLogger("AccountManager.SwitchToAccount - done, result = true", LoggingLevel.Verbose);
                    return(true);
                }
            }
            PlatformAdapter.SendToCustomLogger("AccountManager.SwitchToAccount - done, result = false", LoggingLevel.Verbose);
            return(false);
        }
        protected override async Task Initialize()
        {
            try
            {
                EditButtonDisabled = false;
                var navigationCommand = new NavigateToMediaCommand(_navigationService, _historyDataService);
                SearchViewModel = new SearchControlViewModel(_documentInfoDataService, _searchContentDataService, _navigationService, navigationCommand);

                var data = await _playlistsDataService.GetPlayListsData();

                _allPlaylists = PlaylistViewModelBuilder.Create(data, navigationCommand, _dialogService);
                PopulateRemoveCommand(_allPlaylists);
                SetInternalMode(_allPlaylists, IsInternalModeEnable);
                PlayLists      = _allPlaylists;
                EditButtonText = ReadOnlyModeStateText;
                var personalLibrarydata = await _playlistsDataService.GetPersonalLibrarData();

                PersonalLibraryViewModel = PlaylistViewModelBuilder.Create(personalLibrarydata, navigationCommand, _dialogService);
                PersonalLibraryViewModel.IsInternalMode = IsInternalModeEnable;
                NewPlaylistViewModel = new NewPlaylistViewModel(this.PlayLists, new NavigateToMediaCommand(_navigationService, _historyDataService), _dialogService, (vm) => _allPlaylists.Remove(vm));
                EditButtonDisabled   = true;
            }
            catch (Exception ex)
            {
                PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Error);
            }
        }
        public async void OnActivated(IActivatedEventArgs args)
        {
            CreateRootFrame();
            await RestoreStatus(args.PreviousExecutionState);

            if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                ContinuationManager.MarkAsStale();
            }

            PincodeManager.TriggerBackgroundedPinTimer();
            if (args is IContinuationActivatedEventArgs)
            {
                var continueEvents = args as IContinuationActivatedEventArgs;
                ContinuationManager.MarkAsStale();
                try
                {
                    PlatformAdapter.SendToCustomLogger("SFApplicationHelper.OnActivated - Calling ContinuationManager.Continue", LoggingLevel.Verbose);
                    ContinuationManager.Continue(continueEvents);
                }
                catch (InvalidOperationException e)
                {
                    PlatformAdapter.SendToCustomLogger("SFApplicationHelper.OnActivated - Exception when calling ContinuationManager.Continue", LoggingLevel.Critical);
                    PlatformAdapter.SendToCustomLogger(e, LoggingLevel.Critical);
                    Debug.WriteLine("Exception while continuing, " + e.StackTrace);
                }
            }
            Window.Current.Activate();
        }
            private async Task <IInputStream> GetContent(string path)
            {
                if (path.ElementAt(0) == '/')
                {
                    path = path.Remove(0, 1);
                }

                Stream zipStream = await _file.OpenStreamForReadAsync();

                ZipArchive      archive     = new ZipArchive(zipStream, ZipArchiveMode.Read);
                ZipArchiveEntry contentFile = archive.GetEntry(path);

                if (contentFile == null)
                {
                    throw new Exception("Invalid archive entry");
                }

                try
                {
                    var          zipASize = contentFile.Length;
                    IInputStream stream   = await GetInputStreamFromIOStream(contentFile.Open(), zipASize);

                    return(stream);
                }
                catch (Exception ex)
                {
                    PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Error);
                    return(null);
                }
            }
        public static IStoreManager GetStoreManager(StoreConfiguration storeConfiguration = null)
        {
            if (storeConfiguration == null)
            {
                storeConfiguration = StoreConfiguration.DefaultStoreConfiguration;
            }
            if (storeConfiguration.StoreManagerType != null)
            {
                return
                    (Activator.CreateInstance(storeConfiguration.StoreManagerType, storeConfiguration) as IStoreManager);
            }
#if BTREESTORE
#if SILVERLIGHT
            return(new IsolatedStorageStoreManager(storeConfiguration));
#else
            return(storeConfiguration.UseIsolatedStorage ? (IStoreManager) new IsolatedStorageStoreManager(storeConfiguration) : new FileStoreManager(storeConfiguration));
#endif
#else
#if WINDOWS_PHONE
            return(new BPlusTreeStore.BPlusTreeStoreManager(storeConfiguration, new IsolatedStoragePersistanceManager()));
#elif PORTABLE
            storeConfiguration.DisableBackgroundWrites = true;
            return(new BPlusTreeStoreManager(storeConfiguration, PlatformAdapter.Resolve <IPersistenceManager>()));
#else
            return(storeConfiguration.UseIsolatedStorage ? new BPlusTreeStore.BPlusTreeStoreManager(storeConfiguration, new IsolatedStoragePersistanceManager()) : new BPlusTreeStore.BPlusTreeStoreManager(storeConfiguration, new FilePersistenceManager()));
#endif
#endif
        }
        internal Account RetrieveCurrentAccount()
        {
            PasswordCredential creds = SafeRetrieveResource(PasswordVaultCurrentAccount).FirstOrDefault();

            if (creds != null)
            {
                PasswordCredential account = _vault.Retrieve(creds.Resource, creds.UserName);
                if (String.IsNullOrWhiteSpace(account.Password))
                {
                    _vault.Remove(account);
                }
                else
                {
                    try
                    {
                        PlatformAdapter.SendToCustomLogger(
                            "AuthStorageHelper.RetrieveCurrentAccount - getting current account", LoggingLevel.Verbose);
                        return(JsonConvert.DeserializeObject <Account>(Encryptor.Decrypt(account.Password)));
                    }
                    catch (Exception ex)
                    {
                        PlatformAdapter.SendToCustomLogger(
                            "AuthStorageHelper.RetrieveCurrentAccount - Exception occured when decrypting account, removing account from vault",
                            LoggingLevel.Warning);

                        PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Warning);

                        // if we can't decrypt remove the account
                        _vault.Remove(account);
                    }
                }
            }
            return(null);
        }
        private PasswordCredential SafeRetrieveUser(string resource, string userName)
        {
            try
            {
                var list = SafeRetrieveResource(resource);

                PlatformAdapter.SendToCustomLogger(
                    string.Format(
                        "AuthStorageHelper.SafeRetrieveUser - Attempting to retrieve user Resource={0}  UserName={1}",
                        resource, userName), LoggingLevel.Verbose);

                var passwordCredentials = list as IList <PasswordCredential> ?? list.ToList();
                if (passwordCredentials.Any())
                {
                    return(passwordCredentials.FirstOrDefault(n => userName.Equals(n.UserName)));
                }
            }
            catch (Exception ex)
            {
                PlatformAdapter.SendToCustomLogger(
                    string.Format(
                        "AuthStorageHelper.SafeRetrieveUser - Exception occured when retrieving vault data for resource {0}",
                        resource), LoggingLevel.Critical);

                PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Critical);

                Debug.WriteLine("Failed to retrieve vault data for resource " + resource);
            }
            return(null);
        }
        /// <summary>
        ///     Persist account, and sets account as the current account.
        /// </summary>
        /// <param name="account"></param>
        internal void PersistCredentials(Account account)
        {
            PasswordCredential creds = SafeRetrieveUser(PasswordVaultAccounts, account.UserName);

            if (creds != null)
            {
                PlatformAdapter.SendToCustomLogger("AuthStorageHelper.PersistCredentials - removing existing credential", LoggingLevel.Verbose);
                _vault.Remove(creds);
                IReadOnlyList <PasswordCredential> current = _vault.FindAllByResource(PasswordVaultCurrentAccount);
                if (current != null)
                {
                    foreach (PasswordCredential user in current)
                    {
                        _vault.Remove(user);
                    }
                }
            }
            string serialized = Encryptor.Encrypt(JsonConvert.SerializeObject(account));

            _vault.Add(new PasswordCredential(PasswordVaultAccounts, account.UserName, serialized));
            _vault.Add(new PasswordCredential(PasswordVaultCurrentAccount, account.UserName, serialized));
            var options = new LoginOptions(account.LoginUrl, account.ClientId, account.CallbackUrl,
                                           LoginOptions.DefaultDisplayType, account.Scopes);

            SalesforceConfig.LoginOptions = options;
            PlatformAdapter.SendToCustomLogger("AuthStorageHelper.PersistCredentials - done adding info to vault", LoggingLevel.Verbose);
        }
Exemple #19
0
        private static async Task SavePDFThumbnail(StorageFile file, StorageFolder folder)
        {
            PdfDocument pdfDocument;

            try
            {
                pdfDocument = await PdfDocument.LoadFromFileAsync(file);
            }
            catch (Exception e)
            {
                PlatformAdapter.SendToCustomLogger(e, LoggingLevel.Error);
                return;
            }
            if (pdfDocument == null)
            {
                return;
            }

            var currentPage     = pdfDocument.GetPage(0);
            var destinationFile = await folder.CreateFileAsync(ThumbnailName, CreationCollisionOption.GenerateUniqueName);

            using (var strm = await destinationFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                await currentPage.RenderToStreamAsync(strm, new PdfPageRenderOptions()
                {
                    DestinationHeight = 300, DestinationWidth = 263
                });
            }
        }
            private async Task <IInputStream> GetInputStreamFromIOStream(Stream stream, long fileSize)
            {
                try
                {
                    using (BinaryReader binReader = new BinaryReader(stream))
                    {
                        byte[] byteArr = binReader.ReadBytes((int)fileSize);

                        using (var iMS = new InMemoryRandomAccessStream())
                        {
                            var imsOutputStream = iMS.GetOutputStreamAt(0);
                            using (DataWriter dataWriter = new DataWriter(imsOutputStream))
                            {
                                dataWriter.WriteBytes(byteArr);

                                await dataWriter.StoreAsync();

                                await imsOutputStream.FlushAsync();

                                return(iMS.GetInputStreamAt(0));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Error);
                    return(null);
                }
            }
        /// <summary>
        ///     This will return true if there is a master pincode set.
        /// </summary>
        /// <returns></returns>
        public static bool IsPincodeSet()
        {
            bool result = AuthStorageHelper.GetAuthStorageHelper().RetrievePincode() != null;

            PlatformAdapter.SendToCustomLogger(string.Format("AuthStorageHelper.IsPincodeSet - result = {0}", result), LoggingLevel.Verbose);

            return(result);
        }
 /// <summary>
 ///     Configures the dialog to act as a confirmation for the entered pincode.
 /// </summary>
 private void SetupConfirm()
 {
     PlatformAdapter.SendToCustomLogger("PincodeDialog.SetupCreate - Configuring the dialog to act as a confirmation for the entered pincode", LoggingLevel.Information);
     Title.Text               = LocalizedStrings.GetString("passcode_reenter");
     Description.Text         = LocalizedStrings.GetString("passcode_confirm");
     ContentFooter.Visibility = Visibility.Collapsed;
     Passcode.KeyDown        += ConfirmClicked;
 }
Exemple #23
0
 public ControllerHelperI(string name, string[] args, MainPage page, PlatformAdapter platformAdapter)
 {
     _name            = name;
     _args            = args;
     _page            = page;
     _platformAdapter = platformAdapter;
     _typename        = name;
 }
        /// <summary>
        ///     This will wipe out the pincode and associated data.
        /// </summary>
        public static void WipePincode()
        {
            AuthStorageHelper auth = AuthStorageHelper.GetAuthStorageHelper();

            auth.DeletePincode();
            auth.DeleteData(PinBackgroundedTimeKey);
            auth.DeleteData(PincodeRequired);
            PlatformAdapter.SendToCustomLogger("PincodeManager.WipePincode - Pincode wiped", LoggingLevel.Verbose);
        }
Exemple #25
0
        private static void RunExport(object jobData)
        {
            var exportJob = jobData as ExportJob;

            if (exportJob == null)
            {
                return;
            }
            try
            {
                var storeDirectory  = exportJob._storeWorker.WriteStore.DirectoryPath;
                var exportDirectory = Path.Combine(Path.GetDirectoryName(storeDirectory), "import");
#if PORTABLE
                var persistenceManager = PlatformAdapter.Resolve <IPersistenceManager>();
                if (!persistenceManager.DirectoryExists(exportDirectory))
                {
                    persistenceManager.CreateDirectory(exportDirectory);
                }
                var filePath = Path.Combine(exportDirectory, exportJob._outputFileName);
                using (var stream = persistenceManager.GetOutputStream(filePath, FileMode.Create))
#else
                if (!Directory.Exists(exportDirectory))
                {
                    Directory.CreateDirectory(exportDirectory);
                }
                var filePath = Path.Combine(exportDirectory, exportJob._outputFileName);
                Logging.LogDebug("Export file path calculated as '{0}'", filePath);
                using (var stream = File.Open(filePath, FileMode.Create, FileAccess.Write))
#endif
                {
                    string[] graphs = String.IsNullOrEmpty(exportJob._graphUri)
                                          ? null
                                          : new[] { exportJob._graphUri };
                    var triples = exportJob._storeWorker.ReadStore.Match(null, null, null, graphs: graphs);
                    var sw      = new StreamWriter(stream);
                    var sink    = GetWriterSink(exportJob._exportFormat, sw);
                    var nw      = new BrightstarTripleSinkAdapter(sink);
                    foreach (var triple in triples)
                    {
                        nw.Triple(triple);
                    }
                    sink.Close();
                    sw.Flush();

#if !PORTABLE
                    stream.Flush(true);
                    stream.Close();
#endif
                }
                exportJob._successCallback(exportJob._jobId);
            }
            catch (Exception ex)
            {
                Logging.LogError(BrightstarEventId.ExportDataError, "Error Exporting Data {0} {1}", ex.Message, ex.StackTrace);
                exportJob._errorCallback(exportJob._jobId, ex);
            }
        }
        /// <summary>
        ///     Returns a RestClient if user is already authenticated or otherwise kicks off a login flow
        /// </summary>
        /// <returns></returns>
        public RestClient GetRestClient()
        {
            RestClient restClient = PeekRestClient();

            if (restClient == null)
            {
                PlatformAdapter.Resolve <IAuthHelper>().StartLoginFlow();
            }
            return(restClient);
        }
        private static string GenerateEncryptedPincode(string pincode)
        {
            HashAlgorithmProvider alg = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);
            IBuffer buff   = CryptographicBuffer.ConvertStringToBinary(pincode, BinaryStringEncoding.Utf8);
            IBuffer hashed = alg.HashData(buff);
            string  res    = CryptographicBuffer.EncodeToHexString(hashed);

            PlatformAdapter.SendToCustomLogger("AuthStorageHelper.GenerateEncryptedPincode - Pincode generated, now encrypting and returning it", LoggingLevel.Verbose);
            return(Encryptor.Encrypt(res));
        }
        public void PersistPincode(MobilePolicy policy)
        {
            DeletePincode();
            var newPin = new PasswordCredential(PasswordVaultSecuredData, PasswordVaultPincode,
                                                JsonConvert.SerializeObject(policy));

            _vault.Add(newPin);
            PlatformAdapter.SendToCustomLogger("AuthStorageHelper.PersistPincode - pincode added to vault",
                                               LoggingLevel.Verbose);
        }
Exemple #29
0
        public static IGraph LoadConfiguration(string configurationPath)
        {
            var pm = PlatformAdapter.Resolve <IPersistenceManager>();

            ConfigurationLoader.PathResolver = new DotNetRdfConfigurationPathResolver(configurationPath);
            using (var stream = pm.GetInputStream(configurationPath))
            {
                return(ConfigurationLoader.LoadConfiguration(configurationPath, new Uri(configurationPath), stream));
            }
        }
 /// <summary>
 ///     Configures the dialog for creating a pincode.
 /// </summary>
 private void SetupCreate()
 {
     PlatformAdapter.SendToCustomLogger("PincodeDialog.SetupCreate - Configuring the dialog for creating a pincode", LoggingLevel.Information);
     Title.Text               = LocalizedStrings.GetString("passcode_create_title");
     Description.Text         = LocalizedStrings.GetString("passcode_create_security");
     ContentFooter.Visibility = Visibility.Visible;
     ContentFooter.Text       = String.Format(LocalizedStrings.GetString("passcode_length"),
                                              Options.User.Policy.PinLength);
     Passcode.KeyDown += CreateClicked;
 }