Exemple #1
0
 public string OpenTextFile(string name)
 {
     try
     {
         IIOContext io   = IOContext.Current;
         string     path = io.TranslateLocalPath(name);
         if (io.Exists(path, FileSystemItem.File))
         {
             using (var stream = io.FileStream(path, FileMode.Open))
                 using (var reader = new StreamReader(stream))
                     return(reader.ReadToEnd());
         }
         throw new NonFatalException(D.FILE_NOT_EXISTS + ": " + name);
     }
     catch (CustomException e)
     {
         throw ClientException(e.FriendlyMessage);
     }
     catch (ArgumentException)
     {
         throw ClientException(D.INVALID_PATH + ": " + name);
     }
     catch (Exception e)
     {
         HandleException(e, "Dir");
         throw ClientException(D.UNEXPECTED_ERROR_OCCURED);
     }
 }
Exemple #2
0
        private void ReadFsLog()
        {
            SuccessSync  = false;
            LastSyncTime = default(DateTime);

            IIOContext io = IOContext.Current;

            string path = Path.Combine(_io.LocalStorage, FsLog);

            if (io.Exists(path))
            {
                using (var stream = io.FileStream(path, FileMode.Open))
                    using (var reader = new StreamReader(stream))
                    {
                        string   str   = reader.ReadToEnd();
                        string[] split = str.Split('#');
                        try
                        {
                            LastSyncTime = DateTime.Parse(split[0]);
                            SuccessSync  = bool.Parse(split[1]);
                        }
                        // ReSharper disable once EmptyGeneralCatchClause
                        catch { }
                    }
            }
        }
Exemple #3
0
 public void CreateTextFile(string name, string text)
 {
     try
     {
         IIOContext io   = IOContext.Current;
         string     path = io.TranslateLocalPath(name);
         if (!io.Exists(path))
         {
             string dir = Path.GetDirectoryName(path);
             io.CreateDirectory(dir);
             using (var stream = io.FileStream(path, FileMode.CreateNew))
                 using (var writer = new StreamWriter(stream))
                     writer.Write(text);
         }
         else
         {
             throw new NonFatalException(D.FILE_ALREADY_EXISTS + ": " + name);
         }
     }
     catch (CustomException e)
     {
         throw ClientException(e.FriendlyMessage);
     }
     catch (ArgumentException)
     {
         throw ClientException(D.INVALID_PATH + ": " + name);
     }
     catch (Exception e)
     {
         HandleException(e, "Dir");
         throw ClientException(D.UNEXPECTED_ERROR_OCCURED);
     }
 }
Exemple #4
0
        private DateTime ReadSyncTime()
        {
            IIOContext io   = IOContext.Current;
            string     path = Path.Combine(_io.LocalStorage, SyncTimePrivate);

            if (io.Exists(path))
            {
                using (var stream = io.FileStream(path, FileMode.Open))
                    using (var reader = new StreamReader(stream))
                    {
                        string   text = reader.ReadToEnd();
                        DateTime result;
                        if (DateTime.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
                        {
                            return(result);
                        }
                    }
            }
            return(DateTime.MinValue);
        }
Exemple #5
0
        void OnDownloadCompleted(object sender, NSUrlEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    _filePath = e.FilePath.Replace("file://", "").Replace("%20", " ");

                    NSHttpUrlResponse response = (NSHttpUrlResponse)_currentTask.Response;
                    if (response != null)
                    {
                        HttpStatusCode code = (HttpStatusCode)response.StatusCode;
                        if (code == HttpStatusCode.OK)
                        {
                            NSDictionary headers = response.AllHeaderFields;
                            if (string.IsNullOrWhiteSpace(_behaviors.UserId))
                            {
                                _behaviors.UserId = headers["userid"].ToString();
                            }
                            if (string.IsNullOrWhiteSpace(_behaviors.UserEmail))
                            {
                                _behaviors.UserEmail = headers["email"].ToString();
                            }
                            _behaviors.ResourceVersion = headers["resourceversion"].ToString();

                            _behaviors.SaveUserSession();

                            IIOContext io = IOContext.Current;
                            if (io.Exists(_filePath))
                            {
                                FileStream fileStream = io.FileStream(_filePath, FileMode.Open);

                                fileStream.Seek(0, SeekOrigin.Begin);
                                int contentLength;
                                if (!int.TryParse(headers["unzippedcontentlength"].ToString(), out contentLength))
                                {
                                    contentLength = -1;
                                }
                                Stream responseStream = new ProgressStream(fileStream, contentLength, _behaviors.ReadProgressCallback);

                                // CreateInstance the SyncReader
                                if (ApplicationContext.Current.Settings.BitMobileFormatterDisabled)
                                {
                                    _syncReader = new ODataAtomReader(responseStream, _knownTypes);
                                }
                                else
                                {
                                    _syncReader = new BMReader(responseStream, _knownTypes);
                                }

                                _wrapper.DownloadResponse      = new ChangeSet();
                                _wrapper.DownloadResponse.Data = GetDownloadedValues(_wrapper);
                            }
                            else
                            {
                                _wrapper.Error = new FileNotFoundException(String.Format("Downloaded data file not found! {0}, Description: {1}", e.FilePath, response.Description));
                            }
                        }
                        else
                        {
                            _wrapper.Error = new CacheControllerWebException(string.Format("Remote service returned error status. Status: {0}, Description: {1}", code, response.Description), code);
                        }
                    }
                    else
                    {
                        _wrapper.Error = new CacheControllerException("Response is null");
                    }
                }
                else
                {
                    var response = _currentTask.Response as NSHttpUrlResponse;
                    HandleError(e.Error, response);
                }

                // If we get here then it means we completed the request. Return to the original caller
                _workerManager.CompleteWorkRequest(_wrapper.WorkerRequest, _wrapper);
            }
            catch (Exception ex)
            {
                if (ExceptionUtility.IsFatal(ex))
                {
                    throw;
                }

                _wrapper.Error = ex;

                _workerManager.CompleteWorkRequest(_wrapper.WorkerRequest, _wrapper);
            }
        }
Exemple #6
0
        void OnUploadCompleted(object sender, NSUrlEventArgs e)
        {
            _wrapper.UploadResponse = new ChangeSetResponse();

            FileStream fileStream = null;

            string filePath = null;

            try
            {
                if (e.Error == null)
                {
                    string responseDescription = "response is  null";
                    var    response            = (NSHttpUrlResponse)_currentTask.Response;
                    if (response != null)
                    {
                        responseDescription = response.Description;
                    }

                    filePath = e.FilePath.Replace("file://", "").Replace("%20", " ");
                    IIOContext io = IOContext.Current;
                    if (io.Exists(filePath))
                    {
                        fileStream = io.FileStream(filePath, FileMode.Open);
                        fileStream.Seek(0, SeekOrigin.Begin);

                        // CreateInstance the SyncReader
                        if (ApplicationContext.Current.Settings.BitMobileFormatterDisabled)
                        {
                            _syncReader = new ODataAtomReader(fileStream, _knownTypes);
                        }
                        else
                        {
                            _syncReader = new BMReader(fileStream, _knownTypes);
                        }

                        // Read the response
                        while (_syncReader.Next())
                        {
                            switch (_syncReader.ItemType)
                            {
                            case ReaderItemType.Entry:
                                IOfflineEntity entity      = _syncReader.GetItem();
                                IOfflineEntity ackedEntity = entity;
                                string         tempId      = null;

                                if (_syncReader.HasTempId() && _syncReader.HasConflictTempId())
                                {
                                    throw new CacheControllerException(string.Format("Service returned a TempId '{0}' in both live and conflicting entities.",
                                                                                     _syncReader.GetTempId()));
                                }

                                if (_syncReader.HasTempId())
                                {
                                    tempId = _syncReader.GetTempId();
                                    CheckEntityServiceMetadataAndTempIds(entity, tempId);
                                }

                                if (_syncReader.HasConflict())
                                {
                                    Conflict       conflict       = _syncReader.GetConflict();
                                    IOfflineEntity conflictEntity = (conflict is SyncConflict) ?
                                                                    ((SyncConflict)conflict).LosingEntity : ((SyncError)conflict).ErrorEntity;

                                    if (_syncReader.HasConflictTempId())
                                    {
                                        tempId = _syncReader.GetConflictTempId();
                                        CheckEntityServiceMetadataAndTempIds(conflictEntity, tempId);
                                    }

                                    _wrapper.UploadResponse.AddConflict(conflict);

                                    if (_syncReader.HasConflictTempId() && entity.ServiceMetadata.IsTombstone)
                                    {
                                        conflictEntity.ServiceMetadata.IsTombstone = true;
                                        ackedEntity = conflictEntity;
                                    }
                                }

                                if (!String.IsNullOrEmpty(tempId))
                                {
                                    _wrapper.UploadResponse.AddUpdatedItem(ackedEntity);
                                }

                                break;

                            case ReaderItemType.SyncBlob:
                                _wrapper.UploadResponse.ServerBlob = _syncReader.GetServerBlob();
                                break;
                            }
                        }
                    }
                    else
                    {
                        _wrapper.Error = new FileNotFoundException(String.Format("Downloaded data file not found! {0}, Description: {1}", e.FilePath, responseDescription));
                    }
                }
                else
                {
                    var response = _currentTask.Response as NSHttpUrlResponse;
                    HandleError(e.Error, response);
                }

                _workerManager.CompleteWorkRequest(_wrapper.WorkerRequest, _wrapper);
            }
            catch (Exception ex)
            {
                if (ExceptionUtility.IsFatal(ex))
                {
                    throw;
                }

                _wrapper.Error = ex;

                _workerManager.CompleteWorkRequest(_wrapper.WorkerRequest, _wrapper);
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }

                if (filePath != null)
                {
                    IOContext.Current.Delete(filePath);
                }
            }
        }
        private bool CopyImageFromGallery(Intent data, string destPath, int size)
        {
            Bitmap bitmap = null;

            try
            {
                string sourcePath;
                if (TryGetPath(data, out sourcePath))
                {
                    if (size == 0)
                    {
                        string dir = Path.GetDirectoryName(destPath);
                        if (dir != null && !Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }
                        File.Copy(sourcePath, destPath);
                        return(true);
                    }
                    bitmap = Helper.LoadBitmap(sourcePath, size, size, false);
                }
                else if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
                {
                    Uri uri = data.Data;
                    Activity.ContentResolver.TakePersistableUriPermission(uri
                                                                          , data.Flags & (ActivityFlags.GrantReadUriPermission | ActivityFlags.GrantWriteUriPermission));
                    //var stream = Activity.ContentResolver.OpenInputStream(uri);
                    bitmap = Helper.LoadBitmap(() => Activity.ContentResolver.OpenInputStream(uri), size, size);
                }
                else
                {
                    throw new NotImplementedException("Unexpected behavior");
                }


                IIOContext io      = IOContext.Current;
                string     dirPath = Path.GetDirectoryName(destPath);
                if (dirPath != null)
                {
                    io.CreateDirectory(dirPath);
                }

                using (var stream = io.FileStream(destPath, FileMode.Create))
                    bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);


                return(true);
            }
            catch (Exception e)
            {
                BitBrowserApp.Current.ExceptionHandler.HandleNonFatal(e);
                return(false);
            }
            finally
            {
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
            }
        }