public bool Exists(string name) { bool result; try { IIOContext io = IOContext.Current; string path = io.TranslateLocalPath(name); result = io.Exists(path); } catch (CustomException e) { throw ClientException(e.FriendlyMessage); } catch (ArgumentException) { throw ClientException(D.INVALID_PATH + ": " + name); } catch (Exception e) { HandleException(e, "Exists"); throw ClientException(D.UNEXPECTED_ERROR_OCCURED); } return(result); }
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); } }
public void Copy(string from, string to) { try { IIOContext io = IOContext.Current; string source = io.TranslateLocalPath(from); string dest = io.TranslateLocalPath(to); if (!io.Exists(source)) { throw new NonFatalException(D.FILE_NOT_EXISTS + ": " + from); } if (io.Exists(dest)) { throw new NonFatalException(D.FILE_ALREADY_EXISTS + ": " + to); } io.Copy(source, dest); } catch (CustomException e) { throw ClientException(e.FriendlyMessage); } catch (ArgumentException) { throw ClientException(D.INVALID_PATH + ": " + from + "; " + to); } catch (Exception e) { HandleException(e, "Exists"); throw ClientException(D.UNEXPECTED_ERROR_OCCURED); } }
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 { } } } }
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); } }
//--------------------------- Fecha o disco e destrava o Contexto public void Close() { //Se o contexto não estava trancado, o contexto deve ser fechado pela rotina que o criou if (!isfileopen) { file.Unlock(); } file = null; TempBuffer = null; TempBuffer2 = null; SectorUsageTable = null; HeaderCopy = null; DiscKey = null; if (Partitions != null) { for (int i = 0; i < Partitions.Length; i++) { Partitions[i].Files = null; } } Partitions = null; }
private IEnumerable <string> Dir(string name, bool dirFilesNotFolders) { try { IIOContext io = IOContext.Current; string path = io.TranslateLocalPath(name); if (io.Exists(path)) { IEnumerable <string> result = dirFilesNotFolders ? Directory.EnumerateFiles(path) : Directory.EnumerateDirectories(path); return(result.Select(Path.GetFileName)); } throw new NonFatalException(D.DIRECTORY_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); } }
public bool Delete(string name) { if (name.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries).Length == 1) { throw ClientException(D.UNABE_TO_DELETE_SYSTEM_DIRECTORY); } try { IIOContext io = IOContext.Current; string path = io.TranslateLocalPath(name); return(io.Delete(path)); } catch (CustomException e) { throw ClientException(e.FriendlyMessage); } catch (ArgumentException) { throw ClientException(D.INVALID_PATH + ": " + name); } catch (Exception e) { HandleException(e, "Delete"); throw ClientException(D.UNEXPECTED_ERROR_OCCURED); } }
//--------------------------- Retorna as informações da iso de Wii public static Int32 GetIsoInformation(String file, out string code, out string name, out int region, out long used) { code = ""; name = ""; region = -1; used = 0; IIOContext context = IOManager.CreateIOContext("ISWIIISO", file, FileAccess.Read, FileShare.ReadWrite, 0, FileMode.Open, EFileAttributes.None); if (context.Result != (int)IORet.RET_IO_OK) { //Loga erro return(context.Result); } int r = 0; WiiDisc d = new WiiDisc(context, false); d.Open(); r = d.BuildDisc(PartitionSelection.OnlyGamePartition); if (r == 0) { name = d.name; code = d.code; used = d.UsedSectors; Byte[] bregion = new byte[4]; if (context.Read(bregion, WBFSDevice.IsoRegionPos, 4) != IORet.RET_IO_OK) { //Loga erro region = -1; } else { region = (int)System.Net.IPAddress.NetworkToHostOrder((int)BitConverter.ToUInt32(bregion, 0)); } bregion = null; d.Close(); context.Close(); return(0); } else { d.Close(); context.Close(); return(r); } }
//-------------- Rotinas public DiscReader(IDisc disc) { this.disc = (Disc)disc; device = this.disc.device; context = IOManager.CreateIOContext(this.device.Name + disc.Code, this.device.device.Path, FileAccess.ReadWrite, FileShare.None, 0, FileMode.Open, EFileAttributes.NoBuffering); Lock(); Seek(0); Unlock(); }
public void ClearPrivate() { try { IIOContext io = IOContext.Current; io.Delete(Path.Combine(_io.LocalStorage, io.PrivateDirectory)); } catch (Exception e) { HandleException(e, "ClearPrivate"); } }
//-------------- Rotinas public DVDRomReader(Char drive) { context = IOManager.CreateIOContext("DVD-ROM " + drive, @"\\.\" + drive + ':', FileAccess.Read, FileShare.Read, 0, FileMode.Open, EFileAttributes.NoBuffering); context.Lock(); DISK_GEOMETRY dg = context.GetDiskGeometry(); sectorSize = (int)dg.BytesPerSector; PARTITION_INFORMATION pi = context.GetPartitionInformation(); size = pi.PartitionLength; context.Unlock(); }
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); }
//--------------------------- Verifica se o arquivo é uma iso de Wii public static Int32 IsWiiIso(String file) { IIOContext context = IOManager.CreateIOContext("ISWIIISO", file, FileAccess.Read, FileShare.ReadWrite, 0, FileMode.Open, EFileAttributes.None); if (context.Result != (int)IORet.RET_IO_OK) { //Loga erro return(context.Result); } else { int r = (int)context.Lock(); if (r != (int)IORet.RET_IO_OK) { //Loga erro context.Close(); return(r); } Byte[] header = new Byte[256]; if (context.Read(header, 256) != IORet.RET_IO_OK) { //Loga erro r = context.Result; context.Unlock(); context.Close(); return(r); } r = IsWiiIso(header); context.Unlock(); context.Close(); return(r); } }
//--------------------------- Retorna as informações da iso de Wii public static Int32 GetIsoInformation(String file, out string code, out string name, out long used) { code = ""; name = ""; used = 0; IIOContext context = IOManager.CreateIOContext("ISWIIISO", file, FileAccess.Read, FileShare.ReadWrite, 0, FileMode.Open, EFileAttributes.None); if (context.Result != (int)IORet.RET_IO_OK) { //Loga erro return(context.Result); } int r = 0; WiiDisc d = new WiiDisc(context, false); d.Open(); r = d.BuildDisc(PartitionSelection.OnlyGamePartition); if (r == 0) { name = d.name; code = d.code; used = d.UsedSectors; d.Close(); context.Close(); return(0); } else { d.Close(); context.Close(); return(r); } }
public bool CreateDirectory(string name) { try { IIOContext io = IOContext.Current; string path = io.TranslateLocalPath(name); return(io.CreateDirectory(path)); } catch (CustomException e) { throw ClientException(e.FriendlyMessage); } catch (ArgumentException) { throw ClientException(D.INVALID_PATH + ": " + name); } catch (Exception e) { HandleException(e, "CreateDirectory"); throw ClientException(D.UNEXPECTED_ERROR_OCCURED); } }
//---------------------------- Rotinas public MBRReader(string device) { IIOContext pdrive = IOManager.CreateIOContext("PDRIVE\\" + device, device, FileAccess.Read, FileShare.Read, 0, FileMode.Open, EFileAttributes.NoBuffering); if (pdrive.Result != 0) { result = pdrive.Result; return; } if (pdrive.Lock() != IORet.RET_IO_OK) { //Loga a informação result = pdrive.Result; return; } Byte[] mbr = new byte[512]; if (pdrive.Read(mbr, 512) != IORet.RET_IO_OK) { result = pdrive.Result; pdrive.Unlock(); pdrive.Close(); return; } //----------------- //MBRReader(byte[] mbr) //----------------- pdrive.Unlock(); pdrive.Close(); }
public static void Init(IIOContext context) { Current = context; }
int partIndex = 0; //Partição atual //---------------------------- Rotinas //--------------------------- Construtor, inicializa a classe com um contexto de arquivo public WiiDisc(IIOContext context, bool generateExtendedInfo) { file = context; Partition = PartitionSelection.AllPartitions; GenerateExtendedInfo = generateExtendedInfo; }
//--------------------------- Retorna as informações da iso de Wii public static Int32 GetIsoInformation(String file, out string code, out string name, out int region) { code = ""; name = ""; region = -1; IIOContext context = IOManager.CreateIOContext("ISWIIISO", file, FileAccess.Read, FileShare.ReadWrite, 0, FileMode.Open, EFileAttributes.None); if (context.Result != (int)IORet.RET_IO_OK) { //Loga erro return(context.Result); } else { int r = (int)context.Lock(); if (r != (int)IORet.RET_IO_OK) { //Loga erro context.Close(); return(r); } Byte[] header = new Byte[256]; if (context.Read(header, 256) != IORet.RET_IO_OK) { //Loga erro r = context.Result; context.Unlock(); context.Close(); header = null; return(r); } uint magic = _be32(header, 24); if (magic != 0x5D1C9EA3) { context.Unlock(); context.Close(); header = null; return((int)WBFSRet.RET_WBFS_NOTAWIIDISC); } //Lê o código do jogo de 6 caracteres int j = WBFSDevice.IsoCodePos; byte c = 0; for (j = WBFSDevice.IsoCodePos; j < WBFSDevice.IsoCodePos + WBFSDevice.IsoCodeLen; j++) { code += (char)header[j]; } //Lê o nome do jogo j = WBFSDevice.IsoNamePos; while (((c = header[j++]) != 0) && (j < WBFSDevice.IsoNamePos + WBFSDevice.IsoNameLen)) { name += (char)c; } if (context.Read(header, WBFSDevice.IsoRegionPos, 4) != IORet.RET_IO_OK) { //Loga erro r = context.Result; context.Unlock(); context.Close(); header = null; return(r); } region = (int)System.Net.IPAddress.NetworkToHostOrder((int)BitConverter.ToUInt32(header, 0)); context.Unlock(); context.Close(); header = null; return(0); } }
//--------------------------- Retorna as informações da iso de Wii public static Int32 SetIsoInformation(String file, string code, string name) { IIOContext context = IOManager.CreateIOContext("ISWIIISO", file, FileAccess.ReadWrite, FileShare.Read, 0, FileMode.Open, EFileAttributes.None); if (context.Result != (int)IORet.RET_IO_OK) { //Loga erro return(context.Result); } else { int r = (int)context.Lock(); if (r != (int)IORet.RET_IO_OK) { //Loga erro context.Close(); return(r); } Byte[] header = new Byte[256]; if (context.Read(header, 256) != IORet.RET_IO_OK) { //Loga erro r = context.Result; context.Unlock(); context.Close(); return(r); } uint magic = _be32(header, 24); if (magic != 0x5D1C9EA3) { context.Unlock(); context.Close(); header = null; return((int)WBFSRet.RET_WBFS_NOTAWIIDISC); } header = null; // if (code.Length != 0) { if (code.Length != WBFSDevice.IsoCodeLen) { if (code.Length < WBFSDevice.IsoCodeLen) { while (code.Length < WBFSDevice.IsoCodeLen) { code += '0'; } } else { code = code.Substring(0, WBFSDevice.IsoCodeLen); //Eu preciso fazer isso para o GetDiscByCode() } } context.Seek(WBFSDevice.IsoCodePos); context.Write(code, false); } if (name.Length != 0) { if (name.Length > WBFSDevice.IsoNameLen) { name = name.Substring(0, WBFSDevice.IsoNameLen); } context.Seek(WBFSDevice.IsoNamePos); context.Write(name, false); for (int i = name.Length; i < WBFSDevice.IsoNameLen; i++) { context.Write((byte)0); } } // context.Unlock(); context.Close(); return(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); } } }
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); } }
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(); } } }