internal void Save(DataManager data) { FileStream fileStream = FileUtils.OpenForWrite(data.ResolvePath(FileName)); if (fileStream != null) { // WindowsImpersonationContext wi = Impersonation.Impersonate(); try { XmlSerializer ser = new XmlSerializer(typeof(DayExtra), Data.NamespaceURI); using (StreamWriter writer = new StreamWriter(fileStream)) { ser.Serialize(writer, this); } } catch (Exception e) { ErrorTrace.Trace(TraceLevel.Error, e); // truncate the file if this fails fileStream.SetLength(0); } finally { fileStream.Close(); } // wi.Undo(); } }
internal void LoadDayExtra(string fullPath) { FileStream fileStream = FileUtils.OpenForRead(fullPath); if (fileStream != null) { try { XmlSerializer ser = new XmlSerializer(typeof(DayExtraOld), "urn:newtelligence-com:dasblog:runtime:data"); using (StreamReader reader = new StreamReader(fileStream)) { //TODO: SDH: We need to have a better namespace upgrading solution for Medium Trust for folks with the OLD XML format //XmlNamespaceUpgradeReader upg = new XmlNamespaceUpgradeReader(reader, "", "urn:newtelligence-com:dasblog:runtime:data"); DayExtraOld e = (DayExtraOld)ser.Deserialize(reader); this._date = e.DateLocalTime; this._comments = e.Comments; this._trackings = e.Trackings; } } catch (Exception e) { ErrorTrace.Trace(TraceLevel.Error, e); } finally { fileStream.Close(); } } }
internal void LoadDayExtra(string fullPath) { FileStream fileStream = FileUtils.OpenForRead(fullPath); if (fileStream != null) { try { XmlSerializer ser = new XmlSerializer(typeof(DayExtra), Data.NamespaceURI); using (StreamReader reader = new StreamReader(fileStream)) { //XmlNamespaceUpgradeReader upg = new XmlNamespaceUpgradeReader(reader, "", Data.NamespaceURI); DayExtra e = (DayExtra)ser.Deserialize(reader); this._comments = e.Comments; this._trackings = e.Trackings; } } catch (Exception e) { ErrorTrace.Trace(TraceLevel.Error, e); } finally { fileStream.Close(); } //RepairComments(); } }
public void Rebuild() { // get the lock fileLock.AcquireWriterLock(100); try { XmlSerializer x = new XmlSerializer(typeof(DayExtra)); CommentCollection rebuiltCollection = new CommentCollection(); DirectoryInfo di = new DirectoryInfo(this.contentBaseDirectory); foreach (FileInfo file in di.GetFiles("*dayfeedback.xml")) { using (FileStream fs = file.OpenRead()) { DayExtra de = (DayExtra)x.Deserialize(fs); rebuiltCollection.AddRange(de.Comments); } } _commentCache = rebuiltCollection; } catch (Exception e) { // report error ErrorTrace.Trace(TraceLevel.Error, e); } finally { // release the lock fileLock.ReleaseWriterLock(); } }
public void DeleteComment(string commentId) { if (commentId == null || commentId.Length == 0) { throw new ArgumentNullException("commentId"); } // get the lock fileLock.AcquireWriterLock(100); try{ // find the comment to delete Comment deletedComment = _commentCache[commentId]; // did we get a comment? if (deletedComment != null) { // remove from collection _commentCache.Remove(deletedComment); _lastUpdated = DateTime.UtcNow; } } catch (Exception e) { // report error ErrorTrace.Trace(TraceLevel.Error, e); } finally { // release the lock fileLock.ReleaseWriterLock(); } }
/// <summary> /// Updates a comment in the all comments file. /// </summary> /// <param name="comment">The new version of the comment.</param> public void UpdateComment(Comment comment) { // parameter check if (comment == null) { throw new ArgumentNullException("comment"); } // get the lock fileLock.AcquireWriterLock(100); try{ // check for exiting comment Comment oldComment = _commentCache[comment.EntryId]; if (oldComment == null) { throw new ArgumentException("Comment does not exist in the allcomments file, use the add comment method to add a new comment.", "comment"); } // replace the old comment _commentCache.Remove(oldComment); _commentCache.Add(comment); _lastUpdated = DateTime.UtcNow; } catch (Exception e) { // report error ErrorTrace.Trace(TraceLevel.Error, e); } finally { // release the lock fileLock.ReleaseWriterLock(); } }
// METHODS // note: simple implementation: // we don't want to load the collection, remove 1 comment and save it again // but until we have hard numbers this is too slow, let's use this /// <summary> /// Adds the comment to the all comments file. /// </summary> /// <param name="comment">The comment to add.</param> public void AddComment(Comment comment) { // parameter check if (comment == null) { throw new ArgumentNullException("comment"); } // get the lock fileLock.AcquireWriterLock(100); try{ // check for exiting comment if (_commentCache[comment.EntryId] != null) { throw new ArgumentException("Comment all ready exists in the allcomments file, use the update comment method to update.", "comment"); } // add the comment _commentCache.Add(comment); _lastUpdated = DateTime.UtcNow; } catch (Exception e) { // report error ErrorTrace.Trace(TraceLevel.Error, e); } finally { // release the lock fileLock.ReleaseWriterLock(); } }
static string ReadLogText(string logFilePath, ReaderWriterLock lockObject) { if (String.IsNullOrEmpty(logFilePath)) { throw new ArgumentOutOfRangeException("logFilePath"); } if (lockObject == null) { throw new ArgumentNullException("lockObject"); } string result = String.Empty; try { lockObject.AcquireReaderLock(TimeSpan.FromMilliseconds(250)); if (File.Exists(logFilePath) && Path.GetExtension(logFilePath).Equals(".zip", StringComparison.InvariantCultureIgnoreCase)) { ZipFile zip = ZipFile.Read(logFilePath); foreach (ZipEntry e in zip) { using (MemoryStream m = new MemoryStream()) { e.Extract(m); using (StreamReader reader = new StreamReader(m, Encoding.UTF8)) { result = reader.ReadToEnd(); } } } } else { using (StreamReader reader = new StreamReader(logFilePath)) { result = reader.ReadToEnd(); } } } catch (Exception e) { ErrorTrace.Trace(TraceLevel.Error, e); } finally { if (lockObject.IsReaderLockHeld) { lockObject.ReleaseReaderLock(); } } return(result); }
static void ArchiveLogFileWorker(object argument) { ArchiveThreadParams param = (ArchiveThreadParams)argument; string zipFileName = null; bool deletedOriginal = false; try { if (File.Exists(param.FileName)) { param.LockObject.AcquireReaderLock(TimeSpan.FromMilliseconds(250)); zipFileName = String.Format("{0}.zip", param.FileName); // properly dispose when we're done using (ZipFile zip = new ZipFile(zipFileName)) { // don't include the dir tree in the zipfile zip.IncludeDirectoryTree = false; zip.AddFile(param.FileName); zip.Save(); } File.Delete(param.FileName); deletedOriginal = true; } } catch (Exception e) { ErrorTrace.Trace(TraceLevel.Error, e); // error while creating the zipfile, delete it so we can create a new one later if (zipFileName != null && File.Exists(zipFileName) && !deletedOriginal) { File.Delete(zipFileName); } // logging //while (e != null) { // File.AppendAllText(param.FileName + ".error.txt", "----------------------------------------------------------------" + "\r\n"); // File.AppendAllText(param.FileName + ".error.txt", "filename: " + param.FileName + "\r\n"); // File.AppendAllText(param.FileName + ".error.txt", e.Message + "\r\n"); // File.AppendAllText(param.FileName + ".error.txt", e.StackTrace + "\r\n"); // e = e.InnerException; //} } finally { if (param.LockObject.IsReaderLockHeld) { param.LockObject.ReleaseReaderLock(); } } }
void AddEventDataItemWorker(object argument) { try { WriterThreadParams <EventDataItem> param = (WriterThreadParams <EventDataItem>)argument; WriteEventDataItem(param.LogItem, param.Category, param.LockObject, DefaultEventDataItemFormatter); } catch (Exception e) { ErrorTrace.Trace(TraceLevel.Error, e); } }
void WriteEventDataItem(EventDataItem logItem, LogCategory category, ReaderWriterLock lockObject, EventDataItemFormatter formatter) { if (logItem == null) { throw new ArgumentNullException("logItem"); } if (lockObject == null) { throw new ArgumentNullException("lockObject"); } if (formatter == null) { throw new ArgumentNullException("formatter"); } try { //using (Impersonation.Impersonate()) { // Archive last day's log files. if (!File.Exists(String.Format("{0}.zip", GetLogPath(logItem.EventTimeUtc, LogCategory.Event)))) { ArchiveLogFiles(logItem.EventTimeUtc.AddDays(-1)); } lockObject.AcquireWriterLock(TimeSpan.FromMilliseconds(250)); using (StreamWriter writer = new StreamWriter(GetLogPath(logItem.EventTimeUtc, category), true)) { writer.WriteLine(formatter(logItem)); } } } catch (Exception e) { ErrorTrace.Trace(TraceLevel.Error, e); } finally { if (lockObject.IsWriterLockHeld) { lockObject.ReleaseWriterLock(); } } }
internal void Load(DataManager data) { if (_loaded) { return; } if (data.Resolver != null) { string fullPath = data.ResolvePath(FileName); string oldPath = data.ResolvePath(DateLocalTime.ToString("yyyy-MM-dd") + ".dayextra.xml"); if (UpgradeFilesToUtc && File.Exists(oldPath)) { LoadDayExtra(oldPath); // backup the old file try { DirectoryInfo backup = new DirectoryInfo(Path.Combine(data.ResolvePath(""), "backup")); if (!backup.Exists) { backup.Create(); } FileInfo f = new FileInfo(oldPath); f.MoveTo(Path.Combine(backup.FullName, f.Name)); } catch (Exception e) { ErrorTrace.Trace(TraceLevel.Error, e); } // now write the new file this.Save(data); } else if (File.Exists(fullPath)) { LoadDayExtra(fullPath); } } _loaded = true; }
internal void Save(DataManager data) { string fullPath = data.ResolvePath(FileName); // We use the internal list to circumvent ignoring // items where IsPublic is set to false. if (Entries.Count == 0) { if (File.Exists(fullPath)) { File.Delete(fullPath); } } else { // TODO: Web Core compatability issues ??? // System.Security.Principal.WindowsImpersonationContext wi = Impersonation.Impersonate(); FileStream fileStream = FileUtils.OpenForWrite(fullPath); if (fileStream != null) { try { XmlSerializer ser = new XmlSerializer(typeof(DayEntry), Data.NamespaceURI); using (StreamWriter writer = new StreamWriter(fileStream)) { ser.Serialize(writer, this); } } catch (Exception e) { ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e); } finally { fileStream.Close(); } } // wi.Undo(); } }
internal void Load(DataManager data) { if (Loaded) { return; } lock (entriesLock) { if (Loaded) //SDH: standard thread-safe double check { return; } string fullPath = data.ResolvePath(FileName); FileStream fileStream = FileUtils.OpenForRead(fullPath); if (fileStream != null) { try { XmlSerializer ser = new XmlSerializer(typeof(DayEntry), Data.NamespaceURI); using (StreamReader reader = new StreamReader(fileStream)) { //XmlNamespaceUpgradeReader upg = new XmlNamespaceUpgradeReader( reader, "", Data.NamespaceURI ); DayEntry e = (DayEntry)ser.Deserialize(reader); Entries = e.Entries; } } catch (Exception e) { ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e); } finally { fileStream.Close(); } } Entries.Sort((left, right) => right.CreatedUtc.CompareTo(left.CreatedUtc)); Loaded = true; } }
void WriteLogDataItem(LogDataItem logItem, LogCategory category, ReaderWriterLock lockObject, LogDataItemFormatter formatter) { if (logItem == null) { throw new ArgumentNullException("logItem"); } if (lockObject == null) { throw new ArgumentNullException("lockObject"); } if (formatter == null) { throw new ArgumentNullException("formatter"); } try { //using (Impersonation.Impersonate()) { lockObject.AcquireWriterLock(TimeSpan.FromMilliseconds(250)); using (StreamWriter writer = new StreamWriter(GetLogPath(logItem.RequestedUtc, category), true)) { writer.WriteLine(formatter(logItem)); } } } catch (Exception e) { ErrorTrace.Trace(TraceLevel.Error, e); } finally { if (lockObject.IsWriterLockHeld) { lockObject.ReleaseWriterLock(); } } }
string GetLogText(DateTime dateUtc, LogCategory category, ReaderWriterLock lockObject) { string result = String.Empty; try { // Check for the zip version first. string logFile = String.Format("{0}.zip", GetLogPath(dateUtc, category)); if (!File.Exists(logFile)) { logFile = GetLogPath(dateUtc, category); } result = ReadLogText(logFile, lockObject); } catch (Exception e) { ErrorTrace.Trace(TraceLevel.Error, e); } return(result); }
public string SaveFile(System.IO.Stream inputFile, ref string fileName) { // parameter validation if (inputFile == null) { throw new ArgumentNullException("inputFile"); } if (!inputFile.CanRead) { throw new ArgumentException("input file doesn't support reading."); } if (string.IsNullOrEmpty(fileName)) { throw new ArgumentException("filename must be specified."); } if (Path.IsPathRooted(fileName)) { throw new ArgumentException("the fileName must be a relative filename."); } string targetPath = Path.Combine(contentLocation, fileName); FileInfo file = new FileInfo(targetPath); // check if we need to create the directory try { if (file.Directory.Exists == false && String.CompareOrdinal(file.DirectoryName, contentLocation) != 0) { file.Directory.Create(); } } catch (Exception exc) { ErrorTrace.Trace(TraceLevel.Error, exc); throw; } int cnt = 1; // counter to make a unique filename bool saveFile = true; while (file.Exists) { if (FilesAreIdentical(file, inputFile)) { saveFile = false; break; } string newFileName = String.Format("{0}[{1}]{2}", Path.GetFileNameWithoutExtension(file.Name), cnt++, file.Extension ); file = new FileInfo(Path.Combine(file.DirectoryName, newFileName)); } if (saveFile) { using (FileStream fs = file.OpenWrite()) { CopyStream(inputFile, fs); } } string relUri; string absUri = GetAbsoluteFileUri(file.FullName, out relUri); fileName = relUri; return(absUri); }