public static Stream FOpen(Lua.CharPtr cFilename, Lua.CharPtr cMode) { string filename = "/" + cFilename.ToString(); filename = filename.Replace("\\", "/").Replace("/./", "/"); filename = filename.Substring(1); // remove the leading slash again //bool read = true; bool write = false; bool truncate = false; bool startAtEnd = false; if (cMode.chars.Length != 0) { int pos = 0; switch (cMode.chars[pos]) { case 'r': break; case 'w': //read = false; write = true; truncate = true; break; case 'a': //read = false; write = true; startAtEnd = true; break; default: throw new ArgumentException(string.Format("Bad mode character '{0}' at position {1} in mode '{2}'", cMode.chars[pos], pos, cMode.ToString())); } ++pos; if (cMode.chars[pos] == '+') { //read = true; write = true; ++pos; } if (cMode.chars[pos] == 'b') { // ignore ++pos; } if (cMode.chars[pos] != '\0') { throw new ArgumentException(string.Format("Bad mode character '{0}' at position {1} in mode '{2}'", cMode.chars[pos], pos, cMode.ToString())); } } // Try to populate from Unity Resources, but don't bother if we're truncating if (!truncate && !_fileSystem.ContainsKey(filename)) { PopulateFromResource(filename); } // If we're not writing, we just use a read-only MemoryStream to access the data, allowing simultaneous reads if (!write) { if (!_fileSystem.ContainsKey(filename)) { throw new FileNotFoundException(string.Format("File not found - {0}", filename)); } return(new MemoryStream(_fileSystem[filename], false)); } // Since we're writing we need to use a fancy derivative of MemoryStream that knows how to bake the data into // the filesystem when it is disposed var stream = new FileMemoryStream(filename, truncate, startAtEnd); return(stream); }
public static Stream FOpen(Lua.CharPtr cFilename, Lua.CharPtr cMode) { string filename = "/" + cFilename.ToString(); filename = filename.Replace("\\", "/").Replace("/./", "/"); filename = filename.Substring(1); // remove the leading slash again bool read = true; bool write = false; bool truncate = false; bool startAtEnd = false; if (cMode.chars.Length != 0) { int pos = 0; switch (cMode.chars[pos]) { case 'r': break; case 'w': read = false; write = true; truncate = true; break; case 'a': read = false; write = true; startAtEnd = true; break; default: throw new ArgumentException(string.Format("Bad mode character '{0}' at position {1} in mode '{2}'", cMode.chars[pos], pos, cMode.ToString())); } ++pos; if (cMode.chars[pos] == '+') { read = true; write = true; ++pos; } if (cMode.chars[pos] == 'b') { // ignore ++pos; } if (cMode.chars[pos] != '\0') { throw new ArgumentException(string.Format("Bad mode character '{0}' at position {1} in mode '{2}'", cMode.chars[pos], pos, cMode.ToString())); } } // Try to populate from Unity Resources, but don't bother if we're truncating if (!truncate && !_fileSystem.ContainsKey(filename)) PopulateFromResource(filename); // If we're not writing, we just use a read-only MemoryStream to access the data, allowing simultaneous reads if (!write) { if (!_fileSystem.ContainsKey(filename)) { throw new FileNotFoundException(string.Format("File not found - {0}", filename)); } return new MemoryStream(_fileSystem[filename], false); } // Since we're writing we need to use a fancy derivative of MemoryStream that knows how to bake the data into // the filesystem when it is disposed var stream = new FileMemoryStream(filename, truncate, startAtEnd); return stream; }
/// <summary> /// Uploads a document to the KBX Document Service and stores metadata in Loadshop /// </summary> /// <param name="uploadPayload"></param> /// <returns></returns> public async Task <LoadDocumentMetadata> UploadDocument(LoadDocumentUploadData uploadPayload) { securityService.GuardAction(SecurityActions.Loadshop_Ui_Carrier_MyLoads_Documents_Attach); if (uploadPayload.LoadDocumentType == null || uploadPayload.LoadDocumentType.Id < 1) { throw new ValidationException("Invalid load document type"); } var load = await context.Loads.AsNoTracking().FirstOrDefaultAsync(x => x.LoadId == uploadPayload.LoadId); if (load == null) { throw new ValidationException("Load not found"); } var billingLoadId = await context.LoadTransactions.AsNoTracking() .Include(x => x.Claim) .Where(x => x.TransactionTypeId == TransactionTypes.Accepted) .Where(x => x.LoadId == load.LoadId) .Select(x => x.Claim.BillingLoadId) .FirstOrDefaultAsync(); // copy stream to request var stream = new FileMemoryStream(); await uploadPayload.File.CopyToAsync(stream); // reset position to ensure http request sends payload stream.Position = 0; stream.FileName = uploadPayload.File.FileName; stream.ContentDisposition = uploadPayload.File.ContentDisposition; stream.ContentType = uploadPayload.File.ContentType; // we hold all metadata in loadshop; however we will include some fields in case TOPS needs to query anything from there in the future var request = new DocumentService.SDK.Version.V1.Model.DocumentCreate() { Properties = new List <DocPropertyData>() { new DocPropertyData() { PropertyValue = load.LoadId.ToString(), PropertyName = DocumentServiceConstants.Property_Name_LoadshopLoadId }, new DocPropertyData() { PropertyValue = load.PlatformPlusLoadId?.ToString(), PropertyName = DocumentServiceConstants.Property_Name_PlatformPlusLoadId }, new DocPropertyData() { PropertyValue = load.ReferenceLoadId?.ToString(), PropertyName = DocumentServiceConstants.Property_Name_ReferenceLoadId }, new DocPropertyData() { PropertyValue = billingLoadId, PropertyName = DocumentServiceConstants.Property_Name_BillingLoadId } }, DocTypeId = uploadPayload.LoadDocumentType.Id, CreatedBy = userContext.UserName, CreatedDateTime = DateTime.Now, DocumentFile = stream }; try { // upload file to document API var uploadResult = await documentApiClient.CreateDocument(request); if (uploadResult.Status.Equals("Error", StringComparison.CurrentCultureIgnoreCase)) { throw new Exception($"Error while upload document to Document Service: {uploadResult.Result}"); } var entity = new LoadDocumentEntity() { LoadDocumentId = Guid.NewGuid(), DocumentServiceDocHeaderId = uploadResult.ResultData.DocHeaderId.Value, DocumentServiceDocContentId = uploadResult.ResultData.DocContentId.Value, DocumentServiceDocumentType = uploadPayload.LoadDocumentType.Id, FileName = uploadPayload.File.FileName, Comment = uploadPayload.Comment, LoadId = load.LoadId, CreateBy = userContext.UserName, CreateDtTm = DateTime.Now, LastChgBy = userContext.UserName, LastChgDtTm = DateTime.Now }; // add the new entity and in order for the DB to generate the doc id, use that to pass to the document service context.LoadDocuments.Add(entity); await context.SaveChangesAsync(); return(mapper.Map <LoadDocumentMetadata>(entity)); } catch (Exception e) { // if any errors occured, we dont want to show the record in loadshop, so remove the attachment record and return error logger.LogError($"Error while uploading document: {e.Message}", e); } return(null); }
private void _initAdfFile() { //prerequisites if (FileLoaded) { FileLoaded = false; } if (!File.Exists(FileName)) { throw new FileNotFoundException(FileName); } try { using (var fsSource = new FileStream(FileName, FileMode.Open, FileAccess.Read)) { //File too long? if (fsSource.Length > int.MaxValue) { throw new FileLoadException("File is too big."); } //vars FileLength = (int)fsSource.Length; //verify file length if (FileLength % Blocksize != 0) { throw new InvalidDataException(string.Format("Invalid block size to file size ratio (bs:{0}, fs:{1}).", Blocksize, FileLength)); } #if DEBUG Debug.WriteLine(string.Format("Filename (bytes): {0} ({1})", FileName, FileLength)); #endif //init arrays if (_bytMain != null) { _bytMain = null; } if (_bytCompare != null) { _bytCompare = null; } _bytMain = new byte[FileLength]; _bytCompare = new byte[FileLength]; //check for known disk sizes if (FileLength == 1760 * Blocksize) { FileDiskType = DiskType.DoubleDensity_DD; } if (FileLength == 3520 * Blocksize) { FileDiskType = DiskType.HighDensity_HD; } //read file to buffers fsSource.Read(_bytMain, 0, FileLength); fsSource.Seek(0, SeekOrigin.Begin); fsSource.Read(_bytCompare, 0, FileLength); fsSource.Close(); //init stream if (FileMemoryStream != null) { FileMemoryStream.Dispose(); FileMemoryStream = null; } FileMemoryStream = new MemoryStream(_bytMain); FileLoaded = true; } } catch (Exception e) { Console.WriteLine(e); throw; } }