public MobeelizerOperationError UnregisterForRemoteNotifications(string channelUri) { String token = this.tokenConverter.Convert(channelUri); WebRequest request = WebRequest.Create(GetUrl(String.Format("/unregisterPushToken?deviceToken={0}&deviceType=wp7", token))); request.Method = "POST"; SetHeaders(request, true, true); try { MobeelizerResponse result = new Synchronizer().GetResponse(request); if (result.StatusCode == HttpStatusCode.OK) { Log.i(TAG, "Unregistered for remote notifications with chanel: " + channelUri); return(null); } else if (result.StatusCode == HttpStatusCode.InternalServerError) { return(MobeelizerOperationError.ServerError((result as MobeelizerJsonResponse).Json)); } else { throw new IOException("Http connection status code: " + result.StatusCode.ToString()); } } catch (WebException e) { throw new IOException(e.Message, e); } }
public MobeelizerLoginResponse(MobeelizerOperationError error, string instanceGuid, string role, bool initSyncRequired) { this.Role = role; this.Error = error; this.InitialSyncRequired = initSyncRequired; this.InstanceGuid = instanceGuid; }
public IMobeelizerAuthenticateResponse Authenticate(string user, string password, String notificationChanelUri) { WebRequest request = WebRequest.Create(GetUrl("/authenticate?cache=" + Guid.NewGuid().ToString())); request.Method = "GET"; SetHeaders(request, false, false); request.Headers["mas-user-name"] = user; request.Headers["mas-user-password"] = password; try { MobeelizerResponse result = new Synchronizer().GetResponse(request); if (result.StatusCode == HttpStatusCode.OK) { JObject jObject = (result as MobeelizerJsonResponse).Json; return(new MobeelizerAuthenticateResponse((String)jObject["instanceGuid"], (String)jObject["role"])); } else if (result.StatusCode == HttpStatusCode.InternalServerError) { return(new MobeelizerAuthenticateResponse(MobeelizerOperationError.ServerError((result as MobeelizerJsonResponse).Json))); } else { throw new IOException("Http connection status code: " + result.StatusCode.ToString()); } } catch (WebException e) { return(new MobeelizerAuthenticateResponse(MobeelizerOperationError.ConnectionError(e.Message))); } catch (JsonException e) { return(new MobeelizerAuthenticateResponse(MobeelizerOperationError.Other(e.Message))); } }
internal void RegisterForRemoteNotifications(string chanelUri, MobeelizerOperationCallback callback) { Thread thread = new Thread(new ThreadStart(() => { MobeelizerOperationError error = null; try { NotificationChannelUri = chanelUri; if (IsLoggedIn) { error = connectionManager.RegisterForRemoteNotifications(chanelUri); } } catch (Exception e) { Log.i(TAG, e.Message); error = MobeelizerOperationError.Exception(e); } callback(error); })); thread.Name = "Register for notification thread"; thread.Start(); }
internal MobeelizerOperationError ProcessInputFile(Others.File inputFile, bool isAllSynchronization) { MobeelizerInputData inputData = null; try { inputData = new MobeelizerInputData(inputFile); application.GetFileService().AddFilesFromSync(inputData.GetFiles(), inputData); MobeelizerOperationError updateError = ((MobeelizerDatabase)application.GetDatabase()).UpdateEntitiesFromSync(inputData.GetInputData(), isAllSynchronization); if (updateError != null) { return(updateError); } application.GetFileService().DeleteFilesFromSync(inputData.GetDeletedFiles()); return(null); } catch (IOException e) { throw new InvalidOperationException(e.Message, e); } finally { if (inputData != null) { inputData.Close(); } } }
public MobeelizerOperationError SendRemoteNotification(string device, string group, System.Collections.Generic.IList <string> users, System.Collections.Generic.IDictionary <string, string> notification) { JObject jobject = new JObject(); StringBuilder logBuilder = new StringBuilder(); logBuilder.Append("Sent remote notification ").Append(notification).Append(" to"); if (device != null) { jobject.Add("device", device); logBuilder.Append(" device: ").Append(device); } if (group != null) { jobject.Add("group", group); logBuilder.Append(" group: ").Append(group); } if (users != null) { jobject.Add("users", new JArray(users)); logBuilder.Append(" users: ").Append(users); } if (device == null && group == null && users == null) { logBuilder.Append(" everyone"); } JObject jnotification = new JObject(); foreach (var notify in notification) { jnotification.Add(notify.Key, notify.Value); } jobject.Add("notification", jnotification); WebRequest request = WebRequest.Create(GetUrl("/push")); request.Method = "POST"; using (Stream stream = new Synchronizer().GetRequestStream(request)) { byte[] notificationMessage = Encoding.UTF8.GetBytes(jobject.ToString()); stream.Write(notificationMessage, 0, notificationMessage.Length); } SetHeaders(request, true, true); MobeelizerResponse result = new Synchronizer().GetResponse(request); if (result.StatusCode == HttpStatusCode.OK) { Log.i(TAG, logBuilder.ToString()); return(null); } else if (result.StatusCode == HttpStatusCode.InternalServerError) { return(MobeelizerOperationError.ServerError((result as MobeelizerJsonResponse).Json)); } else { throw new IOException("Http connection status code: " + result.StatusCode.ToString()); } }
public MobeelizerSyncResponse SendSyncAllRequest() { WebRequest request = WebRequest.Create(GetUrl("/synchronizeAll")); request.Method = "POST"; SetHeaders(request, true, true); try { MobeelizerResponse response = new Synchronizer().GetResponse(request); if (response.StatusCode == HttpStatusCode.OK) { return(new MobeelizerSyncResponse((response as MobeelizerTicketResponse).Ticket)); } else if (response.StatusCode == HttpStatusCode.InternalServerError) { return(new MobeelizerSyncResponse(MobeelizerOperationError.ServerError((response as MobeelizerJsonResponse).Json))); } else { throw new IOException("Http connection status code: " + response.StatusCode.ToString()); } } catch (NullReferenceException) { throw new IOException("Server not respond."); } }
public void Login_02() { MobeelizerOperationError loginStatus = null; Mobeelizer.Login("user", "passsssword", (s) => { loginStatus = s; login_02Event.Set(); }); login_02Event.WaitOne(); Assert.IsNotNull(loginStatus); }
public void Login() { UTWebRequest.SyncData = "firstSync.zip"; MobeelizerOperationError loginStatus = null; Mobeelizer.Login("user", "password", (s) => { loginStatus = s; loginEvent.Set(); }); loginEvent.WaitOne(); Assert.IsNull(loginStatus); }
public MobeelizerGetSyncDataOperationResult GetSyncData(string ticket) { WebRequest request = WebRequest.Create(GetUrl(String.Format("/data?ticket={0}", ticket))); request.Method = "GET"; SetHeaders(request, false, true); try { Others.File inputFile = GetInputFileStream(); inputFile.Create(); MobeelizerResponse response = new Synchronizer().GetResponseData(request); if (response.StatusCode == HttpStatusCode.OK) { using (Stream stream = (response as MobeelizerDataResponse).Data) { using (IsolatedStorageFileStream inputStream = inputFile.OpenToWrite()) { stream.CopyTo(inputStream); } } return(new MobeelizerGetSyncDataOperationResult(inputFile)); } else if (response.StatusCode == HttpStatusCode.InternalServerError) { return(new MobeelizerGetSyncDataOperationResult(MobeelizerOperationError.ServerError((response as MobeelizerJsonResponse).Json))); } else { throw new IOException("Http connection status code: " + response.StatusCode.ToString()); } } catch (WebException e) { String message; using (Stream stream = e.Response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream)) { message = reader.ReadToEnd(); } } throw new IOException(message, e); } catch (NullReferenceException) { throw new IOException("Server not respond."); } }
public MobeelizerSyncResponse SendSyncDiffRequest(Others.File outputFile) { String boundary = DateTime.Now.Ticks.ToString(); WebRequest request = WebRequest.Create(GetUrl("/synchronize")); request.Method = "POST"; request.ContentType = String.Format("multipart/form-data; boundary={0}", boundary); using (Stream requestStream = new Synchronizer().GetRequestStream(request)) { String header = String.Format("--{0}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"file\";\r\nContent-Type: application/octet-stream\r\n\r\n", boundary); requestStream.Write(Encoding.UTF8.GetBytes(header), 0, header.Length); using (IsolatedStorageFileStream stream = outputFile.OpenToRead()) { int lenght = (int)stream.Length; byte[] bytes = new byte[lenght]; stream.Read(bytes, 0, lenght); requestStream.Write(bytes, 0, lenght); } string footer = "\r\n--" + boundary + "--\r\n"; byte[] footerbytes = Encoding.UTF8.GetBytes(footer); requestStream.Write(footerbytes, 0, footerbytes.Length); } SetHeaders(request, false, true); try { MobeelizerResponse response = new Synchronizer().GetResponse(request); if (response.StatusCode == HttpStatusCode.OK) { return(new MobeelizerSyncResponse((response as MobeelizerTicketResponse).Ticket)); } else if (response.StatusCode == HttpStatusCode.InternalServerError) { return(new MobeelizerSyncResponse(MobeelizerOperationError.ServerError((response as MobeelizerJsonResponse).Json))); } else { throw new IOException("Http connection status code: " + response.StatusCode.ToString()); } } catch (NullReferenceException) { throw new IOException("Server not respond."); } }
private void UserSwitched(object arg) { MobeelizerOperationError error = (MobeelizerOperationError)arg; if (error == null) { this.IsBusy = false; } else if (error.Code == "missingConnection") { navigationService.ShowMessage(Resources.Errors.e_title, Resources.Errors.e_missingConnection); } else { navigationService.ShowMessage(Resources.Errors.e_title, Resources.Errors.e_cannotConnectToSession); } }
public void SyncAll() { UTWebRequest.SyncData = "firstSync.zip"; Mobeelizer.Login("user", "password", (s) => { syncAllLoginEvent.Set(); }); syncAllLoginEvent.WaitOne(); String justAddEntityGuid = string.Empty; using (IMobeelizerTransaction db = Mobeelizer.GetDatabase().BeginTransaction()) { var departmentTable = db.GetModelSet <Department>(); Department de = new Department(); de.InternalNumber = 1; de.Name = "ddd"; departmentTable.InsertOnSubmit(de); db.SubmitChanges(); justAddEntityGuid = de.Guid; } MobeelizerOperationError status = null; Mobeelizer.SyncAll((s) => { status = s; this.syncAllEvent.Set(); }); syncAllEvent.WaitOne(); Assert.IsNull(status); Department foundObject = null; using (IMobeelizerTransaction db = Mobeelizer.GetDatabase().BeginTransaction()) { var departmentTable = db.GetModelSet <Department>(); var query = from d in departmentTable where d.Guid == justAddEntityGuid select d; try { foundObject = query.Single(); } catch { } Assert.IsNull(foundObject); Assert.AreEqual(1, departmentTable.Count()); } }
private MobeelizerOperationError Sync(bool syncAll) { if (mode == MobeelizerMode.DEVELOPMENT || CheckSyncStatus().IsRunning()) { Log.i(TAG, "Sync is already running - skipping."); return(null); } else if (!connectionManager.IsNetworkAvailable) { Log.i(TAG, "Sync cannot be performed - network is not available."); SetSyncStatus(MobeelizerSyncStatus.FINISHED_WITH_FAILURE); return(MobeelizerOperationError.MissingConnectionError()); } else { SetSyncStatus(MobeelizerSyncStatus.STARTED); return(new MobeelizerSyncServicePerformer(Mobeelizer.Instance, syncAll).Sync()); } }
internal void SyncAll(MobeelizerOperationCallback callback) { Thread thread = new Thread(new ThreadStart(() => { try { callback(SyncAll()); } catch (Exception e) { Log.i(TAG, e.Message); this.SetSyncStatus(MobeelizerSyncStatus.FINISHED_WITH_FAILURE); callback(MobeelizerOperationError.Exception(e)); } })); thread.Name = "Mobeelizer full synchronization thread"; thread.Start(); }
public MobeelizerOperationError WaitUntilSyncRequestComplete(string ticket) { MobeelizerSynchronizationStatus sycStatus = MobeelizerSynchronizationStatus.REJECTED; for (int i = 0; i < 240; i++) { WebRequest request = WebRequest.Create(GetUrl(String.Format("/checkStatus?ticket={0}&aaa={1}", ticket, DateTime.Now.Ticks))); request.Method = "GET"; SetHeaders(request, false, true); MobeelizerResponse result = new Synchronizer().GetResponse(request); if (result.StatusCode == HttpStatusCode.OK) { String strSyncStatus = (String)(result as MobeelizerJsonResponse).Json["status"]; sycStatus = (MobeelizerSynchronizationStatus)Enum.Parse(typeof(MobeelizerSynchronizationStatus), strSyncStatus, true); } else { throw new IOException(result.StatusCode.ToString() + ": " + (result as MobeelizerJsonResponse).Json.ToString()); } if (sycStatus == MobeelizerSynchronizationStatus.REJECTED || sycStatus == MobeelizerSynchronizationStatus.CONFIRMED) { return(MobeelizerOperationError.SyncRejected((String)(result as MobeelizerJsonResponse).Json["message"], (String)(result as MobeelizerJsonResponse).Json["result"])); } else if (sycStatus == MobeelizerSynchronizationStatus.FINISHED) { return(null); } try { Thread.Sleep(100 * i + 500); } catch (Exception e) { throw new IOException(e.Message, e); } } return(MobeelizerOperationError.Other("Sync timeout."));; }
internal void Sync(MobeelizerOperationCallback callback) { Thread thread = new Thread(new ThreadStart(() => { MobeelizerOperationError error = null; try { error = Sync(); } catch (Exception e) { Log.i(TAG, e.Message); this.SetSyncStatus(MobeelizerSyncStatus.FINISHED_WITH_FAILURE); error = MobeelizerOperationError.Exception(e); } callback(error); })); thread.Name = "Mobeelizer synchronization thread"; thread.Start(); }
internal void Login(string instance, string user, string password, MobeelizerOperationCallback callback) { Thread thread = new Thread(new ThreadStart(() => { MobeelizerOperationError error = null; try { error = Login(instance, user, password, false); } catch (Exception e) { Log.i(TAG, e.Message); error = MobeelizerOperationError.Exception(e); } callback(error); })); thread.Name = "Mobeelizer login thread"; thread.Start(); }
private void UserSwitched(object arg) { MobeelizerOperationError error = (MobeelizerOperationError)arg; if (error == null) { this.IsBusy = false; Deployment.Current.Dispatcher.BeginInvoke(new Action(() => { this.RefreshEntitiesList(); })); } else if (error.Code == "missingConnection") { navigationService.ShowMessage(Resources.Errors.e_title, Resources.Errors.e_missingConnection); } else { navigationService.ShowMessage(Resources.Errors.e_title, Resources.Errors.e_cannotConnectToSession); } }
internal void SendRemoteNotification(String device, String group, IList <String> users, IDictionary <String, String> notification, MobeelizerOperationCallback callback) { Thread thread = new Thread(new ThreadStart(() => { MobeelizerOperationError error; try { CheckIfLoggedIn(); error = connectionManager.SendRemoteNotification(device, group, users, notification); } catch (Exception e) { Log.i(TAG, e.Message); error = MobeelizerOperationError.Exception(e); } callback(error); })); thread.Name = "Send notification thread"; thread.Start(); }
internal void UnregisterForRemoteNotifications(MobeelizerOperationCallback callback) { Thread thread = new Thread(new ThreadStart(() => { MobeelizerOperationError error = null; try { CheckIfLoggedIn(); error = connectionManager.UnregisterForRemoteNotifications(NotificationChannelUri); } catch (Exception e) { Log.i(TAG, e.Message); error = MobeelizerOperationError.Exception(e); } callback(error); })); thread.Name = "Register for notification thread"; thread.Start(); }
internal MobeelizerOperationError UpdateEntitiesFromSync(IEnumerable <MobeelizerJsonEntity> entities, bool isAllSynchronization) { MobeelizerOperationError transactionErrors = null; using (MobeelizerDatabaseContext dataContext = new MobeelizerDatabaseContext(this.ConnectionString)) { if (isAllSynchronization) { foreach (var model in models.Values) { var table = dataContext.GetTable(model.Type); table.DeleteAllOnSubmit(from MobeelizerWp7Model record in table select record); } dataContext.ModelMetadata.DeleteAllOnSubmit(from m in dataContext.ModelMetadata select m); // TODO: check it //dataContext.Files.DeleteAllOnSubmit(from f in dataContext.Files select f); dataContext.SubmitChanges(); } foreach (MobeelizerJsonEntity entity in entities) { transactionErrors = models[entity.Model].UpdateFromSync(entity, dataContext); if (transactionErrors != null) { break; } } if (transactionErrors == null) { dataContext.SubmitChanges(); } } return(transactionErrors); }
internal MobeelizerOperationError Sync() { if (application.CheckSyncStatus() != MobeelizerSyncStatus.STARTED) { Log.i(TAG, "Send is already running - skipping."); return(null); } MobeelizerDatabase database = (MobeelizerDatabase)application.GetDatabase(); IMobeelizerConnectionManager connectionManager = application.GetConnectionManager(); String ticket = String.Empty; bool success = false; Others.File outputFile = null; Others.File inputFile = null; try { database.LockModifiedFlag(); if (isAllSynchronization) { Log.i(TAG, "Send sync all request."); MobeelizerSyncResponse response = connectionManager.SendSyncAllRequest(); if (response.Error == null) { ticket = response.Ticket; } else { return(response.Error); } } else { outputFile = GetOuptutFile(); outputFile.Create(); MobeelizerOperationError prepareFileError = dataFileService.PrepareOutputFile(outputFile); if (prepareFileError != null) { Log.i(TAG, "Send file haven't been created."); return(prepareFileError); } else { ChangeStatus(MobeelizerSyncStatus.FILE_CREATED, ticket); Log.i(TAG, "Send sync request."); MobeelizerSyncResponse response = connectionManager.SendSyncDiffRequest(outputFile); if (response.Error == null) { ticket = response.Ticket; } else { return(response.Error); } } } Log.i(TAG, "Sync request completed: " + ticket + "."); ChangeStatus(MobeelizerSyncStatus.TASK_CREATED, ticket); MobeelizerOperationError waitError = connectionManager.WaitUntilSyncRequestComplete(ticket); if (waitError != null) { return(waitError); } else { Log.i(TAG, "Sync process complete with success."); ChangeStatus(MobeelizerSyncStatus.TASK_PERFORMED, ticket); MobeelizerGetSyncDataOperationResult getDataResult = connectionManager.GetSyncData(ticket); if (getDataResult.Error == null) { inputFile = getDataResult.InputFile; } else { return(getDataResult.Error); } ChangeStatus(MobeelizerSyncStatus.FILE_RECEIVED, ticket); MobeelizerOperationError processError = dataFileService.ProcessInputFile(inputFile, isAllSynchronization); if (processError != null) { return(processError); } else { success = true; } connectionManager.ConfirmTask(ticket); database.ClearModifiedFlag(); application.InternalDatabase.SetInitialSyncAsNotRequired(application.Instance, application.User); } } catch (IOException e) { Log.i(TAG, e.Message); return(MobeelizerOperationError.Exception(e)); } catch (InvalidOperationException e) { Log.i(TAG, e.Message); return(MobeelizerOperationError.Exception(e)); } finally { if (inputFile != null) { inputFile.Delete(); } if (outputFile != null) { outputFile.Delete(); } database.UnlockModifiedFlag(); if (success) { ChangeStatus(MobeelizerSyncStatus.FINISHED_WITH_SUCCESS, ticket); } else { Log.i(TAG, "Sync process complete with failure."); ChangeStatus(MobeelizerSyncStatus.FINISHED_WITH_FAILURE, ticket); } } return(success ? null : MobeelizerOperationError.Other("Sync process complete with failure.")); }
internal MobeelizerOperationError UpdateFromSync(MobeelizerJsonEntity entity, MobeelizerDatabaseContext db) { var query = from MobeelizerWp7Model e in db.GetTable(this.Type) join MobeelizerModelMetadata m in db.ModelMetadata on e.Guid equals m.Guid where m.Guid == entity.Guid && m.Model == this.Name select new QueryResult() { Entity = e, Metadata = m }; bool exists = true; QueryResult result = null; if (query.Count() == 0) { exists = false; } else { result = query.Single(); } bool modifiedByUser = exists && result.Metadata.ModificationLock == false && result.Entity.Modified; if (modifiedByUser || !exists && entity.IsDeleted) { return(null); } if (entity.ConflictState == MobeelizerJsonEntity.MobeelizerConflictState.NO_IN_CONFLICT && entity.IsDeleted) { if (exists) { var table = db.GetTable(this.Type); table.DeleteAllOnSubmit(from MobeelizerWp7Model record in table where record.Guid == entity.Guid select record); } return(null); } Dictionary <String, object> values = new Dictionary <string, object>(); if (entity.ConflictState == MobeelizerJsonEntity.MobeelizerConflictState.IN_CONFLICT_BECAUSE_OF_YOU || entity.Fields.Count == 0) { PropertyInfo property = this.Type.GetProperty("Conflicted"); PropertyInfo modifiedProperty = this.Type.GetProperty("Modified"); property.SetValue(result.Entity, true, null); modifiedProperty.SetValue(result.Entity, false, null); return(null); } else if (entity.ConflictState == MobeelizerJsonEntity.MobeelizerConflictState.IN_CONFLICT) { values.Add("Conflicted", 1); } else { values.Add("Conflicted", 0); } values.Add("Owner", entity.Owner); values.Add("Modified", 0); try { values.Add("Deleted", entity.IsDeleted ? 1 : 0); } catch (KeyNotFoundException) { values.Add("Deleted", false); } MobeelizerErrorsHolder errors = new MobeelizerErrorsHolder(); foreach (MobeelizerField field in this.Fields) { field.SetValueFromMapToDatabase(values, entity.Fields, errors); } if (!errors.IsValid) { return(MobeelizerOperationError.UpdateFromSyncError(errors)); } if (exists) { UpdateEntity(db, result.Metadata, values, entity.Guid, result.Entity); } else { values.Add("Guid", entity.Guid); InsertEntity(db, values); } return(null); }
public MobeelizerLoginResponse(MobeelizerOperationError error) { this.Error = error; }
internal MobeelizerSyncResponse(MobeelizerOperationError error) { this.Error = error; }
internal MobeelizerGetSyncDataOperationResult(MobeelizerOperationError error) { this.Error = error; }
internal MobeelizerAuthenticateResponse(MobeelizerOperationError error) { this.Error = error; }
public MobeelizerLoginResponse Login(bool offline) { bool networkConnected = IsNetworkAvailable; if (!networkConnected || offline) { String[] roleAndInstanceGuid = GetRoleAndInstanceGuidFromDatabase(application); if (roleAndInstanceGuid[0] == null) { Log.i(TAG, "Login failure. Missing connection failure."); return(new MobeelizerLoginResponse(MobeelizerOperationError.MissingConnectionError())); } else { Log.i(TAG, "Login '" + application.User + "' from database successful."); return(new MobeelizerLoginResponse(null, roleAndInstanceGuid[1], roleAndInstanceGuid[0], false)); } } try { IMobeelizerAuthenticateResponse response = null; if (application.NotificationChannelUri != null) { response = connectionService.Authenticate(application.User, application.Password, application.NotificationChannelUri); } else { response = connectionService.Authenticate(application.User, application.Password); } if (response.Error == null) { bool initialSyncRequired = IsInitialSyncRequired(application, response.InstanceGuid); SetRoleAndInstanceGuidInDatabase(application, response.Role, response.InstanceGuid); Log.i(TAG, "Login '" + application.User + "' successful."); return(new MobeelizerLoginResponse(null, response.InstanceGuid, response.Role, initialSyncRequired)); } else { Log.i(TAG, "Login failure. Authentication error."); ClearRoleAndInstanceGuidInDatabase(application); return(new MobeelizerLoginResponse(response.Error)); } } catch (InvalidOperationException e) { Log.i(TAG, e.Message); String[] roleAndInstanceGuid = GetRoleAndInstanceGuidFromDatabase(application); if (roleAndInstanceGuid[0] == null) { return(new MobeelizerLoginResponse(MobeelizerOperationError.ConnectionError(e.Message))); } else { return(new MobeelizerLoginResponse(null, roleAndInstanceGuid[1], roleAndInstanceGuid[0], false)); } } }