Beispiel #1
0
        public async static Task UploadAsync(this IMobileServiceClient client, MobileServiceFile file, IMobileServiceFileDataSource dataSource)
        {
            MobileServiceFileMetadata metadata = MobileServiceFileMetadata.FromFile(file);

            IMobileServiceFilesClient filesClient = GetFilesClient(client);
            await filesClient.UploadFileAsync(metadata, dataSource);
        }
        public AzureService()
        {
            string MyAppServiceURL = "http://mxamarincats.azurewebsites.net";

            Client = new MobileServiceClient(MyAppServiceURL);
            Table  = Client.GetTable <T>();
        }
Beispiel #3
0
 public LoginViewModel(IMobileServiceClient client, IAuthenticationService authService, INavigationService navService)
 {
     this._authService         = authService;
     this._navigationService   = navService;
     this._mobileServiceClient = client;
     UpdateCommand             = new Command(Update);
 }
        public async Task ReadAsync_RoundTripsDate_Generic()
        {
            string tableName = "NotSystemPropertyCreatedAtType";

            ResetDatabase(tableName);

            var store = new MobileServiceSQLiteStore(TestDbName);

            store.DefineTable <NotSystemPropertyCreatedAtType>();

            var hijack = new TestHttpHandler();
            IMobileServiceClient service = await CreateClient(hijack, store);

            IMobileServiceSyncTable <NotSystemPropertyCreatedAtType> table = service.GetSyncTable <NotSystemPropertyCreatedAtType>();

            DateTime theDate  = new DateTime(2014, 3, 10, 0, 0, 0, DateTimeKind.Utc);
            var      inserted = new NotSystemPropertyCreatedAtType()
            {
                __CreatedAt = theDate
            };
            await table.InsertAsync(inserted);

            Assert.AreEqual(inserted.__CreatedAt.ToUniversalTime(), theDate);

            NotSystemPropertyCreatedAtType rehydrated = await table.LookupAsync(inserted.Id);

            Assert.AreEqual(rehydrated.__CreatedAt.ToUniversalTime(), theDate);
        }
Beispiel #5
0
        private async Task <bool> Login(IMobileServiceClient client)
        {
            var authentication = ServiceLocator.Instance.Resolve <IAuthentication>();

            if (authentication == null)
            {
                throw new InvalidOperationException("Make sure the ServiceLocator has an instance of IAuthentication");
            }


            var accountType = GetProviderType();

            try
            {
                var user = await authentication.LoginAsync(client, accountType);

                if (user != null)
                {
                    return(true);
                }
            }
            catch (System.Exception e)
            {
                Logger.Instance.Report(e);
            }

            return(false);
        }
        public async Task ReadAsync_RoundTripsBytes()
        {
            const string tableName = "bytes_test_table";

            ResetDatabase(tableName);

            var store = new MobileServiceSQLiteStore(TestDbName);

            store.DefineTable(tableName, new JObject {
                { "id", String.Empty },
                { "data", new byte[0] }
            });

            var hijack = new TestHttpHandler();
            IMobileServiceClient service = await CreateClient(hijack, store);

            IMobileServiceSyncTable table = service.GetSyncTable(tableName);

            byte[] theData = { 0, 128, 255 };

            JObject inserted = await table.InsertAsync(new JObject { { "data", theData } });

            Assert.AreEquivalent(theData, inserted["data"].Value <byte[]>());

            JObject rehydrated = await table.LookupAsync(inserted["id"].Value <string>());

            Assert.AreEquivalent(theData, rehydrated["data"].Value <byte[]>());
        }
        public async Task InsertAsync_Throws_IfItemAlreadyExistsInLocalStore()
        {
            ResetDatabase(TestTable);

            var store = new MobileServiceSQLiteStore(TestDbName);

            store.DefineTable(TestTable, new JObject()
            {
                { "id", String.Empty },
                { "String", String.Empty }
            });

            var hijack = new TestHttpHandler();
            IMobileServiceClient service = await CreateClient(hijack, store);

            string pullResult = "[{\"id\":\"abc\",\"String\":\"Wow\"}]";

            hijack.AddResponseContent(pullResult);
            hijack.AddResponseContent("[]");

            IMobileServiceSyncTable table = service.GetSyncTable(TestTable);
            await table.PullAsync(null, null);

            var ex = await AssertEx.Throws <MobileServiceLocalStoreException>(() => table.InsertAsync(new JObject()
            {
                { "id", "abc" }
            }));

            Assert.AreEqual(ex.Message, "An insert operation on the item is already in the queue.");
        }
Beispiel #8
0
        private async Task <bool> Login(IMobileServiceClient client)
        {
            var authentication = DependencyService.Get <IAuthenticator>();

            if (authentication == null)
            {
                throw new InvalidOperationException("Make sure the ServiceLocator has an instance of IAuthenticator.");
            }

            var accountType = ProviderType;
            var parameters  = App.LoginParameters;

            try
            {
                var user = await authentication.LoginAsync(client, accountType, parameters);

                if (user != null)
                {
                    return(true);
                }
            }
            catch (System.Exception e)
            {
            }

            return(false);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MobileServiceAuthentication"/> class.
        /// </summary>
        /// <param name="client">
        /// The <see cref="MobileServiceClient"/> associated with this 
        /// MobileServiceLogin instance.
        /// </param>
        /// <param name="providerName">
        /// The <see cref="MobileServiceAuthenticationProvider"/> used to authenticate.
        /// </param>
        /// <param name="parameters">
        /// Provider specific extra parameters that are sent as query string parameters to login endpoint.
        /// </param>
        public MobileServiceAuthentication(IMobileServiceClient client, string providerName, IDictionary<string, string> parameters)
        {
            Debug.Assert(client != null, "client should not be null.");
            if (providerName == null)
            {
                throw new ArgumentNullException("providerName");
            }

            this.Client = client;
            this.Parameters = parameters;
            this.ProviderName = providerName;
            string path = MobileServiceUrlBuilder.CombinePaths(LoginAsyncUriFragment, this.ProviderName);
            string loginAsyncDoneUriFragment = MobileServiceAuthentication.LoginAsyncDoneUriFragment;
            if (!string.IsNullOrEmpty(this.Client.LoginUriPrefix))
            {
                path = MobileServiceUrlBuilder.CombinePaths(this.Client.LoginUriPrefix, this.ProviderName);
                loginAsyncDoneUriFragment = MobileServiceUrlBuilder.CombinePaths(this.Client.LoginUriPrefix, "done");
            }
            string queryString = MobileServiceUrlBuilder.GetQueryString(parameters, useTableAPIRules: false);
            string pathAndQuery = MobileServiceUrlBuilder.CombinePathAndQuery(path, queryString);

            this.StartUri = new Uri(this.Client.MobileAppUri, pathAndQuery);
            this.EndUri = new Uri(this.Client.MobileAppUri, loginAsyncDoneUriFragment);

            if (this.Client.AlternateLoginHost != null)
            {
                this.StartUri = new Uri(this.Client.AlternateLoginHost, pathAndQuery);
                this.EndUri = new Uri(this.Client.AlternateLoginHost, loginAsyncDoneUriFragment);
            }
        }
Beispiel #10
0
        public AzureService()
        {
            string MyAppServiceURL = "http://demodeveloperxamarin.azurewebsites.net";

            Client = new MobileServiceClient(MyAppServiceURL);
            Table  = Client.GetTable <Contacts>();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MobileServiceAuthentication"/> class.
        /// </summary>
        /// <param name="client">
        /// The <see cref="MobileServiceClient"/> associated with this
        /// MobileServiceLogin instance.
        /// </param>
        /// <param name="providerName">
        /// The <see cref="MobileServiceAuthenticationProvider"/> used to authenticate.
        /// </param>
        /// <param name="parameters">
        /// Provider specific extra parameters that are sent as query string parameters to login endpoint.
        /// </param>
        public MobileServiceAuthentication(IMobileServiceClient client, string providerName, IDictionary <string, string> parameters)
        {
            Debug.Assert(client != null, "client should not be null.");
            if (providerName == null)
            {
                throw new ArgumentNullException("providerName");
            }

            this.Client       = client;
            this.Parameters   = parameters;
            this.ProviderName = providerName;
            string path = MobileServiceUrlBuilder.CombinePaths(LoginAsyncUriFragment, this.ProviderName);
            string loginAsyncDoneUriFragment = MobileServiceAuthentication.LoginAsyncDoneUriFragment;

            if (!string.IsNullOrEmpty(this.Client.LoginUriPrefix))
            {
                path = MobileServiceUrlBuilder.CombinePaths(this.Client.LoginUriPrefix, this.ProviderName);
                loginAsyncDoneUriFragment = MobileServiceUrlBuilder.CombinePaths(this.Client.LoginUriPrefix, "done");
            }
            string queryString  = MobileServiceUrlBuilder.GetQueryString(parameters, useTableAPIRules: false);
            string pathAndQuery = MobileServiceUrlBuilder.CombinePathAndQuery(path, queryString);

            this.StartUri = new Uri(this.Client.MobileAppUri, pathAndQuery);
            this.EndUri   = new Uri(this.Client.MobileAppUri, loginAsyncDoneUriFragment);

            if (this.Client.AlternateLoginHost != null)
            {
                this.StartUri = new Uri(this.Client.AlternateLoginHost, pathAndQuery);
                this.EndUri   = new Uri(this.Client.AlternateLoginHost, loginAsyncDoneUriFragment);
            }
        }
Beispiel #12
0
        public async Task <bool> LoginAsync(IMobileServiceClient client, MobileServiceAuthenticationProvider provider)
        {
            var success = false;

            try
            {
                var user = await client.LoginAsync(Xamarin.Forms.Forms.Context, provider);

                if (user != null)
                {
                    Settings.AuthToken = user.MobileServiceAuthenticationToken;

                    var employee = await client.InvokeApiAsync <Employee>("UserInfo", System.Net.Http.HttpMethod.Get, null);

                    Settings.FirstName = employee.FirstName;
                    Settings.LastName  = employee.LastName;
                    Settings.PhotoUrl  = employee.PhotoUrl;
                    Settings.UserId    = employee.Id;

                    Xamarin.Forms.Application.Current.MainPage = new RootPage();

                    return(true);
                }

                return(false);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error logging in: {ex.Message}");
            }

            return(success);
        }
Beispiel #13
0
        public AzureServices()
        {
            string MyAppServiceURL = "http://pedro1teste.azurewebsites.net";

            Client = new MobileServiceClient(MyAppServiceURL);
            Table  = Client.GetTable <Model.Luminosidade>();
        }
        public async Task InitializeAsync()
        {
            this.MobileService =
                new MobileServiceClient(MobileUrl, new LoggingHandler());

            //   string filename = "local.db";
            //   string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            //   string libraryPath = Path.Combine(documentsPath, "..", "Library");
            //   var path = Path.Combine(libraryPath, filename);
            //   var path = Path.Combine(documentsPath, filename);

            //  if (!File.Exists(path))
            //  {
            //      File.Create(path).Dispose();
            //  }
            //var store = new MobileServiceSQLiteStore(path);

            var store = new MobileServiceSQLiteStore("local.db");

            store.DefineTable <Job>();

            jobTable = MobileService.GetSyncTable <Job>();

            await MobileService.SyncContext.InitializeAsync(store, StoreTrackingOptions.NotifyLocalAndServerOperations);

            // jobTable = MobileService.GetSyncTable<Job>();
        }
Beispiel #15
0
        public AzureService()
        {
            string MyAppServiceURL = "http://catsappdiplomado.azurewebsites.net";

            Client = new MobileServiceClient(MyAppServiceURL);
            Table  = Client.GetTable <T>();
        }
 public static void Client(
     [MobileTable(MobileAppUriSetting = "MyUri", ApiKeySetting = "MyKey")] IMobileServiceClient client,
     TraceWriter trace)
 {
     Assert.NotNull(client);
     trace.Warning("Client");
 }
Beispiel #17
0
        public AzureRepository()
        {
            string MyAppServiceURL = "https://calculadorafreelancer01.azurewebsites.net";

            Client = new MobileServiceClient(MyAppServiceURL);
            Table  = Client.GetTable <TEntity>();
        }
Beispiel #18
0
      public AzureService()
      {
          MobileService = AuthInfo.Instance.GetMobileServiceClient();

          //MobileService = new MobileServiceClient(
          //    AuthInfo.APPLICATION_URL, AuthInfo.APPLICATION_KEY);
      }
        public async Task ReadAsync_RoundTripsBytes_Generic()
        {
            const string tableName = "BytesType";

            ResetDatabase(tableName);

            var store = new MobileServiceSQLiteStore(TestDbName);

            store.DefineTable <BytesType>();

            var hijack = new TestHttpHandler();
            IMobileServiceClient service = await CreateClient(hijack, store);

            IMobileServiceSyncTable <BytesType> table = service.GetSyncTable <BytesType>();

            byte[] theData = { 0, 128, 255 };

            BytesType inserted = new BytesType {
                Data = theData
            };

            await table.InsertAsync(inserted);

            Assert.AreEquivalent(inserted.Data, theData);

            BytesType rehydrated = await table.LookupAsync(inserted.Id);

            Assert.AreEquivalent(rehydrated.Data, theData);
        }
Beispiel #20
0
        public override async Task <MobileServiceUser> LoginAsync(IMobileServiceClient client, MobileServiceAuthenticationProvider provider, IDictionary <string, string> parameters = null)
        {
            try
            {
                var window = UIKit.UIApplication.SharedApplication.KeyWindow;
                var root   = window.RootViewController;
                if (root == null)
                {
                    return(null);
                }

                var current = root;
                while (current.PresentedViewController != null)
                {
                    current = current.PresentedViewController;
                }

                return(await client.LoginAsync(current, provider, parameters));
            }
            catch (Exception e)
            {
                e.Data["method"] = "LoginAsync";
            }

            return(null);
        }
        public async Task ReadAsync_RoundTripsDate()
        {
            string tableName = "itemWithDate";

            ResetDatabase(tableName);

            var store = new MobileServiceSQLiteStore(TestDbName);

            store.DefineTable(tableName, new JObject()
            {
                { "id", String.Empty },
                { "date", DateTime.Now }
            });

            var hijack = new TestHttpHandler();
            IMobileServiceClient service = await CreateClient(hijack, store);

            IMobileServiceSyncTable table = service.GetSyncTable(tableName);

            DateTime theDate  = new DateTime(2014, 3, 10, 0, 0, 0, DateTimeKind.Utc);
            JObject  inserted = await table.InsertAsync(new JObject()
            {
                { "date", theDate }
            });

            Assert.AreEqual(inserted["date"].Value <DateTime>(), theDate);

            JObject rehydrated = await table.LookupAsync(inserted["id"].Value <string>());

            Assert.AreEqual(rehydrated["date"].Value <DateTime>(), theDate);
        }
Beispiel #22
0
        public AzureService()
        {
            string MyAppServiceURL = "http://meodemoxamarin.azurewebsites.net/";

            Client = new MobileServiceClient(MyAppServiceURL);
            table  = Client.GetTable <T>();
        }
        internal MobileServiceFileSyncContext(IMobileServiceClient client, IFileMetadataStore metadataStore, IFileOperationQueue operationsQueue, 
            IFileSyncTriggerFactory syncTriggerFactory, IFileSyncHandler syncHandler, IMobileServiceFilesClient filesClient)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            if (metadataStore == null)
            {
                throw new ArgumentNullException("metadataStore");
            }

            if (operationsQueue == null)
            {
                throw new ArgumentNullException("operationsQueue");
            }

            if (syncTriggerFactory == null)
            {
                throw new ArgumentNullException("syncTriggerFactory");
            }

            if (syncHandler == null)
            {
                throw new ArgumentNullException("syncHandler");
            }

            this.metadataStore = metadataStore;
            this.syncHandler = syncHandler;
            this.operationsQueue = operationsQueue;
            this.mobileServiceFilesClient = filesClient ?? new MobileServiceFilesClient(client, new AzureBlobStorageProvider(client));
            this.eventManager = client.EventManager;
            this.triggers = syncTriggerFactory.CreateTriggers(this);
        }
Beispiel #24
0
        public async Task SystemPropertiesArePreserved_OnlyWhenReturnedFromServer()
        {
            ResetDatabase(TestTable);

            var hijack = new TestHttpHandler();
            var store  = new MobileServiceSQLiteStore(TestDbName);

            store.DefineTable <ToDoWithSystemPropertiesType>();

            IMobileServiceClient service = await CreateClient(hijack, store);

            IMobileServiceSyncTable <ToDoWithSystemPropertiesType> table = service.GetSyncTable <ToDoWithSystemPropertiesType>();

            // first insert an item
            var updatedItem = new ToDoWithSystemPropertiesType()
            {
                Id        = "b",
                String    = "Hey",
                Version   = "abc",
                CreatedAt = new DateTime(2013, 1, 1, 1, 1, 1, DateTimeKind.Utc),
                UpdatedAt = new DateTime(2013, 1, 1, 1, 1, 2, DateTimeKind.Utc)
            };
            await table.UpdateAsync(updatedItem);

            var lookedupItem = await table.LookupAsync("b");

            Assert.Equal("Hey", lookedupItem.String);
            Assert.Equal("abc", lookedupItem.Version);
            // we ignored the sys properties on the local object
            Assert.Equal(lookedupItem.CreatedAt, new DateTime(0, DateTimeKind.Utc));
            Assert.Equal(lookedupItem.UpdatedAt, new DateTime(0, DateTimeKind.Utc));

            Assert.Equal(1L, service.SyncContext.PendingOperations); // operation pending

            hijack.OnSendingRequest = async req =>
            {
                string content = await req.Content.ReadAsStringAsync();

                Assert.Equal(@"{""id"":""b"",""String"":""Hey""}", content); // the system properties are not sent to server
                return(req);
            };
            string updateResult = "{\"id\":\"b\",\"String\":\"Wow\",\"version\":\"def\",\"createdAt\":\"2014-01-29T23:01:33.444Z\", \"updatedAt\":\"2014-01-30T23:01:33.444Z\"}";

            hijack.Responses.Add(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(updateResult)
            });                                                                                                             // push
            await service.SyncContext.PushAsync();

            Assert.Equal(0L, service.SyncContext.PendingOperations); // operation removed

            lookedupItem = await table.LookupAsync("b");

            Assert.Equal("Wow", lookedupItem.String);
            Assert.Equal("def", lookedupItem.Version);
            // we preserved the system properties returned from server on update
            Assert.Equal(lookedupItem.CreatedAt.ToUniversalTime(), new DateTime(2014, 01, 29, 23, 1, 33, 444, DateTimeKind.Utc));
            Assert.Equal(lookedupItem.UpdatedAt.ToUniversalTime(), new DateTime(2014, 01, 30, 23, 1, 33, 444, DateTimeKind.Utc));
        }
		private TodoItemManager()
		{
			this.client = new MobileServiceClient(Constants.ApplicationURL);
			var store = new MobileServiceSQLiteStore("localstore.db");
			store.DefineTable<TodoItem>();
			this.client.SyncContext.InitializeAsync(store);
			this.todoTable = client.GetSyncTable<TodoItem>();
		}
        public AuthenticationService(IMobileServiceClient mobileService, Application application)
        {
            this.mobileService = mobileService;

            application.RegisterActivityLifecycleCallbacks(lifecycleHandler);

            lifecycleHandler.ActivityResumed += (s, e) => currentActivity = e.Activity;
        }
        public AptkAmaDataService(IAptkAmaPluginConfiguration configuration, IMobileServiceClient client)
        {
            Configuration = configuration;
            Client        = client;

            // Init tables
            Initialize();
        }
        /// <summary>
        /// Returns true when the authentication token for the current user is expired.
        /// </summary>
        /// <param name="client">The current MobileServiceClient instance</param>
        /// <param name="credential">PasswordCredential to check.</param>
        /// <returns>true when the token is expired; otherwise false.</returns>
        public static bool IsTokenExpired(this IMobileServiceClient client, PasswordCredential credential)
        {
            // Get the stored password.
            credential.RetrievePassword();

            // Check for expired token.
            return(CheckToken(credential.Password));
        }
Beispiel #29
0
 public static void Initialize(string appServiceUrl = AppServiceUrl)
 {
     if (!string.IsNullOrEmpty(appServiceUrl))
     {
         MobileServiceClient = new MobileServiceClient(appServiceUrl);
         IsInitialized       = true;
     }
 }
Beispiel #30
0
        public WritePostViewModel(IMobileServiceClient client, IUserService userService, ITimelineService timelineService)
        {
            this.client          = client;
            this.userService     = userService;
            this.timelineService = timelineService;

            this.CreateCommands();
        }
 public IMobileServiceClient GetMobileServicesClinet()
 {
     if (_client == null)
     {
         _client = new MobileServiceClient(Helpers.Constants.ClientAddress);
     }
     return(_client);
 }
Beispiel #32
0
 public AzureExpenseService(IMobileServiceClient client)
 {
     _client              = client;
     _expenseTable        = _client.GetTable <Expense>();
     _reportTable         = _client.GetTable <Report>();
     _expenseReceiptTable = _client.GetTable <ExpenseReceipt>();
     _categoryTable       = _client.GetTable <Category>();
 }
        /// <summary>
        /// Initialize Android plugin
        /// </summary>
        public static void Init(IAptkAmaPluginConfiguration configuration)
        {
#if __ANDROID__ || __IOS__
            CurrentPlatform.Init();
#endif
            _configuration = configuration;
            _client        = CreateMobileServiceClient();
        }
Beispiel #34
0
        public AzureClient()
        {
            _client =
                new
                MobileServiceClient("http://EderadoXamarinTest.azurewebsites.net");

            _table = _client.GetTable <Nota>();
        }
Beispiel #35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SqLiteRepository{TEntity, TIdentifier}"/> class.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <exception cref="System.ArgumentNullException">context</exception>
 public SqLiteRepository(IMobileServiceClient context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     this.DbContext = context;
 }
        //private IMobileServiceTable<TodoItem> todoTable = App.MobileService.GetTable<TodoItem>();

        public MainPageViewModel()
        {
            _mobileService  = new MobileServiceClient(
            "https://isvacceleratoreumar.azurewebsites.net",
            "https://default-web-eastus744386286bdd4ad5816e8100d15de451.azurewebsites.net",
            "");

            _todoTable = _mobileService.GetSyncTable<TodoItem>();
        }
Beispiel #37
0
        static MobileService()
        {
#if LOCAL_SERVICE
            Client = new MobileServiceClient("http://localhost:59988/", new LegacyUserIdHandler(), new AuthFailureHandler());
            Client.AlternateLoginHost = new Uri(MobileServiceUrl);
#else
            Client = new MobileServiceClient(MobileServiceUrl, new LegacyUserIdHandler(), new AuthFailureHandler());
#endif
        }
        public FileSyncTriggerFactory(IMobileServiceClient mobileServiceClient, bool autoUpdateParentRecords)
        {
            if (mobileServiceClient == null) {
                throw new ArgumentNullException("mobileServiceClient");
            }

            this.mobileServiceClient = mobileServiceClient;
            this.autoUpdateRecords = autoUpdateParentRecords;
        }
        public Task<MobileServiceUser> LoginAsync(IMobileServiceClient client, MobileServiceAuthenticationProvider provider, IDictionary<string, string> parameters = null)
        {
            try
            {
                return client.LoginAsync(Forms.Context, provider, parameters);
            }
            catch { }

            return null;
        }
        public async Task InitializeAsync()
        {
            this.MobileService = 
                new MobileServiceClient(MobileUrl, new LoggingHandler());

            var store = new MobileServiceSQLiteStore("local.db");
            store.DefineTable<Job>();

            await MobileService.SyncContext.InitializeAsync(store, StoreTrackingOptions.NotifyLocalAndServerOperations);
            jobTable = MobileService.GetSyncTable<Job>();
        }
        private async Task<StorageToken> GetStorageToken(IMobileServiceClient client, MobileServiceFile file, StoragePermissions permissions)
        {

            var tokenRequest = new StorageTokenRequest();
            tokenRequest.Permissions = permissions;
            tokenRequest.TargetFile = file;

            string route = string.Format("/tables/{0}/{1}/StorageToken", file.TableName, file.ParentId);

            return await this.client.InvokeApiAsync<StorageTokenRequest, StorageToken>(route, tokenRequest);
        }
Beispiel #42
0
 IMobileServiceClient CreateClient()
 {
     client = new MobileServiceClient(DefaultMobileServiceUrl, new AuthHandler())
     {
         SerializerSettings = new MobileServiceJsonSerializerSettings()
         {
             ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
             CamelCasePropertyNames = true
         }
     };
     return client;
 }
Beispiel #43
0
        public MainViewModel(NavigationService navigationService, IMobileServiceClient mobileServiceClient) : base(navigationService)
        {
            if (mobileServiceClient == null) throw new ArgumentNullException(nameof(mobileServiceClient));
            this._mobileServiceClient = mobileServiceClient;

            DigitalClock = new BasicDigitalClock();

            var dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Tick += dispatcherTimer_Tick;
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
            dispatcherTimer.Start();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MobileServiceAuthentication"/> class.
        /// </summary>
        /// <param name="client">
        /// The <see cref="MobileServiceClient"/> associated with this 
        /// MobileServiceLogin instance.
        /// </param>
        /// <param name="provider">
        /// The <see cref="MobileServiceAuthenticationProvider"/> used to authenticate.
        /// </param>
        public MobileServiceAuthentication(IMobileServiceClient client, MobileServiceAuthenticationProvider provider)
        {
            Debug.Assert(client != null, "client should not be null.");

            this.Client = client;
            this.Provider = provider;

            string providerName = this.Provider.ToString().ToLower();

            this.StartUri = new Uri(this.Client.ApplicationUri, MobileServiceAuthentication.LoginAsyncUriFragment + "/" + providerName);
            this.EndUri = new Uri(this.Client.ApplicationUri, MobileServiceAuthentication.LoginAsyncDoneUriFragment);
        }
        private async Task<HttpResponseMessage> ResendRequest(IMobileServiceClient client, HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Clone the request
            var clonedRequest = await CloneRequest(request);

            // Set the authentication header
            clonedRequest.Headers.Remove("X-ZUMO-AUTH");
            clonedRequest.Headers.Add("X-ZUMO-AUTH", client.CurrentUser.MobileServiceAuthenticationToken);

            // Resend the request
            return await base.SendAsync(clonedRequest, cancellationToken);
        }
Beispiel #46
0
        public async Task InitializeAsync()
        {
            this.MobileService = 
                new MobileServiceClient(MobileUrl, new LoggingHandler());

            var store = new MobileServiceSQLiteStore("local.db");
            store.DefineTable<Job>();

            await MobileService.SyncContext.InitializeAsync(store, StoreTrackingOptions.NotifyLocalAndServerOperations);
            jobTable = MobileService.GetSyncTable<Job>();

            // This sample doesn't do any authentication. To add it, see 
            // https://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-xamarin-forms-get-started-users/
        }
        public async Task InitializeAsync()
        {
            this.MobileService = AppService.CreateMobileServiceClient(
                MobileAppURL,
                "");
            // 3. initialize local store

            var store = new MobileServiceSQLiteStore("local-db-" + MobileAppName);
            store.DefineTable<Job>();

            await MobileService.SyncContext.InitializeAsync(store);

            jobTable = MobileService.GetSyncTable<Job>();
        }
        public async Task InitializeAsync()
        {
            this.MobileService = AppService.CreateMobileServiceClient(
                "https://fetechnician-code.azurewebsites.net/",
                "OtFsjAFDBBMENsPCBQFJmItwjvAfaX77");
            // 3. initialize local store

            var store = new MobileServiceSQLiteStore("local-db-fabrikam80");
            store.DefineTable<Job>();

            await MobileService.SyncContext.InitializeAsync(store);

            jobTable = MobileService.GetSyncTable<Job>();
        }
        public Task<MobileServiceUser> LoginAsync(IMobileServiceClient client, MobileServiceAuthenticationProvider provider, IDictionary<string, string> parameters = null)
        {
            try
            {

				return client.LoginAsync(GetController(), provider, parameters);
                
            }
            catch (Exception e)
            {
                e.Data["method"] = "LoginAsync";
            }

            return null;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MobileServiceAuthentication"/> class.
        /// </summary>
        /// <param name="client">
        /// The <see cref="MobileServiceClient"/> associated with this 
        /// MobileServiceLogin instance.
        /// </param>
        /// <param name="providerName">
        /// The <see cref="MobileServiceAuthenticationProvider"/> used to authenticate.
        /// </param>
        public MobileServiceAuthentication(IMobileServiceClient client, string providerName)
        {
            Debug.Assert(client != null, "client should not be null.");
            if (providerName == null)
            {
                throw new ArgumentNullException("providerName");
            }

            this.Client = client;

            this.ProviderName = providerName;

            this.StartUri = new Uri(this.Client.ApplicationUri, MobileServiceAuthentication.LoginAsyncUriFragment + "/" + this.ProviderName);
            this.EndUri = new Uri(this.Client.ApplicationUri, MobileServiceAuthentication.LoginAsyncDoneUriFragment);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="client"></param>
        public MainViewModel(IMobileServiceClient client, NetworkInformationDelegate networkDelegate)
        {
            this.client = client;
            this.networkDelegate = networkDelegate;

            this.todoTable = client.GetTable<TodoItem2>();

            this.RefreshCommand = new RelayCommand(this.RefreshTodoItems);
            this.SaveCommand = new RelayCommand(this.Save);
            this.CompletedCommand = new RelayCommand<TodoItem2>(x => this.Complete(x));
            this.RemoveCommand = new RelayCommand<TodoItem2>(x => this.Remove(x));

            this.Items = new ObservableCollection<TodoItem2>();

            //this.RefreshTodoItems();
        }
        internal Push(IMobileServiceClient client)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            MobileServiceClient internalClient = client as MobileServiceClient;
            if (internalClient == null)
            {
                throw new ArgumentException("Client must be a MobileServiceClient object");
            }

            this.PushHttpClient = new PushHttpClient(internalClient);
            this.Client = client;
        }
        public CustomFileSyncTrigger(IFileSyncContext fileSyncContext, IMobileServiceClient mobileServiceClient, bool autoUpdateParentRecords)
        {
            if (fileSyncContext == null) {
                throw new ArgumentNullException("fileSyncContext");
            }

            if (mobileServiceClient == null) {
                throw new ArgumentNullException("mobileServiceClient");
            }

            this.fileSyncContext = fileSyncContext;
            this.mobileServiceClient = mobileServiceClient;

            this.dataChangeNotificationSubscription = mobileServiceClient.EventManager.Subscribe<StoreOperationCompletedEvent>(OnStoreOperationCompleted);

            if (autoUpdateParentRecords) {
                this.fileChangeNotificationSubscription = mobileServiceClient.EventManager.Subscribe<FileOperationCompletedEvent>(OnFileOperationCompleted);
            }
        }
        public async Task<MobileServiceUser> LoginAsync(IMobileServiceClient client,
            MobileServiceAuthenticationProvider provider)
        {
            var coreWindow = Windows.ApplicationModel.Core.CoreApplication.MainView;
            // Dispatcher needed to run on UI Thread
            var dispatcher = coreWindow.CoreWindow.Dispatcher;

            MobileServiceUser user = null;


            try
            {
                if (dispatcher.HasThreadAccess)  //is running on UI thread
                {
                    user = await client.LoginAsync(provider);
                }
                else
                {
                    await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                    {
                        user = await client.LoginAsync(provider);

                    });
                }

                if (user != null)
                {
                    Settings.Current.AuthToken = user?.MobileServiceAuthenticationToken ?? string.Empty;
                    Settings.Current.AzureMobileUserId = user?.UserId ?? string.Empty;
                }

            }
            catch (Exception e)
            {
                if (!e.Message.Contains("cancelled"))
                {
                    e.Data["method"] = "LoginAsync";
                    Logger.Instance.Report(e);
                }
            }

            return user;
        }
Beispiel #55
0
        //returns info for the authenticated user
        public static async Task<UserProfile> GetUserProfileAsync(IMobileServiceClient client)
        {
            var userprof =
                await client.InvokeApiAsync<UserProfile>(
                    "UserInfo",
                    System.Net.Http.HttpMethod.Get,
                    null);

            Settings.Current.UserFirstName = userprof?.FirstName ?? string.Empty;
            Settings.Current.UserLastName = userprof?.LastName ?? string.Empty;
            Settings.Current.UserProfileUrl = userprof?.ProfilePictureUri ?? string.Empty;
            Settings.Current.UserUID = userprof?.UserId ?? string.Empty;

            if (string.IsNullOrWhiteSpace(userprof?.ProfilePictureUri))
            {
                Settings.Current.UserProfileUrl = "http://appstudio.windows.com/Content/img/temp/icon-user.png";
            }

            return userprof;
        }
		// Return username of currently logged in user
		public async Task<string> GetUsername(IMobileServiceClient client)
		{
			//Get user name
			var url = "https://demofieldengineernxevufbcegvsy.azurewebsites.net/.auth/me";
			HttpClient httpclient = new HttpClient();
			httpclient.DefaultRequestHeaders.Add("X-ZUMO-AUTH", client.CurrentUser.MobileServiceAuthenticationToken);

			HttpResponseMessage response = await httpclient.GetAsync (url);
			string content = await response.Content.ReadAsStringAsync();

			// get rid of {,},[,]
			content = content.Replace("{","").Replace("}","").Replace("[","").Replace("]","").Replace("\"","");

			// split with , and :
			String [] splitContent = content.Split(new Char[] { ',', ':'},
				StringSplitOptions.RemoveEmptyEntries).ToArray();

			// find "name" key
			int nameIndex = Array.IndexOf(splitContent, "name");
			// get "name" value
			return splitContent[(nameIndex+2)];
		}
Beispiel #57
0
        public async Task<MobileServiceUser> LoginAsync(IMobileServiceClient client,
            MobileServiceAuthenticationProvider provider)
        {
            try
            {
                Settings.Current.LoginAttempts++;
                var user = await client.LoginAsync(CrossCurrentActivity.Current.Activity, provider);
                Settings.Current.AuthToken = user?.MobileServiceAuthenticationToken ?? string.Empty;
                Settings.Current.AzureMobileUserId = user?.UserId ?? string.Empty;
                return user;
            }
            catch (Exception e)
            {
                if (!e.Message.Contains("cancelled"))
                {
                    e.Data["method"] = "LoginAsync";
                    Logger.Instance.Report(e);
                }
            }

            return null;
        }
        public AddUserDeviceViewModel(
			ILoggedInUserService loggedInUserService,
			IMobileServiceClient mobileServiceClient)
        {
            loggedInUserService.CheckIfNull("loggedInUserService");

            this.DeviceSelections = new ObservableCollection<string>();

            this.AddCommand = new MvxCommand(this.AddExecute, this.CanAdd);

            // setup key actions
            this.keyActions = new Dictionary<string, Action>
                           {
                               { UserDeviceSelections.Garmin, () => this.ShowViewModel<GarminViewModel>() },
                                     { UserDeviceSelections.Fitbit, () => this.ShowViewModel<FitbitViewModel>() },
                           };

            this.DeviceSelections = new ObservableCollection<string> {
                UserDeviceSelections.Garmin,
                UserDeviceSelections.Fitbit
            };
        }
Beispiel #59
0
        public async Task<MobileServiceUser> LoginAsync(IMobileServiceClient client,
            MobileServiceAuthenticationProvider provider)
        {
            try
            {
                var window = UIKit.UIApplication.SharedApplication.KeyWindow;
                var root = window.RootViewController;
                if (root != null)
                {
                    var current = root;
                    while (current.PresentedViewController != null)
                    {
                        current = current.PresentedViewController;
                    }


                    Settings.Current.LoginAttempts++;

                    var user = await client.LoginAsync(current, provider);

                    Settings.Current.AuthToken = user?.MobileServiceAuthenticationToken ?? string.Empty;
                    Settings.Current.AzureMobileUserId = user?.UserId ?? string.Empty;

                    return user;
                }
            }
            catch (Exception e)
            {
                if (!e.Message.Contains("cancelled"))
                {
                    e.Data["method"] = "LoginAsync";
                    Logger.Instance.Report(e);
                }
            }

            return null;
        }
 public NotificationsService(IMobileServiceClient mobileService)
 {
     this.mobileService = mobileService;
 }