protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); SetContentView (Resource.Layout.Main); acctStore = AccountStore.Create (this); InitViews (); InitEventHandlers (); includeLinkCheckBox.Checked = true; }
public ArtportalenAccountStorage(ICurrentUser currentUser) { _currentUser = currentUser; #if __ANDROID__ _accountStore = AccountStore.Create(Forms.Context); #endif #if __IOS__ _accountStore = AccountStore.Create(); #endif _account = _accountStore.FindAccountsForService(ServiceId).FirstOrDefault(a => a.Username == _currentUser.Id); }
void LoginToFacebook(bool allowCancel) { var loginPage = Element as FBLoginPage; string providername = loginPage.ProviderName; var activity = this.Context as Activity; OAuth2Authenticator auth = null; switch (providername) { case "Google": { auth = new OAuth2Authenticator( // For Google login, for configure refer https://code.msdn.microsoft.com/Register-Identity-Provider-41955544 App.ClientId, App.ClientSecret, // Below values do not need changing "https://www.googleapis.com/auth/userinfo.email", new Uri(App.url2), new Uri(App.url3), // Set this property to the location the user will be redirected too after successfully authenticating new Uri(App.url4) //,isUsingNativeUI: true ); break; } case "FaceBook": { auth = new OAuth2Authenticator( clientId: App.AppId, scope: App.ExtendedPermissions, authorizeUrl: new Uri(App.AuthorizeUrl), redirectUrl: new Uri(App.RedirectUrl)); break; } } auth.AllowCancel = allowCancel; // If authorization succeeds or is canceled, .Completed will be fired. auth.Completed += async(s, eargs) => { if (!eargs.IsAuthenticated) { return; } else { //var token = eargs.Account.Properties["access_token"]; if (providername.Equals("FaceBook")) { // Now that we're logged in, make a OAuth2 request to get the user's info. var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?fields=id,name,picture,email"), null, eargs.Account); var result = await request.GetResponseAsync(); string resultText = result.GetResponseText(); var obj = JsonValue.Parse(resultText); // Console.WriteLine(token + " -=- " + resultText); App.FacebookId = obj["id"]; App.FacebookName = obj["name"]; App.EmailAddress = obj["email"]; App.ProfilePic = obj["picture"]["data"]["url"]; // saveset(obj["id"], obj["name"]); } else { string url1 = "https://www.googleapis.com/oauth2/v2/userinfo"; string url2 = "https://www.googleapis.com/plus/v1/people/me/openIdConnect"; var request = new OAuth2Request("GET", new Uri(url1), null, eargs.Account); var result = await request.GetResponseAsync(); string resultText = result.GetResponseText(); var obj = JsonValue.Parse(resultText); /*string username = (string)obj["name"]; * string email = (string)obj["email"];*/ App.FacebookId = obj["sub"]; App.FacebookName = obj["name"]; App.EmailAddress = obj["email"]; App.ProfilePic = obj["picture"]; // saveset(obj["id"], obj["name"]); } // On Android: store the account AccountStore.Create(Context).Save(eargs.Account, "Facebook"); //Save as a new user to the database await App.UserManager.SaveTaskAsync (new Models.User { FBID = App.FacebookId, UserName = App.FacebookName, Email = App.EmailAddress, ImgLink = App.ProfilePic }, true); //retreive gcm id var prefs = Android.App.Application.Context.GetSharedPreferences("MyApp", FileCreationMode.Private); string id = prefs.GetString("regId", null); RegisterAsync(id, new string[] { App.FacebookId + "T" }, App.FacebookId); await App.Current.MainPage.Navigation.PopModalAsync(); App.IsLoggedIn = true; ((App)App.Current).SaveProfile(); ((App)App.Current).PresentMainPage(); } }; Intent intent = (Intent)auth.GetUI(activity); activity.StartActivity(intent); }
public Tuple <AccountStore, string> GetAccountStore() { var accountStore = AccountStore.Create(); return(new Tuple <AccountStore, string>(accountStore, "com.monojit.development.TestShareComponent")); }
public iOSPlatformProvider() { AccountStore = AccountStore.Create(); }
public AccountStoreService(AccountStore accountStore, string serviceId) { _accountStore = accountStore; _serviceId = serviceId; }
public AccountStore GetAccountStore() { return(AccountStore.Create()); }
public string GetCredentials() { return(AccountStore.Create().FindAccountsForService("StoreUserInfo").FirstOrDefault().Username); }
/// <summary> /// Returns a previously saved password from the local AccountStore /// </summary> /// <returns>The password or null if none was set</returns> public string GetPassword() { var account = AccountStore.Create(Forms.Context).FindAccountsForService(appName).FirstOrDefault(); return((account != null) ? account.Properties["Password"] : null); }
private async void AccountStoreTests(object authenticator, AuthenticatorCompletedEventArgs ee) { string title = "AccountStore tests"; string msg = ""; AccountStore account_store = AccountStore.Create(); account_store.Save(ee.Account, provider); //------------------------------------------------------------------ // Android // https://kb.xamarin.com/agent/case/225411 // cannot reproduce Account account1 = account_store.FindAccountsForService(provider).FirstOrDefault(); if (null != account1) { //------------------------------------------------------------------ string token = default(string); if (null != account1) { string token_name = default(string); Type t = authenticator.GetType(); if (t == typeof(Xamarin.Auth._MobileServices.OAuth2Authenticator)) { token_name = "access_token"; token = account1.Properties[token_name].ToString(); } else if (t == typeof(Xamarin.Auth._MobileServices.OAuth1Authenticator)) { token_name = "oauth_token"; token = account1.Properties[token_name].ToString(); } } //------------------------------------------------------------------ MessageDialog md = new MessageDialog(msg, title); await md.ShowAsync(); } //------------------------------------------------------------------ AccountStore.Create().Save(ee.Account, provider + ".v.2"); //------------------------------------------------------------------ // throws on iOS // Account account2 = AccountStore.Create().FindAccountsForService(provider + ".v.2").FirstOrDefault(); if (null != account2) { //------------------------------------------------------------------ string token = default(string); if (null != account2) { string token_name = default(string); Type t = authenticator.GetType(); if (t == typeof(Xamarin.Auth._MobileServices.OAuth2Authenticator)) { token_name = "access_token"; token = account2.Properties[token_name].ToString(); } else if (t == typeof(Xamarin.Auth._MobileServices.OAuth1Authenticator)) { token_name = "oauth_token"; token = account2.Properties[token_name].ToString(); } } //------------------------------------------------------------------ MessageDialog md = new MessageDialog ( "access_token = " + token, "Access Token" ); await md.ShowAsync(); } //------------------------------------------------------------------ return; }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); if (MainActivity.Activities.ContainsKey("ShopInfoActivity")) { MainActivity.Activities["ShopInfoActivity"].Finish(); MainActivity.Activities.Remove("ShopInfoActivity"); MainActivity.Activities.Add("ShopInfoActivity", this); } else { MainActivity.Activities.Add("ShopInfoActivity", this); } // Create your application here SetContentView(Resource.Layout.ShopInfoLayout2); shopID = Intent.GetStringExtra("SHOP_ID_NUMBER"); local = Intent.GetStringExtra("Local"); ShopDBInformation DBShopContext = null; if (Data_ShopInfo.DIC_SHOP_DB_INFO_OVERALL_INFO.ContainsKey(shopID)) { DBShopContext = Data_ShopInfo.DIC_SHOP_DB_INFO_OVERALL_INFO[shopID]; } else { ShopDBInformation shopData = new ShopDBInformation() { BookMark = 0, Comment = "", Rating = 0f, IdentificationNumber = shopID }; Data_ShopInfo.DIC_SHOP_DB_INFO_OVERALL_INFO.Add(shopData.IdentificationNumber, shopData); DBShopContext = Data_ShopInfo.DIC_SHOP_DB_INFO_OVERALL_INFO[shopID]; Data_ShopInfo.InsertShopInfoData(shopData); } ShopInformation XMLShopContext = Data_ShopInfo.DIC_SHOP_XML_INFO_OVERALL_INFO[shopID]; TextView tv_ShopName = FindViewById <TextView>(Resource.Id.tv_ShopName); tv_ShopName.Text = XMLShopContext.ShopName; TextView tv_ShopAddress = FindViewById <TextView>(Resource.Id.tv_ShopAddress); tv_ShopAddress.Text = XMLShopContext.LocalNam; TextView tv_SaleKind = FindViewById <TextView>(Resource.Id.tv_SaleKind); tv_SaleKind.Text = XMLShopContext.Category; RatingBar ratingbar = FindViewById <RatingBar>(Resource.Id.ratingbar); ratingbar.Rating = DBShopContext.Rating; ratingbar.RatingBarChange += (o, e) => { Toast.MakeText(this, "New Rating: " + ratingbar.Rating.ToString(), ToastLength.Short).Show(); DBShopContext.Rating = ratingbar.Rating; Data_ShopInfo.SHOP_DB.UpdateShopData("Rating", DBShopContext.Rating, DBShopContext.IdentificationNumber); }; RatingBar bookmark = FindViewById <RatingBar>(Resource.Id.BookMark); bookmark.Rating = DBShopContext.BookMark; bookmark.Touch += (o, e) => { if (e.Event.ActionMasked == MotionEventActions.Up) { count++; if (count % 2 == 0) { bookmark.Rating = 0; DBShopContext.BookMark = 0; Data_ShopInfo.SHOP_DB.UpdateShopData("BookMark", DBShopContext.BookMark, DBShopContext.IdentificationNumber); } else { bookmark.Rating = 1; DBShopContext.BookMark = 1; Data_ShopInfo.SHOP_DB.UpdateShopData("BookMark", DBShopContext.BookMark, DBShopContext.IdentificationNumber); } } }; EditText et = FindViewById <EditText>(Resource.Id.et_comment); et.Text = DBShopContext.Comment.ToString(); et.TextChanged += (o, e) => { DBShopContext.Comment = et.Text; Data_ShopInfo.SHOP_DB.UpdateShopData("Comment", DBShopContext.Comment, DBShopContext.IdentificationNumber); }; int tweetcount = ("#" + XMLShopContext.ShopName + "(#" + XMLShopContext.LocalNam + GetString(Resource.String.UnderShopdddd) + "\n" + GetString(Resource.String.SaleKind) + " " + XMLShopContext.Category + "\n" + GetString(Resource.String.MyRating) + " " + ratingbar.Rating.ToString() + "\n" + GetString(Resource.String.MyComment) + " ").Length; global::Android.Text.IInputFilter[] fA = new Android.Text.IInputFilter[1]; fA[0] = new Android.Text.InputFilterLengthFilter(139 - tweetcount); et.SetFilters(fA); LinearLayout twit_sharing = FindViewById <LinearLayout>(Resource.Id.twit_sharing); LinearLayout twit_others_opinion = FindViewById <LinearLayout>(Resource.Id.twit_others_opinion); twit_sharing.Click += (o, e) => { Android.Net.ConnectivityManager connectivityManager = (Android.Net.ConnectivityManager)GetSystemService(ConnectivityService); Android.Net.NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo; bool isOnline = (activeConnection != null) && activeConnection.IsConnected; if (isOnline) { if (loggedInAccount == null) { Toast.MakeText(this, GetString(Resource.String.acquireLogin), ToastLength.Short).Show(); var auth = new OAuth1Authenticator( consumerKey: "qjXcnuCmZKPLU9Mupr0nkEcCv", consumerSecret: "q3c4nxTk1jqsLowujLxTmugsmdaLZFVq5cLI4SmWA1pRSlPcaD", requestTokenUrl: new Uri("https://api.twitter.com/oauth/request_token"), authorizeUrl: new Uri("https://api.twitter.com/oauth/authorize"), accessTokenUrl: new Uri("https://api.twitter.com/oauth/access_token"), callbackUrl: new Uri("http://www.hansei.ac.kr/")); //save the account data in the authorization completed even handler auth.Completed += (sender, eventArgs) => { if (eventArgs.IsAuthenticated) { loggedInAccount = eventArgs.Account; AccountStore.Create(this).Save(loggedInAccount, "UndertheShopTwitApp"); var cred = new LinqToTwitter.InMemoryCredentialStore(); cred.ConsumerKey = loggedInAccount.Properties["oauth_consumer_key"]; cred.ConsumerSecret = loggedInAccount.Properties["oauth_consumer_secret"]; cred.OAuthToken = loggedInAccount.Properties["oauth_token"]; cred.OAuthTokenSecret = loggedInAccount.Properties["oauth_token_secret"]; var auth0 = new LinqToTwitter.PinAuthorizer() { CredentialStore = cred, }; var TwitterCtx = new LinqToTwitter.TwitterContext(auth0); TwitterCtx.TweetAsync("#" + XMLShopContext.ShopName + "(#" + XMLShopContext.LocalNam + GetString(Resource.String.UnderShopdddd) + "\n" + GetString(Resource.String.SaleKind) + " " + XMLShopContext.Category + "\n" + GetString(Resource.String.MyRating) + " " + ratingbar.Rating.ToString() + "\n" + GetString(Resource.String.MyComment) + " " + et.Text); Toast.MakeText(this, GetString(Resource.String.TwitSharingComment), ToastLength.Short).Show(); } }; auth.Error += (sender, eventArgs) => { Toast.MakeText(this, GetString(Resource.String.authfail), ToastLength.Short).Show(); var next = new Intent(this.ApplicationContext, typeof(ShopInfoActivity)); next.PutExtra("SHOP_ID_NUMBER", shopID); next.PutExtra("Local", local); StartActivity(next); Finish(); }; var ui = auth.GetUI(this); StartActivityForResult(ui, -1); } else { var cred = new LinqToTwitter.InMemoryCredentialStore(); cred.ConsumerKey = loggedInAccount.Properties["oauth_consumer_key"]; cred.ConsumerSecret = loggedInAccount.Properties["oauth_consumer_secret"]; cred.OAuthToken = loggedInAccount.Properties["oauth_token"]; cred.OAuthTokenSecret = loggedInAccount.Properties["oauth_token_secret"]; var auth0 = new LinqToTwitter.PinAuthorizer() { CredentialStore = cred, }; var TwitterCtx = new LinqToTwitter.TwitterContext(auth0); TwitterCtx.TweetAsync("#" + XMLShopContext.ShopName + "(#" + XMLShopContext.LocalNam + GetString(Resource.String.UnderShopdddd) + "\n" + GetString(Resource.String.SaleKind) + " " + XMLShopContext.Category + "\n" + GetString(Resource.String.MyRating) + " " + ratingbar.ToString() + "\n" + GetString(Resource.String.MyComment) + " " + et.Text); Toast.MakeText(this, GetString(Resource.String.TwitSharingComment), ToastLength.Short).Show(); } } else { AlertDialog.Builder dlg = new AlertDialog.Builder(this); dlg.SetTitle(GetString(Resource.String.InternetCheck)); dlg.SetMessage(GetString(Resource.String.InternetCheckMessage)); dlg.SetIcon(Resource.Drawable.AppIcon); dlg.SetPositiveButton(GetString(Resource.String.confirm), (s, o2) => { }); dlg.Show(); } }; twit_others_opinion.Click += (o, e) => { Android.Net.ConnectivityManager connectivityManager = (Android.Net.ConnectivityManager)GetSystemService(ConnectivityService); Android.Net.NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo; bool isOnline = (activeConnection != null) && activeConnection.IsConnected; if (isOnline) { if (loggedInAccount == null) { Toast.MakeText(this, GetString(Resource.String.acquireLogin), ToastLength.Short).Show(); var auth = new OAuth1Authenticator( consumerKey: "qjXcnuCmZKPLU9Mupr0nkEcCv", consumerSecret: "q3c4nxTk1jqsLowujLxTmugsmdaLZFVq5cLI4SmWA1pRSlPcaD", requestTokenUrl: new Uri("https://api.twitter.com/oauth/request_token"), authorizeUrl: new Uri("https://api.twitter.com/oauth/authorize"), accessTokenUrl: new Uri("https://api.twitter.com/oauth/access_token"), callbackUrl: new Uri("http://www.hansei.ac.kr/")); //save the account data in the authorization completed even handler auth.Completed += (sender, eventArgs) => { if (eventArgs.IsAuthenticated) { loggedInAccount = eventArgs.Account; AccountStore.Create(this).Save(loggedInAccount, "UndertheShopTwitApp"); } if (loggedInAccount != null) { var ne = new Intent(this, typeof(SearchTwitter)); ne.PutExtra("keyword", "#" + XMLShopContext.ShopName); StartActivity(ne); } else { Toast.MakeText(this, GetString(Resource.String.authfail), ToastLength.Short).Show(); var next = new Intent(this.ApplicationContext, typeof(ShopInfoActivity)); next.PutExtra("SHOP_ID_NUMBER", shopID); next.PutExtra("Local", local); StartActivity(next); Finish(); } }; var ui = auth.GetUI(this); StartActivityForResult(ui, -1); } else { var ne = new Intent(this, typeof(SearchTwitter)); ne.PutExtra("keyword", "#" + XMLShopContext.ShopName); ne.PutExtra("SHOP_ID_NUMBER", shopID); ne.PutExtra("Local", local); StartActivity(ne); } } else { AlertDialog.Builder dlg = new AlertDialog.Builder(this); dlg.SetTitle(GetString(Resource.String.InternetCheck)); dlg.SetMessage(GetString(Resource.String.InternetCheckMessage)); dlg.SetIcon(Resource.Drawable.AppIcon); dlg.SetPositiveButton(GetString(Resource.String.confirm), (s, o2) => { }); dlg.Show(); } }; //twit_sharing.Click += (o, e) => { Tweet("#" + shopContext.ShopName + "(#"+shopContext.LocalNam+ GetString(Resource.String.UnderShopdddd) + "\n" + // GetString(Resource.String.SaleKind) +" " + shopContext.Category + "\n" + // GetString(Resource.String.MyRating) + " " + myRate.ToString() + "\n" + // GetString(Resource.String.MyComment) + " " + tv.Text , "Nothing"); }; //twit_others_opinion.Click += (o, e) => { // var next = new Intent(this, typeof(OthersOpinionActivity)); // next.PutExtra("ShopName", shopContext.ShopName); // StartActivity(next); //}; LinearLayout shopLoca = FindViewById <LinearLayout>(Resource.Id.shopLoca); shopLoca.Click += ShopLoca_Click; }
public OAuthNativeFlowPage() { InitializeComponent(); store = AccountStore.Create(); }
public void Init(Context context) { this.Context = context; AccountStore = AccountStore.Create(); }
public LoginCommand(LoginViewModel viewModel, AccountStore accountStore, INavigationService navigationService) { _viewModel = viewModel; _accountStore = accountStore; _navigationService = navigationService; }
/// <summary> /// Gets the saved accounts associated with this service. /// </summary> public virtual Task <IEnumerable <Account> > GetAccountsAsync() { return(Task.Factory.StartNew(delegate { return AccountStore.Create().FindAccountsForService(ServiceId); })); }
/// <summary> /// Initializes a new instance of the <see cref="AccessTokenStore"/> class. /// </summary> /// <param name="accountStore">The account store.</param> /// <exception cref="System.ArgumentNullException">accountStore</exception> public AccessTokenStore(AccountStore accountStore) { Requires.NotNull(accountStore, "accountStore"); this.accountStore = accountStore; }
public void Init(Context context) { RootView = context; AccountStore = AccountStore.Create(context); }
public bool DoCredentialsExist() { return(AccountStore.Create().FindAccountsForService("StoreUserInfo").Any() ? true : false); }
static App() { try { Container = new Container(); var analyticsSvc = DependencyService.Get <IAnalyticsService>(); var userService = new CurrentUserService(); var orderService = new AzureOrderService(new HttpClient(), _orderEndpoint, _apiKey); var propertyService = new PropertyService(new HttpClient(), _propertyEndpoint, new AnalyticsLogger <PropertyService>(analyticsSvc, userService)); var imageService = new BlobImageService(new HttpClient(), _blobEndpoint, new AnalyticsLogger <BlobImageService>(analyticsSvc, userService)); var subService = new SubscriptionService(new HttpClient(), _subEndpoint, new AnalyticsLogger <SubscriptionService>(analyticsSvc, userService)); var prService = new PurchasedReportService(new HttpClient(), _purchasedReportsEndpoint, new AnalyticsLogger <PurchasedReportService>(analyticsSvc, userService)); var authenticator = new OAuth2Authenticator(Configuration.ClientId, null, Configuration.Scope, new Uri(GoogleAuthorizeUrl), new Uri(Configuration.RedirectNoPath + ":" + Configuration.RedirectPath), new Uri(GoogleAccessTokenUrl), null, true); var notifyService = new NotificationService(new HttpClient(), _notifyEndpoint, _apiKey); var purchaseEmailLogger = new EmailLogger <PurchasingService>(notifyService, userService); var purchaseService = new PurchasingService(CrossInAppBilling.Current, purchaseEmailLogger); authenticator.Completed += (s, e) => { if (e.IsAuthenticated) { userService.LogIn(e.Account); } }; // Setup caches and begin process of filling them. var dbBasePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); var propertyCache = new LocalSqlCache <PropertyModel>(Path.Combine(dbBasePath, "property.db3"), new AnalyticsLogger <LocalSqlCache <PropertyModel> >(analyticsSvc, userService)); var orderCache = new LocalSqlCache <Models.Order>(Path.Combine(dbBasePath, "order.db3"), new AnalyticsLogger <LocalSqlCache <Models.Order> >(analyticsSvc, userService)); var imageCache = new LocalSqlCache <ImageModel>(Path.Combine(dbBasePath, "images.db3"), new AnalyticsLogger <LocalSqlCache <ImageModel> >(analyticsSvc, userService)); var subCache = new LocalSqlCache <SubscriptionModel>(Path.Combine(dbBasePath, "subs.db3"), new AnalyticsLogger <LocalSqlCache <SubscriptionModel> >(analyticsSvc, userService)); var settingsCache = new LocalSqlCache <SettingsModel>(Path.Combine(dbBasePath, "sets.db3"), new AnalyticsLogger <LocalSqlCache <SettingsModel> >(analyticsSvc, userService)); var prCache = new LocalSqlCache <PurchasedReportModel>(Path.Combine(dbBasePath, "purchasedreports.db3"), new AnalyticsLogger <LocalSqlCache <PurchasedReportModel> >(analyticsSvc, userService)); var startUpLogger = new AnalyticsLogger <App>(analyticsSvc, userService); Action ClearCaches = () => { try { orderCache.Clear(); propertyCache.Clear(); imageCache.Clear(); subCache.Clear(); prCache.Clear(); } catch { } }; Func <AccountModel, Task> RefreshCaches = user => { var userId = user.UserId; var prTask = Task.Run(() => { try { var prs = prService.GetPurchasedReports(userId); prCache.Put(prs.ToDictionary(x => x.PurchaseId, x => x)); } catch (Exception ex) { startUpLogger.LogError("Failed to get purchased reports on refresh.", ex); } }); var orderTask = Task.Run(async() => { try { var orders = await orderService.GetMemberOrders(userId); var unCached = orders.Except(orderCache.GetAll().Select(x => x.Value).ToList(), new OrderEqualityComparer()).ToList(); orderCache.Put(orders.ToDictionary(x => x.OrderId, x => x)); var subTask = Task.Run(() => { try { DependencyService.Get <IMessagingSubscriber>().Subscribe(orders.Select(x => $"{(Device.RuntimePlatform == Device.Android ? App.TopicPrefix : "")}{x.OrderId}").ToList()); } catch { } }); var propTask = Task.Run(async() => { if (!orders.Any()) { propertyCache.Clear(); return; } var properties = await propertyService.GetProperties(unCached.Select(x => x.OrderId).ToList()); propertyCache.Update(properties); }); var imgTask = Task.Run(() => { if (!orders.Any()) { imageCache.Clear(); return; } var images = imageService.GetImages(unCached.Select(x => x.OrderId).ToList()); imageCache.Update(images); }); var subscriptionTask = Task.Run(async() => { try { // TODO: Refactor this so it can be tested. var allSubs = subService.GetSubscriptions(userId).OrderBy(x => x.StartDateTime).ToList(); var recentSub = allSubs.LastOrDefault(); var purchases = new List <InAppBillingPurchase>(); SubscriptionModel newSub = null; // Check app store purchases to see if they auto-renewed if (recentSub != null && !SubscriptionUtility.SubscriptionActive(recentSub)) { try { purchases = (await purchaseService.GetPurchases(ItemType.Subscription)).ToList(); } catch (Exception ex) { purchaseEmailLogger.LogError($"Error occurred while getting purchases.", ex); } var mostRecent = purchases.OrderBy(x => x.TransactionDateUtc)?.LastOrDefault(); if (mostRecent != null) { newSub = SubscriptionUtility.GetModelFromIAP(mostRecent, user, recentSub); if (newSub != null) { allSubs.Add(newSub); subService.AddSubscription(newSub); } } } if (!allSubs.Any()) { subCache.Clear(); } else { subCache.Put(allSubs.ToDictionary(x => x.PurchaseId, x => x)); } } catch (Exception ex) { startUpLogger.LogError("Failed to get subscriptions on refresh.", ex); } }); await Task.WhenAll(new[] { propTask, imgTask, subTask, subscriptionTask }); } catch (Exception ex) { startUpLogger.LogError($"Failed to fill caches.\n{ex.ToString()}", ex); } }); return(Task.WhenAll(new[] { prTask, orderTask })); }; var refresher = new CacheRefresher(new AnalyticsLogger <CacheRefresher>(analyticsSvc, userService), RefreshCaches); refresher.Invalidate(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed refresher.RefreshCaches(userService.GetLoggedInAccount()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed userService.OnLoggedIn += async(s, e) => { ClearCaches(); await refresher.RefreshCaches(e.Account); }; userService.OnLoggedOut += (s, e) => ClearCaches(); // Register services Container.Register <IOrderService>(() => orderService, Lifestyle.Singleton); Container.Register <IPropertyService>(() => propertyService, Lifestyle.Singleton); Container.Register <IImageService>(() => imageService, Lifestyle.Singleton); Container.Register <INotificationService>(() => notifyService, Lifestyle.Singleton); Container.Register <ILogger <SingleReportPurchaseViewModel> >(() => new EmailLogger <SingleReportPurchaseViewModel>(notifyService, userService), Lifestyle.Singleton); Container.RegisterConditional(typeof(ILogger <>), typeof(AnalyticsLogger <>), c => !c.Handled); Container.Register <OAuth2Authenticator>(() => authenticator, Lifestyle.Singleton); Container.Register <AccountStore>(() => AccountStore.Create(), Lifestyle.Singleton); Container.Register <ICurrentUserService>(() => userService, Lifestyle.Singleton); Container.Register <IPurchasingService>(() => purchaseService, Lifestyle.Singleton); Container.Register <ICacheRefresher>(() => refresher, Lifestyle.Singleton); Container.Register <ISubscriptionService>(() => subService, Lifestyle.Singleton); Container.Register <IOrderValidationService, OrderValidationService>(); Container.Register <IPageFactory, PageFactory>(Lifestyle.Singleton); Container.Register <IToastService>(() => DependencyService.Get <IToastService>(), Lifestyle.Singleton); Container.Register <IMessagingSubscriber>(() => DependencyService.Get <IMessagingSubscriber>(), Lifestyle.Singleton); Container.Register <IMessagingCenter>(() => MessagingCenter.Instance, Lifestyle.Singleton); Container.Register <IPurchasedReportService>(() => prService, Lifestyle.Singleton); Container.Register <IAnalyticsService>(() => analyticsSvc, Lifestyle.Singleton); Container.Register <LaunchedFromPushModel>(() => App.PushModel ?? new LaunchedFromPushModel(), Lifestyle.Singleton); // Finish registering created caches Container.Register <ICache <PropertyModel> >(() => propertyCache, Lifestyle.Singleton); Container.Register <ICache <Models.Order> >(() => orderCache, Lifestyle.Singleton); Container.Register <ICache <ImageModel> >(() => imageCache, Lifestyle.Singleton); Container.Register <ICache <SubscriptionModel> >(() => subCache, Lifestyle.Singleton); Container.Register <ICache <SettingsModel> >(() => settingsCache, Lifestyle.Singleton); Container.Register <ICache <PurchasedReportModel> >(() => prCache, Lifestyle.Singleton); Container.RegisterConditional(typeof(ICache <>), typeof(MemoryCache <>), c => !c.Handled); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); throw; } }
public bool DoCredentialsExist() { return(AccountStore.Create().FindAccountsForService(App.AppName).Any() ? true : false); }
public Account SaveAccount(Account account, string appName) { AccountStore.Create(this).Save(account, appName); return(account); }
public AccountStore GetAccountStore() { return(AccountStore.Create(Forms.Context)); }
public OAuth() { InitializeComponent(); store = AccountStore.Create(); }
//this is from https://stackoverflow.com/questions/24105390/how-to-login-to-facebook-in-xamarin-forms/24423833#24423833 //https://forums.xamarin.com/discussion/26374/onmodelchanged-event-not-found-for-android-page-renderer //notice the OnModel is outdated you should use OnElementChanged but OnElementChanged is called twice protected override void OnElementChanged(ElementChangedEventArgs <Xamarin.Forms.Page> e) { base.OnElementChanged(e); if (e.OldElement != null || Element == null) { return; } if (!instance) { Console.WriteLine("Called"); instance = true; return; } //try to retrive account IEnumerable <Account> accounts = AccountStore.Create().FindAccountsForService("Facebook"); // this is a ViewGroup - so should be able to load an AXML file and FindView<> var activity = this.Context as Activity; //for facebook var auth = new OAuth2Authenticator( clientId: "203538636868958", // your OAuth2 client id scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"), // the auth URL for the service redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html")); // the redirect URL for the service //for google // google is non working /* var auth = new OAuth2Authenticator( * clientId: "833412182850-lvl6gh2pprh35dnutrnb61thgcq4efic.apps.googleusercontent.com", // your OAuth2 client id * scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols * authorizeUrl: new Uri("https://accounts.google.com/o/oauth2/auth/"), // the auth URL for the service * redirectUrl: new Uri("https://www.googleapis.com/oauth2/v2/userinfo"), * accessTokenUrl:new Uri("https://www.googleapis.com/oauth2/v4/token"), * getUsernameAsync: null, * clientSecret: "oL9klRrrltzSmmSF8Fd-Jbli"); // the redirect URL for the service */ auth.Completed += (sender, eventArgs) => { if (eventArgs.IsAuthenticated) { App.SuccessfulLoginActionFacebook.Invoke(); // Use eventArgs.Account to do wonderful things var account = eventArgs.Account; var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?fields=email,first_name,last_name,gender,picture"), null, account); AccountStore.Create().Save(eventArgs.Account, "Facebook"); var x = Task.Run(async() => { return(await request.GetResponseAsync()); }); x.ContinueWith( t => { if (t.IsFaulted) { Console.WriteLine("Error: " + t.Exception.InnerException.Message); } else { string json = t.Result.GetResponseText(); Console.WriteLine(json); } } ).ConfigureAwait(false); App.SaveToken(eventArgs.Account.Properties["access_token"]); App.MasterDetailPage(); } else { Console.WriteLine("User Cancelled"); activity.StartActivity(typeof(MainActivity)); //we restart it activity.Finish(); //we lose the previews activities entirly } }; activity.StartActivity(auth.GetUI(activity)); }
private async void LoginButton_Click(object sender, System.EventArgs e) { EditText email = FindViewById <EditText>(Resource.Id.et_login_email); EditText password = FindViewById <EditText>(Resource.Id.et_login_password); Regex emailRegex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"); if (string.IsNullOrEmpty(email.Text)) { email.Error = "Въведете e-mail"; } else if (!emailRegex.IsMatch(email.Text)) { email.Error = "Въведете валиден e-mail"; } else if (string.IsNullOrEmpty(password.Text)) { password.Error = "Въведете парола"; } else if (password.Text.Length < 6 && password.Text.Length > 15) { password.Error = "Парола трябва да е между 6 и 15 символа"; } else { var loginUser = new LoginUser { Email = email.Text, Password = password.Text }; AndHUD.Shared.Show(this, "Влизане…"); HttpResponseMessage httpResponse = await RestManager.LoginUser(loginUser); if (httpResponse.IsSuccessStatusCode) { string response = await httpResponse.Content.ReadAsStringAsync(); UserCredentials userCredentials = JsonConvert.DeserializeObject <UserCredentials>(response); Account account = new Account { Username = loginUser.Email }; account.Properties.Add("token", userCredentials.AccessToken); account.Properties.Add("roles", userCredentials.Roles); account.Properties.Add("memberId", userCredentials.MemberId.ToString()); string appName = GetString(Resource.String.app_name); AccountStore.Create(this).Save(account, appName); RestManager.SetAccessToken(userCredentials.AccessToken); Intent intent = new Intent(this, typeof(UserProfileActivity)); StartActivity(intent); } else { Toast.MakeText(ApplicationContext, "Грешен имейл и/или парола", ToastLength.Long).Show(); } AndHUD.Shared.Dismiss(this); } }
public LoginPage() { InitializeComponent(); store = AccountStore.Create(); }
protected override AccountStore GetStore() { return(AccountStore.Create()); }
public TestLogin() { InitializeComponent(); store = AccountStore.Create(); }
private async void AccountStoreTestsAsync(object authenticator, AuthenticatorCompletedEventArgs ee) { AccountStore account_store = AccountStore.Create(); await account_store.SaveAsync(ee.Account, provider); //------------------------------------------------------------------ // Android // https://kb.xamarin.com/agent/case/225411 // cannot reproduce try { //------------------------------------------------------------------ // Xamarin.iOS - following line throws IEnumerable <Account> accounts = await account_store.FindAccountsForServiceAsync(provider); Account account1 = accounts.FirstOrDefault(); //------------------------------------------------------------------ if (null != account1) { string token = default(string); string token_name = default(string); Type t = authenticator.GetType(); if (t == typeof(Xamarin.Auth._MobileServices.OAuth2Authenticator)) { token_name = "access_token"; token = account1.Properties[token_name].ToString(); } else if (t == typeof(Xamarin.Auth._MobileServices.OAuth1Authenticator)) { token_name = "oauth_token"; token = account1.Properties[token_name].ToString(); } UIAlertView alert = new UIAlertView ( "Token 3", "access_token = " + token, null, "OK", null ); alert.Show(); } } catch (System.Exception exc) { // Xamarin.iOS // exc {System.ArgumentNullException: Value cannot be null. // Parameter name: data // at Foundation.NSString.Fr…} System.ArgumentNullException // Value cannot be null. // Parameter name: data string msg = exc.Message; System.Diagnostics.Debug.WriteLine("Exception AccountStore: " + msg); } try { await AccountStore.Create().SaveAsync(ee.Account, provider + ".v.2"); } catch (System.Exception exc) { string msg = exc.Message; System.Diagnostics.Debug.WriteLine("Exception AccountStore: " + msg); } try { //------------------------------------------------------------------ // Xamarin.iOS - throws IEnumerable <Account> accounts = await account_store.FindAccountsForServiceAsync(provider + ".v.2"); Account account2 = accounts.FirstOrDefault(); //------------------------------------------------------------------ if (null != account2) { string token = default(string); string token_name = default(string); Type t = authenticator.GetType(); if (t == typeof(Xamarin.Auth._MobileServices.OAuth2Authenticator)) { token_name = "access_token"; token = account2.Properties[token_name].ToString(); } else if (t == typeof(Xamarin.Auth._MobileServices.OAuth1Authenticator)) { token_name = "oauth_token"; token = account2.Properties[token_name].ToString(); } UIAlertView alert = new UIAlertView ( "Token 4", "access_token = " + token, null, "OK", null ); alert.Show(); } } catch (System.Exception exc) { string msg = exc.Message; System.Diagnostics.Debug.WriteLine("Exception AccountStore: " + msg); } return; }
public FacebookVM() { store = AccountStore.Create(); }
protected override void OnCreate(Bundle savedInstanceState) { // Set the current instance of MainActivity. CurrentActivity = this; App.ScreenWidth = (int)Resources.DisplayMetrics.WidthPixels; // real pixels App.ScreenHeight = (int)Resources.DisplayMetrics.HeightPixels; // real pixels App.ScreenDPI = (int)Resources.DisplayMetrics.DensityDpi; TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(savedInstanceState); if (!App.NotificationOn) { _player = MediaPlayer.Create(this, Resource.Raw.siren2); } App.Init((IAuthenticate)this); if (savedInstanceState != null) { isStarted = savedInstanceState.GetBoolean(Constants.SERVICE_STARTED_KEY, false); } //wire up WireUpLongRunningTask(); /*startServiceIntent = new Intent(this, typeof(TimestampService)); * startServiceIntent.SetAction(Constants.ACTION_START_SERVICE); * * * stopServiceIntent = new Intent(this, typeof(TimestampService)); * stopServiceIntent.SetAction(Constants.ACTION_STOP_SERVICE);*/ OnNewIntent(this.Intent); //SetContentView(Resource.Layout.Main); // On Android: var accounts = AccountStore.Create(this).FindAccountsForService("Facebook"); var account = accounts.FirstOrDefault(); if (account != null) { App.IsLoggedIn = true; } UserDialogs.Init(this); Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init(); Xamarin.FormsMaps.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); //ImageCircleRenderer.Init(); LoadApplication(new App()); //StartService(startServiceIntent); try { // Check to ensure everything's setup right GcmClient.CheckDevice(this); GcmClient.CheckManifest(this); // Register for push notifications System.Diagnostics.Debug.WriteLine("Registering..."); GcmClient.Register(this, PushHandlerBroadcastReceiver.SENDER_IDS); } catch (Java.Net.MalformedURLException) { CreateAndShowDialog("There was an error creating the client. Verify the URL.", "Error"); } catch (Exception e) { CreateAndShowDialog(e.Message, "Error"); } }
public CredentialStore() { store = AccountStore.Create(); var records = store.FindAccountsForService (context); }
public static void SaveCredentials(Account account) { AccountStore.Create().Save(account, App.AppName); }
public static void RemoveCredentials() { AccountStore.Create().Delete(AppAccount, App.AppName); }
public SecureDataStore(IMvxAndroidCurrentTopActivity currentTopActivity) { _accountStore = AccountStore.Create(currentTopActivity.Activity); }