private void DownloadImage() { Logger.ReportInfo("Fetching image: " + Path); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(Path); req.Timeout = 60000; using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) using (MemoryStream ms = new MemoryStream()) { Stream r = resp.GetResponseStream(); int read = 1; byte[] buffer = new byte[10000]; while (read > 0) { read = r.Read(buffer, 0, buffer.Length); ms.Write(buffer, 0, read); } ms.Flush(); ms.Seek(0, SeekOrigin.Begin); using (var stream = ProtectedFileStream.OpenExclusiveWriter(LocalFilename)) { stream.Write(ms.ToArray(), 0, (int)ms.Length); } } }
private ImageInfo ResizeImage(ImageSet set, int width, int height) { lock (set) { ImageInfo info = new ImageInfo(set); info.Width = width; info.Height = height; info.Date = DateTime.UtcNow; info.ImageFormat = set.PrimaryImage.ImageFormat; set.ResizedImages.Add(info); using (System.Drawing.Bitmap bmp = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromFile(set.PrimaryImage.Path)) using (System.Drawing.Bitmap newBmp = new System.Drawing.Bitmap(width, height)) using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(newBmp)) { graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphic.DrawImage(bmp, 0, 0, width, height); MemoryStream ms = new MemoryStream(); newBmp.Save(ms, info.ImageFormat); using (var fs = ProtectedFileStream.OpenExclusiveWriter(info.Path)) { BinaryWriter bw = new BinaryWriter(fs); bw.Write(ms.ToArray()); } } return(info); } }
public void TestReaderAndWritersPlayNicely() { string file = Path.GetTempFileName(); byte[] contents = new byte[] { 1, 2, 3 }; File.WriteAllBytes(file, contents); for (int i = 0; i < 5; i++) { Repeat(5, true, () => { using (var stream = ProtectedFileStream.OpenSharedReader(file)) { AssertAreEqual(contents, stream.ReadAllBytes()); Thread.Sleep(1); } }); } for (int i = 0; i < 5; i++) { Repeat(5, true, () => { using (var stream = ProtectedFileStream.OpenExclusiveWriter(file)) { stream.Write(contents, 0, contents.Length); Thread.Sleep(1); } }); } }
public override string GetLocalImagePath() { if (!imageIsCached) { return(LocalFilename); } lock (Lock) { if (!isValid && File.Exists(LocalFilename)) { var localInfo = new System.IO.FileInfo(LocalFilename); var remoteInfo = new System.IO.FileInfo(Path); isValid = localInfo.LastWriteTimeUtc > remoteInfo.LastWriteTimeUtc; isValid &= localInfo.Length == remoteInfo.Length; } if (!isValid) { byte[] data = File.ReadAllBytes(Path); using (var stream = ProtectedFileStream.OpenExclusiveWriter(LocalFilename)) { BinaryWriter bw = new BinaryWriter(stream); bw.Write(data); } isValid = true; } return(LocalFilename); } }
// marked internal for testing (perhaps we should use reflection to test) internal void LoadFastLoadData() { FastLoadData data = null; try { using (var stream = ProtectedFileStream.OpenSharedReader(FastLoadFile)) { data = Serializer.Deserialize <object>(stream) as FastLoadData; } } catch (Exception e) { Logger.ReportException("Failed to load fast load data: ", e); } if (data != null && data.Items != null) { lock (dictionary) { foreach (var item in data.Items) { if (!dictionary.ContainsKey(item.Guid)) { dictionary[item.Guid] = new DatedObject() { FileDate = DateTime.MinValue, Data = item.Data }; } } } Logger.ReportInfo("Successfully loaded fastload data for : " + path + " " + typeof(T).ToString()); } }
/// <summary> /// Write current config to file /// </summary> public void Write() { XmlDocument dom = new XmlDocument(); dom.Load(filename); var settingsNode = GetSettingsNode(dom); foreach (var member in SettingMembers(typeof(T))) { var serializer = FindSerializer(member.Type); object v = member.Read(boundObject); if (v == null) { v = defaults[member.Name]; } XmlNode node = settingsNode.SelectSingleNode(member.Name); if (node == null) { /* * var comment = GetComment(member); * if (comment != "") { * settingsNode.AppendChild(dom.CreateComment(comment)); * } */ node = dom.CreateNode(XmlNodeType.Element, member.Name, null); settingsNode.AppendChild(node); } serializer.Write(node, v); } // for each try { using (var pfs = ProtectedFileStream.OpenExclusiveWriter(filename)) { dom.Save(pfs); } saveRetries = 0; //successful save } catch (IOException) { //might have been locked somewhere else - try again saveRetries++; if (saveRetries <= MAX_RETRIES) { System.Threading.Thread.Sleep(10); this.Write(); } else { saveRetries = 0; throw new Exception("Max retries exceeded attempting to save file " + filename); } } }
private void SetData(Guid guid, T value) { var filename = GetFilename(guid); using (var stream = ProtectedFileStream.OpenExclusiveWriter(filename)) { Serializer.Serialize <object>(stream, value); } SetInternalData(guid, value, DateTime.MinValue); }
private static string SaveImage(Image image, string fn) { try { using (var fs = ProtectedFileStream.OpenExclusiveWriter(fn)) { image.Save(fs, image.RawFormat.Equals(ImageFormat.MemoryBmp) ? ImageFormat.Png : image.RawFormat); } } catch (Exception e) { Logger.ReportException("Error saving cache image {0}", e, fn); return(null); } return(fn); }
public void TestReadersHaveConcurrentAccess() { string file = Path.GetTempFileName(); byte[] contents = new byte[] { 1, 2, 3 }; File.WriteAllBytes(file, contents); for (int i = 0; i < 5; i++) { Repeat(5, true, () => { using (var stream = ProtectedFileStream.OpenSharedReader(file)) { AssertAreEqual(contents, stream.ReadAllBytes()); } }); } }
public string CacheImage(Guid id, Image image) { var imageSet = GetOrCreateImageSet(id); lock (imageSet) { if (imageSet != null) { ClearImageSet(imageSet); } ImageInfo info = new ImageInfo(imageSet); info.Width = image.Width; info.Height = image.Height; info.ImageFormat = image.RawFormat.Equals(ImageFormat.MemoryBmp) ? ImageFormat.Png : image.RawFormat; //image was processed - may have transparency info.Date = DateTime.UtcNow; imageSet.PrimaryImage = info; try { using (var fs = ProtectedFileStream.OpenExclusiveWriter(info.Path)) { image.Save(fs, info.ImageFormat); } } catch { try { File.Delete(info.Path); } catch { //cleanup } // weird bug, some images on tvdb will not save as jpegs try { //Logger.ReportVerbose("Saving as png.."); info.ImageFormat = ImageFormat.Png; image.Save(info.Path, ImageFormat.Png); } catch { try { File.Delete(info.Path); } catch { //cleanup } // give up imageSet.PrimaryImage = null; throw; } } return(info.Path); } }
public void TestSystemForgivesExternalBlockers() { string file = Path.GetTempFileName(); byte[] contents = new byte[] { 1, 2, 3 }; File.WriteAllBytes(file, contents); FileStream fs = File.Open(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None); Repeat(1, true, () => { using (var stream = ProtectedFileStream.OpenSharedReader(file)) { AssertAreEqual(contents, stream.ReadAllBytes()); } }); Thread.Sleep(1); fs.Close(); }
/// <summary> /// Acquires the protected file stream, loads the policy information /// </summary> /// <returns>Protected file stream result</returns> public async Task <GetProtectedFileStreamResult> LoadAsync() { if (!IsLoaded) { // Create a ProtectedFileStream to read the contents from the .ptxt or .pjpg file. // Note: if the opened file is not a .ptxt file, the ProtectedFileStream will read it as-is. // So we don't need to write a special case for regular .txt files. var encryptedFileStream = await EncryptedFile.OpenAsync(FileAccessMode.Read); Result = await ProtectedFileStream.AcquireAsync( encryptedFileStream, UserId, AuthenticationCallback, ConsentCallback, PolicyAcquisitionOptions.None); IsLoaded = true; } return(Result); }
private T LoadFile(string path) { var guid = GetGuid(path); if (guid == null) { return(null); } T data = null; try { // we have a guid using (var stream = ProtectedFileStream.OpenSharedReader(path)) { data = Serializer.Deserialize <object>(stream) as T; } if (data == null) { Logger.ReportWarning("Invalid data was detected in the file : " + path); guid = null; } else { DatedObject current; lock (dictionary) { if (dictionary.TryGetValue(guid.Value, out current)) { Serializer.Merge(data, current.Data, true); data = current.Data; } } } } catch (Exception e) { Logger.ReportException("Failed to load date: ", e); } return(data); }
protected void ResizeImage(string source, string destination, int width, int height) { using (System.Drawing.Bitmap bmp = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromFile(source)) using (System.Drawing.Bitmap newBmp = new System.Drawing.Bitmap(width, height)) using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(newBmp)) { graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphic.DrawImage(bmp, 0, 0, width, height); MemoryStream ms = new MemoryStream(); newBmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png); using (var fs = ProtectedFileStream.OpenExclusiveWriter(destination)) { BinaryWriter bw = new BinaryWriter(fs); bw.Write(ms.ToArray()); } } }
private byte[] ReadBytesFromFile(string filename) { using (var stream = ProtectedFileStream.OpenSharedReader(filename)) { return(stream.ReadAllBytes()); } }
private static Stream WriteExclusiveFileStream(string file) { return(ProtectedFileStream.OpenExclusiveWriter(file)); }
public void Validate() { var loadedData = new Dictionary <Guid, T>(); var directory = Kernel.Instance.GetLocation <IFolderMediaLocation>(path); List <Guid> validChildren = new List <Guid>(); foreach (var item in directory.Children.OrderBy(key => key.DateModified).Reverse()) { if (item is IFolderMediaLocation) { continue; } if (item.Path == FastLoadFile) { continue; } var guid = GetGuid(item.Path); DatedObject data; if (guid != null) { lock (dictionary) { if (dictionary.TryGetValue(guid.Value, out data)) { if (data.FileDate == item.DateModified) { validChildren.Add(guid.Value); continue; } } } } T obj = LoadFile(item.Path); if (obj != null) { SetInternalData(guid.Value, obj, item.DateModified); validChildren.Add(guid.Value); } } lock (dictionary) { foreach (var key in dictionary.Keys.Except(validChildren).ToArray()) { dictionary.Remove(key); } } // Save the fastload file FastLoadData fastLoadData; lock (dictionary) { fastLoadData = new FastLoadData() { Items = dictionary.Select(pair => new IdentifiableData() { Guid = pair.Key, Data = pair.Value.Data }) .ToList() }; } using (var stream = ProtectedFileStream.OpenExclusiveWriter(FastLoadFile)) { Serializer.Serialize <object>(stream, fastLoadData); } Logger.ReportInfo("Finished validating : " + path + " " + typeof(T).ToString()); }
public void DownloadFile() { Stream partialInfoStream = null; Stream downloadStream = null; Stream localStream = null; object partialLock = ProtectedFileStream.GetLock(PartialFileName); // someone else is handling the download, exit if (!Monitor.TryEnter(partialLock)) { return; } try { partialInfoStream = new FileStream(PartialFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); localStream = new FileStream(LocalFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read); long totalRead = 0; try { BinaryReader reader = new BinaryReader(partialInfoStream); totalRead = reader.ReadInt64(); } catch { // ignore } WebRequest request = HttpWebRequest.Create(Path); downloadStream = request.GetResponse().GetResponseStream(); try { if (totalRead > 0) { downloadStream.Seek(totalRead, SeekOrigin.Begin); localStream.Seek(totalRead, SeekOrigin.Begin); } } catch { // if stream supports no resume we must restart totalRead = 0; } byte[] buffer = new byte[128 * 1024]; while (true) { int read = downloadStream.Read(buffer, 0, buffer.Length); if (read <= 0) { break; } localStream.Write(buffer, 0, read); partialInfoStream.Seek(0, SeekOrigin.Begin); BinaryWriter bw = new BinaryWriter(partialInfoStream); bw.Write(totalRead); } // at this point we are done. partialInfoStream.Close(); partialInfoStream = null; File.Delete(PartialFileName); } catch (Exception e) { Logger.ReportException("Failed to download podcast!", e); } finally { Monitor.Exit(partialLock); if (partialInfoStream != null) { partialInfoStream.Dispose(); } if (downloadStream != null) { downloadStream.Dispose(); } if (localStream != null) { localStream.Dispose(); } } }
private void FetchImage() { bool sizeIsSet = Size != null && Size.Height > 0 && Size.Width > 0; localPath = localImage.GetLocalImagePath(); if (sizeIsSet) { localPath = localImage.GetLocalImagePath(Size.Width, Size.Height); } if (localImage.Corrupt) { Logger.ReportWarning("Image " + localPath + " is Corrupt."); doneProcessing = true; IsLoaded = true; Microsoft.MediaCenter.UI.Application.DeferredInvoke(_ => { if (afterLoad != null) { afterLoad(); } }); return; } Image newImage = null; if (Kernel.Instance.ConfigData.CacheAllImagesInMemory) { //defunct code.. //if (Kernel.Instance.ConfigData.UseSQLImageCache) //{ // Logger.ReportVerbose("Loading image (from sql): " + localPath); // var imageStream = ImageCache.Instance.GetImageStream(localImage.Id, localImage.Width); // //System.Drawing.Image test = System.Drawing.Image.FromStream(imageStream); // //test.Save("c:\\users\\eric\\my documents\\imagetest\\" + localImage.Id + localImage.Width + ".png"); // //test.Dispose(); // newImage = (Image)ImageFromStream.Invoke(null, new object[] { null, imageStream }); //} //else { Logger.ReportVerbose("Loading image (cacheall true) : " + localPath); byte[] bytes; lock (ProtectedFileStream.GetLock(localPath)) { bytes = File.ReadAllBytes(localPath); } MemoryStream imageStream = new MemoryStream(bytes); imageStream.Position = 0; newImage = (Image)ImageFromStream.Invoke(null, new object[] { null, imageStream }); } } Microsoft.MediaCenter.UI.Application.DeferredInvoke(_ => { if (newImage == null) { //Logger.ReportVerbose("Loading image : " + localPath); string imageRef = "file://" + localPath; newImage = new Image(imageRef); } lock (this) { image = newImage; if (!sizeIsSet) { size = new Size(localImage.Width, localImage.Height); } doneProcessing = true; } IsLoaded = true; if (afterLoad != null) { afterLoad(); } }); }
private static Stream ReadFileStream(string file) { return(ProtectedFileStream.OpenSharedReader(file)); }
/// <summary> /// Read current config from file /// </summary> void Read() { bool stuff_changed = false; XmlDocument dom = new XmlDocument(); XmlNode settingsNode = null; try { using (var data = ProtectedFileStream.OpenSharedReader(filename)) { dom.Load(data); } readRetries = 0; //successful load settingsNode = GetSettingsNode(dom); if (settingsNode == null) { throw new Exception("Corrupt file can not recover"); } } catch (FileNotFoundException) { // corrupt or missing config so create File.WriteAllText(filename, "<Settings></Settings>"); dom.Load(filename); settingsNode = GetSettingsNode(dom); } catch (IOException) { //might be in use somewhere else - retry readRetries++; if (readRetries <= MAX_RETRIES) { System.Threading.Thread.Sleep(10); this.Read(); } else { readRetries = 0; throw new Exception("Max retries exceeded attempting to read file " + filename); } } foreach (AbstractMember member in SettingMembers(typeof(T))) { var serializer = FindSerializer(member.Type); XmlNode node = settingsNode.SelectSingleNode(member.Name); if (node == null) { node = dom.CreateNode(XmlNodeType.Element, member.Name, null); settingsNode.AppendChild(node); serializer.Write(node, defaults[member.Name]); stuff_changed = true; } try { var data = serializer.Read(node, member.Type); member.Write(boundObject, data); } catch (Exception e) { Trace.WriteLine(e.ToString()); serializer.Write(node, defaults[member.Name]); stuff_changed = true; } } if (stuff_changed) { Write(); } }
private void WriteBytesToFile(string filename, byte[] bytes) { using (var stream = ProtectedFileStream.OpenExclusiveWriter(filename)) { stream.Write(bytes, 0, bytes.Length); } }