public SyncAction GetSyncAction(string targetName, int syncPointId, IFileReference currentFileVersion, IFileReference newFileVersion) { if (m_FileReferenceComparer.Equals(currentFileVersion, newFileVersion)) { return null; } if (currentFileVersion != null) { if (newFileVersion == null) { return SyncAction.CreateRemoveFileSyncAction(targetName, SyncActionState.Queued, syncPointId, currentFileVersion); } else { return SyncAction.CreateReplaceFileSyncAction(targetName, SyncActionState.Queued, syncPointId, currentFileVersion, newFileVersion); } } else { if (newFileVersion != null) { return SyncAction.CreateAddFileSyncAction(targetName, SyncActionState.Queued, syncPointId, newFileVersion); } else { throw new InvalidOperationException(); } } }
/// <summary> /// Initializes a new instance of the <see cref="CsvTableDataLoader" /> class. /// </summary> /// <param name="file"> The file reference to the CSV file. </param> /// <param name="table"> The metadata of the requested table. </param> public CsvTableDataLoader(IFileReference file, TableDescription table) : base(table) { // TODO: Constructor injection this.valueConverter = new CsvValueConverter(); this.file = file; }
public Sample Format(IFileReference file, string languageClass = null) { var snippet = new Sample(file.Path){ Language = languageClass ?? "lang-" + Path.GetExtension(file.Path).Replace(".", "") }; file.ReadContents(stream => { using (var reader = new StreamReader(stream)) { int lineNumber = 0; string line; while ((line = reader.ReadLine()) != null) { lineNumber++; if (line.Contains(Samples.SAMPLE) || line.Contains(Samples.END)) { snippet.Append(string.Empty, lineNumber); } else { snippet.Append(line, lineNumber); } } } }); return snippet; }
/// <summary> /// Delete the specified temporary file. /// </summary> /// <param name="file"></param> public static void Delete(IFileReference file) { if (!file.IsTempFile) { throw new DicomIoException("Only temporary files should be removed through this operation."); } Instance.DeletePrivate(file); }
/// <summary> /// Initializes an instance of <see cref="FileByteTarget"/>. /// </summary> /// <param name="file"></param> public FileByteTarget(IFileReference file) { _file = file; _stream = _file.OpenWrite(); _endian = Endian.LocalMachine; _writer = EndianBinaryWriter.Create(_stream, _endian); _lock = new object(); }
bool TryResolveConflict(ChangeGraphBuilder changeGraphBuilder, IMultiFileSystemHistoryService historyService, ConflictInfo conflict, out IFileReference resolved) { var graph = changeGraphBuilder.GetChangeGraphs(GetDiff(historyService, conflict)).Single(); var sinks = graph.GetSinks().ToArray(); return TryResolveConflict(sinks, out resolved); }
public Change(ChangeType type, IFileReference fromFile, IFileReference toFile) { AssertIsValidChange(type, fromFile, toFile); AssertPathsAreEqual(fromFile, toFile); Type = type; FromVersion = fromFile; ToVersion = toFile; }
/// <summary> /// Initializes a <see cref="TempFileBuffer"/> object. /// </summary> /// <param name="data">Byte array subject to buffering.</param> public TempFileBuffer(byte[] data) { this.file = TemporaryFile.Create(); this.Size = (uint)data.Length; using (var stream = this.file.OpenWrite()) { stream.Write(data, 0, (int)this.Size); } }
/// <summary> /// <paramref name="streamProvider"/> streamProvider callers will dispose result after use. /// <paramref name="streamProvider"/> and <paramref name="fileReference"/> are mutually exclusive. /// </summary> internal ManagedResource(string name, bool isPublic, Func<Stream> streamProvider, IFileReference fileReference, uint offset) { Debug.Assert(streamProvider == null ^ fileReference == null); _streamProvider = streamProvider; _name = name; _fileReference = fileReference; _offset = offset; _isPublic = isPublic; }
void AssertIsValidAddedChange(IFileReference fromFile, IFileReference toFile) { if (fromFile != null) { throw new ArgumentException($"{nameof(fromFile)} must be null for ChangeType {ChangeType.Added}", nameof(fromFile)); } if (toFile == null) { throw new ArgumentNullException(nameof(toFile)); } }
public FileByteSource(IFileReference file) { _file = file; _stream = _file.OpenRead(); _endian = Endian.LocalMachine; _reader = EndianBinaryReader.Create(_stream, _endian); _mark = 0; _largeObjectSize = 64 * 1024; _milestones = new Stack<long>(); _lock = new object(); }
public SyncAction(ChangeType type, IFileReference fromVersion, IFileReference toVersion, Guid id, string target, SyncActionState state, int syncPointId) : base(type, fromVersion, toVersion) { if (syncPointId <= 0) { throw new ArgumentOutOfRangeException(nameof(syncPointId), "Id must be a positive integer"); } this.Target = target; this.Id = id; this.State = state; this.SyncPointId = syncPointId; }
protected override bool TryResolveConflict(IEnumerable<IFileReference> versions, out IFileReference resolvedVersion) { var containsMultipleItems = versions.Skip(1).Any(); if (containsMultipleItems) { resolvedVersion = null; return false; } else { resolvedVersion = versions.Single(); return true; } }
void AssertIsValidChange(ChangeType type, IFileReference fromFile, IFileReference toFile) { switch (type) { case ChangeType.Added: AssertIsValidAddedChange(fromFile, toFile); break; case ChangeType.Deleted: AssertIsValidDeletedChange(fromFile, toFile); break; case ChangeType.Modified: AssertIsValidModifiedChange(fromFile, toFile); break; default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } }
public bool Equals(IFileReference other) { if (other == null) { return false; } if (ReferenceEquals(this, other)) { return true; } return StringComparer.InvariantCultureIgnoreCase.Equals(this.Path, other.Path) && LastWriteTime == other.LastWriteTime && Length == other.Length; }
protected override void RecordFileReference(IFileReference fileReference) { this.metadataWriter.GetAssemblyFileHandle(fileReference); }
public override Task <IFileReference> AddFileAsync(IFileReference source, string filename, BuildId buildId, TextWriter log) => throw new NotSupportedException(Strings.CopyToHttpStoreNotSupported);
/// <summary> /// Process P-DATA-TF PDUs. /// </summary> /// <param name="pdu">PDU to process.</param> private async Task ProcessPDataTFAsync(PDataTF pdu) { try { foreach (var pdv in pdu.PDVs) { if (_dimse == null) { // create stream for receiving command if (_dimseStream == null) { _dimseStream = new MemoryStream(); _dimseStreamFile = null; } } else { // create stream for receiving dataset if (_dimseStream == null) { if (_dimse.Type == DicomCommandField.CStoreRequest) { var pc = Association.PresentationContexts.FirstOrDefault(x => x.ID == pdv.PCID); var file = new DicomFile(); file.FileMetaInfo.MediaStorageSOPClassUID = pc.AbstractSyntax; file.FileMetaInfo.MediaStorageSOPInstanceUID = _dimse.Command.Get<DicomUID>(DicomTag.AffectedSOPInstanceUID); file.FileMetaInfo.TransferSyntax = pc.AcceptedTransferSyntax; file.FileMetaInfo.ImplementationClassUID = Association.RemoteImplemetationClassUID; file.FileMetaInfo.ImplementationVersionName = Association.RemoteImplementationVersion; file.FileMetaInfo.SourceApplicationEntityTitle = Association.CallingAE; CreateCStoreReceiveStream(file); } else { _dimseStream = new MemoryStream(); _dimseStreamFile = null; } } } await this._dimseStream.WriteAsync(pdv.Value, 0, pdv.Value.Length).ConfigureAwait(false); if (pdv.IsLastFragment) { if (pdv.IsCommand) { _dimseStream.Seek(0, SeekOrigin.Begin); var command = new DicomDataset(); var reader = new DicomReader(); reader.IsExplicitVR = false; reader.Read(new StreamByteSource(_dimseStream), new DicomDatasetReaderObserver(command)); _dimseStream = null; _dimseStreamFile = null; var type = command.Get<DicomCommandField>(DicomTag.CommandField); switch (type) { case DicomCommandField.CStoreRequest: _dimse = new DicomCStoreRequest(command); break; case DicomCommandField.CStoreResponse: _dimse = new DicomCStoreResponse(command); break; case DicomCommandField.CFindRequest: _dimse = new DicomCFindRequest(command); break; case DicomCommandField.CFindResponse: _dimse = new DicomCFindResponse(command); break; case DicomCommandField.CMoveRequest: _dimse = new DicomCMoveRequest(command); break; case DicomCommandField.CMoveResponse: _dimse = new DicomCMoveResponse(command); break; case DicomCommandField.CEchoRequest: _dimse = new DicomCEchoRequest(command); break; case DicomCommandField.CEchoResponse: _dimse = new DicomCEchoResponse(command); break; case DicomCommandField.NActionRequest: _dimse = new DicomNActionRequest(command); break; case DicomCommandField.NActionResponse: _dimse = new DicomNActionResponse(command); break; case DicomCommandField.NCreateRequest: _dimse = new DicomNCreateRequest(command); break; case DicomCommandField.NCreateResponse: _dimse = new DicomNCreateResponse(command); break; case DicomCommandField.NDeleteRequest: _dimse = new DicomNDeleteRequest(command); break; case DicomCommandField.NDeleteResponse: _dimse = new DicomNDeleteResponse(command); break; case DicomCommandField.NEventReportRequest: _dimse = new DicomNEventReportRequest(command); break; case DicomCommandField.NEventReportResponse: _dimse = new DicomNEventReportResponse(command); break; case DicomCommandField.NGetRequest: _dimse = new DicomNGetRequest(command); break; case DicomCommandField.NGetResponse: _dimse = new DicomNGetResponse(command); break; case DicomCommandField.NSetRequest: _dimse = new DicomNSetRequest(command); break; case DicomCommandField.NSetResponse: _dimse = new DicomNSetResponse(command); break; default: _dimse = new DicomMessage(command); break; } _dimse.PresentationContext = Association.PresentationContexts.FirstOrDefault(x => x.ID == pdv.PCID); if (!_dimse.HasDataset) { this.PerformDimse(this._dimse); _dimse = null; return; } } else { if (_dimse.Type != DicomCommandField.CStoreRequest) { _dimseStream.Seek(0, SeekOrigin.Begin); var pc = Association.PresentationContexts.FirstOrDefault(x => x.ID == pdv.PCID); _dimse.Dataset = new DicomDataset(); _dimse.Dataset.InternalTransferSyntax = pc.AcceptedTransferSyntax; var source = new StreamByteSource(_dimseStream); source.Endian = pc.AcceptedTransferSyntax.Endian; var reader = new DicomReader(); reader.IsExplicitVR = pc.AcceptedTransferSyntax.IsExplicitVR; reader.Read(source, new DicomDatasetReaderObserver(_dimse.Dataset)); _dimseStream = null; _dimseStreamFile = null; } else { var request = _dimse as DicomCStoreRequest; try { var dicomFile = GetCStoreDicomFile(); _dimseStream = null; _dimseStreamFile = null; // NOTE: dicomFile will be valid with the default implementation of CreateCStoreReceiveStream() and // GetCStoreDicomFile(), but can be null if a child class overrides either method and changes behavior. // See documentation on CreateCStoreReceiveStream() and GetCStoreDicomFile() for information about why // this might be desired. request.File = dicomFile; if (request.File != null) { request.Dataset = request.File.Dataset; } } catch (Exception e) { // failed to parse received DICOM file; send error response instead of aborting connection SendResponse( new DicomCStoreResponse( request, new DicomStatus(DicomStatus.ProcessingFailure, e.Message))); Logger.Error("Error parsing C-Store dataset: {@error}", e); (this as IDicomCStoreProvider).OnCStoreRequestException( _dimseStreamFile != null ? _dimseStreamFile.Name : null, e); return; } } this.PerformDimse(this._dimse); _dimse = null; } } } } catch (Exception e) { SendAbort(DicomAbortSource.ServiceUser, DicomAbortReason.NotSpecified); Logger.Error("Exception processing P-Data-TF PDU: {@error}", e); } finally { SendNextMessage(); } }
/// <summary> /// Performs some computation with the given file reference. /// </summary> public void Visit(IFileReference fileReference) { if (fileReference.FileName.Value.IndexOfAny(badPosixNameChars) > 0) this.ReportError(MetadataError.NotPosixAssemblyName, fileReference, fileReference.FileName.Value); if (fileReference.FileName.UniqueKeyIgnoringCase == this.validator.currentModule.ModuleName.UniqueKeyIgnoringCase) this.ReportError(MetadataError.SelfReference, fileReference); }
/// <summary> /// Traverses the children of the file reference. /// </summary> public virtual void TraverseChildren(IFileReference fileReference) { Contract.Requires(fileReference != null); //no children }
/// <summary> /// Performs some computation with the given file reference. /// </summary> public virtual void Visit(IFileReference fileReference) { }
public static SyncAction CreateAddFileSyncAction(Guid id, string target, SyncActionState state, int syncPointId, IFileReference toVersion) { return new SyncAction(ChangeType.Added, null, toVersion, id, target, state, syncPointId); }
public static SyncAction CreateReplaceFileSyncAction(string target, SyncActionState state, int syncPointId, IFileReference oldVersion, IFileReference newVersion) { return new SyncAction(ChangeType.Modified, oldVersion, newVersion, Guid.NewGuid(), target, state, syncPointId); }
/// <summary> /// /// </summary> /// <param name="other"></param> /// <returns></returns> public virtual bool Equals(IFileReference other) { throw new NotImplementedException(); }
/// <summary> /// <paramref name="streamProvider"/> streamProvider callers will dispose result after use. /// <paramref name="streamProvider"/> and <paramref name="fileReference"/> are mutually exclusive. /// </summary> internal ManagedResource(string name, bool isPublic, Func <Stream> streamProvider, IFileReference fileReference, uint offset) { Debug.Assert(streamProvider == null ^ fileReference == null); _streamProvider = streamProvider; _name = name; _fileReference = fileReference; _offset = offset; _isPublic = isPublic; }
public override void Visit(IFileReference fileReference) { allElements.Add(new InvokInfo(Traverser, "IFileReference", fileReference)); }
protected override void RecordFileReference(IFileReference fileReference) { }
private async Task <ContentItem> RefreshContentFromFile(string fileName, ContentItem cachedItem, TimeSpan expiresIn) { using (Trace.Activity("Downloading Content Item: " + fileName)) { IFileReference reference = await FileStorage.GetFileReferenceAsync( CoreConstants.Folders.ContentFolderName, fileName, ifNoneMatch : cachedItem?.ContentId); if (reference == null) { Trace.Verbose("Requested Content File Not Found: " + fileName); return(null); } // Check the content ID to see if it's different if (cachedItem != null && String.Equals(cachedItem.ContentId, reference.ContentId, StringComparison.Ordinal)) { Trace.Verbose("No change to content item. Using Cache"); // Update the expiry time cachedItem.ExpiryUtc = DateTime.UtcNow + expiresIn; Trace.Verbose($"Updating Cache: {fileName} expires at {cachedItem.ExpiryUtc}"); return(cachedItem); } // Retrieve the content Trace.Verbose("Content Item changed. Trying to update..."); try { using (var stream = reference.OpenRead()) { if (stream == null) { Trace.Error("Requested Content File Not Found: " + fileName); return(null); } else { using (Trace.Activity("Reading Content File: " + fileName)) { using (var reader = new StreamReader(stream)) { string text = await reader.ReadToEndAsync(); string content; if (fileName.EndsWith(".md")) { content = new Markdown().Transform(text); } else { content = text; } IHtmlString html = new HtmlString(content.Trim()); // Prep the new item for the cache var expiryTime = DateTime.UtcNow + expiresIn; return(new ContentItem(html, expiryTime, reference.ContentId, DateTime.UtcNow)); } } } } } catch (Exception) { Debug.Assert(false, "owchy oochy - reading content failed"); Trace.Error("Reading updated content failed. Returning cached content instead."); return(cachedItem); } } }
protected abstract void RecordFileReference(IFileReference fileReference);
public override void Visit(IFileReference fileReference) { RecordFileReference(fileReference); }
public Task UploadBlobToContainer(IFileReference fileName, string blobName) { throw new NotImplementedException(); }
public static SyncAction CreateAddFileSyncAction(string target, SyncActionState state, int syncPointId, IFileReference toVersion) { return CreateAddFileSyncAction(Guid.NewGuid(), target, state, syncPointId, toVersion); }
public static void SetApplication(File file, IFileReference application) { NgenPackageItem item = Ngen.CreatePackageItem(file); item.Application = application; }
public static SyncAction CreateRemoveFileSyncAction(string target, SyncActionState state, int syncPointId, IFileReference removedFile) { return new SyncAction(ChangeType.Deleted, removedFile, null, Guid.NewGuid(), target, state, syncPointId); }
public virtual void onMetadataElement(IFileReference fileReference) { }
/// <summary> /// Traverses the file reference. /// </summary> public void Traverse(IFileReference fileReference) { Contract.Requires(fileReference != null); if (this.preorderVisitor != null) this.preorderVisitor.Visit(fileReference); if (this.stopTraversal) return; this.TraverseChildren(fileReference); if (this.stopTraversal) return; if (this.postorderVisitor != null) this.postorderVisitor.Visit(fileReference); }
public FileByteBuffer(IFileReference file, long Position, uint Length) { this.File = file; this.Position = Position; this.Size = Length; }
public void Visit(IFileReference fileReference) { Contract.Assume(false); }
public FileReferenceItem(IFileReference fileReference) { FileReferenceReference = fileReference; }
/// <summary> /// The purpose of this method is to return the Stream that a SopInstance received /// via CStoreSCP will be written to. This default implementation creates a temporary /// file and returns a FileStream on top of it. Child classes can override this to write /// to another stream and avoid the I/O associated with the temporary file if so desired. /// Beware that some SopInstances can be very large so using a MemoryStream() could cause /// out of memory situations. /// </summary> /// <param name="file">A DicomFile with FileMetaInfo populated.</param> /// <returns>The stream to write the SopInstance to.</returns> protected virtual void CreateCStoreReceiveStream(DicomFile file) { _dimseStreamFile = TemporaryFile.Create(); _dimseStream = _dimseStreamFile.Open(); file.Save(_dimseStream); _dimseStream.Seek(0, SeekOrigin.End); }
protected override void RecordFileReference(IFileReference fileReference) { this.metadataWriter.GetFileRefIndex(fileReference); }
public async Task ShowPropertySearchLegalView([NotNull] IFileReference fileReference) { await _workspaceViewModel.ShowPropertySearchLegalView(fileReference); }
public InternalState(IFileReference fileReference, RevalidationState state) { FileReference = fileReference ?? throw new ArgumentNullException(nameof(fileReference)); State = state ?? throw new ArgumentNullException(nameof(state)); }
public virtual void Visit(IFileReference fileReference) { }
/// <summary> /// Reads the specified file and returns a DicomFile object. Note that the values for large /// DICOM elements (e.g. PixelData) are read in "on demand" to conserve memory. Large DICOM elements /// are determined by their size in bytes - see the default value for this in the FileByteSource._largeObjectSize /// </summary> /// <param name="file">The file reference of the DICOM file</param> /// <param name="fallbackEncoding">Encoding to apply when attribute Specific Character Set is not available.</param> /// <returns>DicomFile instance</returns> internal static DicomFile Open(IFileReference file, Encoding fallbackEncoding) { if (fallbackEncoding == null) { throw new ArgumentNullException("fallbackEncoding"); } DicomFile df = new DicomFile(); try { df.File = file; using (var source = new FileByteSource(file)) { DicomFileReader reader = new DicomFileReader(); var result = reader.Read( source, new DicomDatasetReaderObserver(df.FileMetaInfo), new DicomDatasetReaderObserver(df.Dataset, fallbackEncoding)); if (result == DicomReaderResult.Processing) { throw new DicomFileException(df, "Invalid read return state: {state}", result); } if (result == DicomReaderResult.Error) { return null; } df.IsPartial = result == DicomReaderResult.Stopped || result == DicomReaderResult.Suspended; df.Format = reader.FileFormat; df.Dataset.InternalTransferSyntax = reader.Syntax; return df; } } catch (Exception e) { throw new DicomFileException(df, e.Message, e); } }
public FileByteBufferTest() { _fileReference = TemporaryFile.Create(); }