XAML to XPS memory leak - wpf

For a windows service project i have to make reports in xps format. I have xaml code that i turn into an xps document:
private void th_PrintErrorReport(OrderReportData reportData)
{
...
//Use the XAML reader to create a FlowDocument from the XAML string.
FlowDocument document = XamlReader.Load(new XmlTextReader(new StringReader(vRawXaml))) as FlowDocument;
//create xps file
using (XpsDocument xpsDoc = new XpsDocument(vFilePath, System.IO.FileAccess.Write, CompressionOption.Maximum))
{
// create a serialization manager
using (XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false))
{
// retrieve document paginator
DocumentPaginator paginator = ((IDocumentPaginatorSource)document).DocumentPaginator;
// save as XPS
rsm.SaveAsXaml(paginator);
rsm.Commit();
}
}
}
This works but unfortunately creates a memory leak, each report created leaves the wpf controls (contentpresent, labels, etc) in memory. I checked this with a memory profiler. I checked topics like this one and this one which made me think that the wpf dispatcher/message pump is the problem. To make the message pump run i changed my code to:
public void StartHandling()
{
_ReportPrintingActive = true;
//xaml parsing has to run on a STA thread
_ReportPrintThread = new Thread(th_ErrorReportHandling);
_ReportPrintThread.SetApartmentState(ApartmentState.STA);
_ReportPrintThread.Name = "ErrorReportPrinter";
_ReportPrintThread.Start();
}
private void th_ErrorReportHandling()
{
Dispatcher.Run();
}
public void PrintErrorReport(OrderReportData reportData)
{
Action action = () =>
{
th_PrintErrorReport(reportData);
};
Dispatcher.FromThread(_ReportPrintThread).BeginInvoke(action);
}
But still no success. What am i missing ?

Using the reflection code from this post made the memory leak go away : https://stackoverflow.com/a/2410588/687462

Related

How to execute a Revit IExternalCommand from a WPF button?

I am in need of help.
I have created a dockable WPF within Revit.
It is working well and I can 'show' & ;hide' from push buttons.
My aim is to create buttons within the WPF that run custom commands.I dont need to interact or show any information within the WPF, its purely just acting as a push button but in the WPF instead of a ribbon.
The commands currently work and can be executed via the Add-In Manager.
Below is the command I am trying to run:
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using System.Collections.Generic;
using System.Linq;
namespace Adams.Commands
{
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
public class PrecastDisallowJoin : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
var uiApplication = commandData.Application;
var application = uiApplication.Application;
var uiDocument = uiApplication.ActiveUIDocument;
var document = uiDocument.Document;
// Prompt the user to select some walls
var references = uiDocument.Selection
.PickObjects(
ObjectType.Element,
new WallSelectionFilter(),
"Please select walls");
var components = references.Select(r => document.GetElement(r)).ToList();
// Start a transaction
using (Transaction t = new Transaction(document, "Change Wall Join Behavior"))
{
t.Start();
// Loop through the selected walls and change their join behavior
foreach (Reference reference in references)
{
Wall wall = document.GetElement(reference) as Wall;
WallUtils.DisallowWallJoinAtEnd(wall, 0);
WallUtils.DisallowWallJoinAtEnd(wall, 1);
}
// Commit the transaction
t.Commit();
}
return Result.Succeeded;
}
public class WallSelectionFilter : ISelectionFilter
{
public bool AllowElement(Element elem)
{
//return elem is FamilyInstance;
return elem.Name.Contains("Precast");
}
public bool AllowReference(Reference reference, XYZ position)
{
return true;
}
}
}
}
My XAML.cs looks like this:
using Autodesk.Revit.UI;
using System.Windows.Controls;
using Adams.Commands;
using System.Windows;
namespace Adams.ui
{
public partial class Customers : UserControl
{
public UIDocument uIDocument { get; }
public ExternalCommandData commandData { get; }
public Customers(UIDocument uIDocument )
{
InitializeComponent();
}
private void btnStartExcelElementsApp_Click(object sender, RoutedEventArgs e)
{
string message = string.Empty;
PrecastDisallowJoin precastDisallow = new PrecastDisallowJoin();
precastDisallow.Execute(commandData, ref message, null);
}
}
}
Any ideas of what i should be trying?
I'm new to creating add-ins and appreciate any help offered.
If I have missed any critical info please let me know.
Thank you all
When I tried the above it crashes Revit.
Im not sure how to pass the required information in the Execute method in the XAML.
The Revit dockable dialogue and hence your WPF form lives in a modeless context. It does not execute within a valid Revit API context. A valid Revit API context is only provided by Revit itself, within the event handlers called by Revit when specific events are raised. For instance, clicking a button to launch an add-in external command raises the IExternalCommand.Execute event.
The Building Coder shares a long list of articles on Idling and External Events for Modeless Access and Driving Revit from Outside
explaining how to gain access to a valid Revit API context from a modeless state.
You can address your task by using an external event:
Idling Enhancements and External Events
External Command Lister and Adding Ribbon Commands
External Event and 10 Year Forum Anniversary
Implementing the TrackChangesCloud External Event
Vipassana and Idling versus External Events
The question has also been discussed many times in the Revit API discussion forum, so you can check there for threads including WPF, dockable and external event.
You can use IExternalEventHandler:
public class MyExternalEvent : IExternalEventHandler
{
public void Execute(UIApplication app)
{
//do your revit related stuff here
}
public string GetName()
{
return "xxx";
}
}
Create external event:
ExternalEvent myExEvent= ExternalEvent.Create(new MyExternalEvent());
In order to effectively use the above you will have to hold reference to "myExEvent" in some ViewModelClass then you will be able to raise this event inside your xaml.cs:
ViewModelClass.TheEvent = myExEvent;
ViewModelClass.TheEvent.Raise();
EDIT: What you were trying to do is unfortunately not acceptable with revit API. WPF window displayed as dockpanel does not have access to valid revit api context. IExternalEventHandler gives you the possibility to somehow link dockpanel user interface with revit api.

Accessing document elements when using Windows.Forms.WebBrowser

I'm new to automating webpage access, so forgive what is probably a remedial question. I'm using C#/Windows.Forms in a console app. I need to programmatically enter the value of an input on a webpage that I cannot modify and that is running javascript. I have successfully opened the page (triggering WebBrowser.DocumentCompleted). I set browser emulation mode to IE11 (in registry), so scripts run without errors. When DocumentCompleted() triggers, I am unable to access the document elements without first viewing the document content via MessageBox.Show(), which is clearly not acceptable for my unattended app.
What do I need to do so that my document elements are accessbile in an unattended session (so I can remove MessageBox.Show() from the code below)? Details below. Thank you.
The input HTML is:
<input class="input-class" on-keyup="handleKeyPress($key)" type="password">
My DocumentCompleted event handler is:
private static void LoginPageCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wb = ((WebBrowser)sender);
var document = wb.Document;
// I'm trying to eliminate these 3 lines
var documentAsIHtmlDocument = (mshtml.IHTMLDocument)document.DomDocument;
var content = documentAsIHtmlDocument.documentElement.innerHTML;
MessageBox.Show(content);
String classname = null;
foreach (HtmlElement input in document.GetElementsByTagName("input"))
{
classname = input.GetAttribute("className");
if (classname == "input-class")
{
input.SetAttribute("value", password);
break;
}
}
}
The problem for me was that the page I'm accessing is being created by javascript. Even though documentComplete event was firing, the page was still not completely rendered. I have successfully processed the first page by waiting for the document elements to be available and if not available, doing Application.DoEvents(); in a loop until they are, so I know now that I'm on the right track.
This SO Question helped me: c# WebBrowser- How can I wait for javascript to finish running that runs when the document has finished loading?
Note that checking for DocumentComplete does not accurately indicate the availability of the document elements on a page generated by javascript. I needed to keep checking for the elements and running Application.DoEvents() until they became available (after the javascript generated them).
If the problem comes from the creation of a STAThread, necessary to instantiate the underlying Activex component of WebBrowser control, this is
a modified version of Hans Passant's code as shown in the SO Question you linked.
Tested in a Console project.
class Program
{
static void Main(string[] args)
{
NavigateURI(new Uri("[SomeUri]", UriKind.Absolute), "SomePassword");
Console.ReadLine();
}
private static string SomePassword = "SomePassword";
private static void NavigateURI(Uri url)
{
Thread thread = new Thread(() => {
WebBrowser browser = new WebBrowser();
browser.DocumentCompleted += browser_DocumentCompleted;
browser.Navigate(url);
Application.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
protected static void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser browser = ((WebBrowser)sender);
if (browser.Url == e.Url)
{
while (browser.ReadyState != WebBrowserReadyState.Complete)
{ Application.DoEvents(); }
HtmlDocument Doc = browser.Document;
if (Doc != null)
{
foreach (HtmlElement input in Doc.GetElementsByTagName("input"))
{
if (input.GetAttribute("type") == "password")
{
input.InnerText = SomePassword;
//Or
//input.SetAttribute("value", SomePassword);
break;
}
}
}
Application.ExitThread();
}
}
}

CefSharp.Wpf: Open csv, mailto and pdf with Process.Start(...)

I need to handle different content types from f:///. My application renders offline websites in a WPF application. Everything is working except for links to other content files (csv, mailto and pdf).
If I register a CefCustomScheme for "mailto", then I get the ProcessRequestAsync and can run the Process.Start(...). However another blank window also popup.
If I then add a second CefCustomScheme for "file", then nothing happens. None of the ISchemeHandler ProcessRequestAsync methods are invoked.
I must be able to handle all requests, excluding *.html, in a separate handler
Essentially I just want to replicate the behavior of the MS Web-browser Control. There all I did was point to the entry page (index.htm), and everything loaded. Then if a user clicks any link, the control handled the action and started the correct process (content handler, i.e. Excel for Csv).
The code:
// Startup
var settings = new CefSettings();
settings.LogFile = #"c:\temp\ceflog.txt";
settings.LogSeverity = LogSeverity.Verbose;
settings.IgnoreCertificateErrors = true;
CefCustomScheme mailtoScheme = new CefCustomScheme();
mailtoScheme.SchemeName = "mailto";
mailtoScheme.SchemeHandlerFactory = new SchemeHandlerFactory();
CefCustomScheme filesScheme = new CefCustomScheme();
mailtoScheme.SchemeName = "file";
mailtoScheme.SchemeHandlerFactory = new SchemeHandlerFactory();
settings.RegisterScheme(mailtoScheme);
settings.RegisterScheme(filesScheme);
if (!Cef.Initialize(settings))
throw new InvalidOperationException("Failed to initialize the browser factory");
-- SchemeHandlerFactory
public class SchemeHandlerFactory : ISchemeHandlerFactory {
public ISchemeHandler Create() {
return new CustomSchemeHandler();
}
}
-- Handler
public class CustomSchemeHandler : ISchemeHandler {
private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public bool ProcessRequestAsync(IRequest request, ISchemeHandlerResponse response, OnRequestCompletedHandler requestCompletedCallback) {
_log.DebugFormat("Processing url: {0}", request.Dump());
var knownContentTypes = new[] {".csv", ".xsls", ".xlsx", ".pdf", ".txt"};
var ext=Path.GetExtension(request.Url);
if(knownContentTypes.Contains(ext)) {
_log.DebugFormat("Starting process for: {0}",request.Url);
Process.Start(request.Url);
return false;
}
return true;
}
The solution was to implement an IRequestHandler and use the OnBeforeResourceLoad event to check what content was requested. The ISchemeHandler is used for the "mailto" actions.
In my case I had to assign the request handler after the frame loaded. This allowed the web browser to render all content first.
Code sample GitHub example

System.Windows.Controls.WebBrowser, System.Windows.Threading.Dispatcher, and a windows service

I'm trying to render some html content to a bitmap in a Windows Service.
I'm using System.Windows.Controls.WebBrowser to perform the render. The basic rendering setup works as a standalone process with a WPF window hosting the control, but as a service, at least I'm not getting the LoadCompleted events to fire.
I know that I at least need a Dispatcher or other message pump looping for this WPF control. Perhaps I'm doing it right and there are just additional tricks/incompatibilities necessary for the WebBrowser control. Here's what I've got:
I believe only one Dispatcher needs to be running and that it can run for the life of the service. I believe the Dispatcher.Run() is the actual loop itself and thus needs it's own thread which it can otherwise block. And that thread needs to be [STAThread] in this scenario. Therefore, in a relevant static constructor, I have the following:
var thread = new Thread(() =>
{
dispatcher = Dispatcher.CurrentDispatcher;
Dispatcher.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
where dispatcher is a static field. Again, I think there can only be one but I'm not sure if I'm supposed to be able use Dispatcher.CurrentDispatcher() from anywhere instead and get the right reference.
The rendering operation is as follows. I create, navigate, and dispose of the WebBrowser on dispatcher's thread, but event handler assignments and mres.Wait I think may all happen on the render request-handling operation. I had gotten The calling thread cannot access this object because a different thread owns it but now with this setup I don't.
WebBrowser wb = null;
var mres = new ManualResetEventSlim();
try
{
dispatcher.Invoke(() => { wb = new WebBrowser(); });
wb.LoadCompleted += (s, e) =>
{
// Not firing
};
try
{
using (var ms = new MemoryStream())
using (var sw = new StreamWriter(ms, Encoding.Unicode))
{
sw.Write(html);
sw.Flush();
ms.Seek(0, SeekOrigin.Begin);
// GO!
dispatcher.Invoke(() =>
{
try
{
wb.NavigateToStream(ms);
Debug.Assert(Dispatcher.FromThread(Thread.CurrentThread) != null);
}
catch (Exception ex)
{
// log
}
});
if (!mres.Wait(15 * 1000)) throw new TimeoutException();
}
}
catch (Exception ex)
{
// log
}
}
finally
{
dispatcher.Invoke(() => { if (wb != null) wb.Dispose(); });
}
When I run this, I get my timeout exception every time since the LoadCompleted never fires. I've tried to verify that the dispatcher is running and pumping properly. Not sure how to do that, but I hooked a few of the dispatcher's events from the static constructor and I get some printouts from that, so I think it's working.
The code does get to a wb.NavigateToStream(ms); breakpoint.
Is this bad application of Dispatcher? Is the non-firing of wb.LoadCompleted due to something else?
Thanks!
Here's a modified version of your code which works as a console app. A few points:
You need a parent window for WPF WebBrowser. It may be a hidden window like below, but it has to be physically created (i.e. have a live HWND handle). Otherwise, WB never finishes loading the document (wb.Document.readyState == "interactive"), and LoadCompleted never gets fired. I was not aware of such behavior and it is different from the WinForms version of WebBrowser control. May I ask why you picked WPF for this kind of project?
You do need to add the wb.LoadCompleted event handler on the same thread the WB control was created (the dispatcher's thread here). Internally, WPF WebBrowser is just a wrapper around apartment-threaded WebBrowser ActiveX control, which exposes its events via IConnectionPointContainer interface. The rule is, all calls to an apartment-threaded COM object must be made on (or proxied to) the thread the object was originally created on, because that's what such kind of objects expect. In that sense, IConnectionPointContainer methods are no different to other methods of WB.
A minor one, StreamWriter automatically closes the stream it's initialized with (unless explicitly told to not do so in the constructor), so there is no need to for wrapping the stream with using.
The code is ready to compile and run (it requires some extra assembly references: PresentationFramework, WindowsBase, System.Windows, System.Windows.Forms, Microsoft.mshtml).
using System;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Windows;
using System.Windows.Threading;
using System.Windows.Controls;
using System.IO;
using System.Runtime.InteropServices;
using mshtml;
namespace ConsoleWpfApp
{
class Program
{
static Dispatcher dispatcher = null;
static ManualResetEventSlim dispatcherReady = new ManualResetEventSlim();
static void StartUIThread()
{
var thread = new Thread(() =>
{
Debug.Print("UI Thread: {0}", Thread.CurrentThread.ManagedThreadId);
try
{
dispatcher = Dispatcher.CurrentDispatcher;
dispatcherReady.Set();
Dispatcher.Run();
}
catch (Exception ex)
{
Debug.Print("UI Thread exception: {0}", ex.ToString());
}
Debug.Print("UI Thread exits");
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
static void DoWork()
{
Debug.Print("Worker Thread: {0}", Thread.CurrentThread.ManagedThreadId);
dispatcherReady.Wait(); // wait for the UI tread to initialize
var mres = new ManualResetEventSlim();
WebBrowser wb = null;
Window window = null;
try
{
var ms = new MemoryStream();
using (var sw = new StreamWriter(ms, Encoding.Unicode)) // StreamWriter automatically closes the steam
{
sw.Write("<b>Hello, World!</b>");
sw.Flush();
ms.Seek(0, SeekOrigin.Begin);
// GO!
dispatcher.Invoke(() => // could do InvokeAsync here as then we wait anyway
{
Debug.Print("Invoke Thread: {0}", Thread.CurrentThread.ManagedThreadId);
// create a hidden window with WB
window = new Window()
{
Width = 0,
Height = 0,
Visibility = System.Windows.Visibility.Hidden,
WindowStyle = WindowStyle.None,
ShowInTaskbar = false,
ShowActivated = false
};
window.Content = wb = new WebBrowser();
window.Show();
// navigate
wb.LoadCompleted += (s, e) =>
{
Debug.Print("wb.LoadCompleted fired;");
mres.Set(); // singal to the Worker thread
};
wb.NavigateToStream(ms);
});
// wait for LoadCompleted
if (!mres.Wait(5 * 1000))
throw new TimeoutException();
dispatcher.Invoke(() =>
{
// Show the HTML
Console.WriteLine(((HTMLDocument)wb.Document).documentElement.outerHTML);
});
}
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
}
finally
{
dispatcher.Invoke(() =>
{
if (window != null)
window.Close();
if (wb != null)
wb.Dispose();
});
}
}
static void Main(string[] args)
{
StartUIThread();
DoWork();
dispatcher.InvokeShutdown(); // shutdown UI thread
Console.WriteLine("Work done, hit enter to exit");
Console.ReadLine();
}
}
}
Maybe the Webbrowser Control needs Desktop Interaction for rendering the content:
My feeling say that using WPF controls and in particular particulary the Webbrowser-Control (=Wrapper around the IE ActiveX control) isn't the best idea.. There are other rendering engines that might be better suited for this task: Use chrome as browser in C#?

How do I cache images on the client for a WPF application?

We are developing a WPF desktop application that is displaying images that are currently being fetched over HTTP.
The images are already optimised for quality/size but there is an obvious wait each time that the image is fetched.
Is there a way to cache images on the client so that they aren't downloaded each time?
I know this question is very old, but I had to use caching recently in a WPF application and found that there is a much better option in .Net 3.5 with BitmapImage by setting UriCachePolicy, that will use system-level caching:
<Image.Source>
<BitmapImage UriCachePolicy="Revalidate"
UriSource="https://farm3.staticflickr.com/2345/2077570455_03891081db.jpg"/>
</Image.Source>
You can even set the value in the app.config to make all your app use a default value for caching:
<system.net>
<requestCaching defaultPolicyLevel="CacheIfAvailable"/>
</system.net>
You will find an explanation of the RequestCacheLevel values here: http://msdn.microsoft.com/en-us/library/system.net.cache.requestcachelevel(v=vs.110).aspx
This functionality understands HTTP/1.1 headers, so if you set Revalidate it uses If-Modified-Since header to avoid downloading it each time, but still checking if the image has been changed so you always have the correct one.
For people coming here via Google, I have packaged the original implementation that Simon Hartcher posted, refactored by Jeroen van Langen (along with the tweaks from Ivan Leonenko to make it bindable), into an Open Source NuGet package.
Please find the details here - http://floydpink.github.io/CachedImage/
i've read your blog, and that brought me to this (i think much easier) concept setup:
As you will noticed, i reused some of your code you shared, so i'll share mine back.
Create a new custom control called CachedImage.
public class CachedImage : Image
{
private string _imageUrl;
static CachedImage()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CachedImage), new FrameworkPropertyMetadata(typeof(CachedImage)));
}
public string ImageUrl
{
get
{
return _imageUrl;
}
set
{
if (value != _imageUrl)
{
Source = new BitmapImage(new Uri(FileCache.FromUrl(value)));
_imageUrl = value;
}
}
}
}
Next i've made a FileCache class (so i have control on all caching not only images)
public class FileCache
{
public static string AppCacheDirectory { get; set; }
static FileCache()
{
// default cache directory, can be changed in de app.xaml.
AppCacheDirectory = String.Format("{0}/Cache/", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
}
public static string FromUrl(string url)
{
//Check to see if the directory in AppData has been created
if (!Directory.Exists(AppCacheDirectory))
{
//Create it
Directory.CreateDirectory(AppCacheDirectory);
}
//Cast the string into a Uri so we can access the image name without regex
var uri = new Uri(url);
var localFile = String.Format("{0}{1}", AppCacheDirectory, uri.Segments[uri.Segments.Length - 1]);
if (!File.Exists(localFile))
{
HttpHelper.GetAndSaveToFile(url, localFile);
}
//The full path of the image on the local computer
return localFile;
}
}
Also for downloading content I made a helper class:
public class HttpHelper
{
public static byte[] Get(string url)
{
WebRequest request = HttpWebRequest.Create(url);
WebResponse response = request.GetResponse();
return response.ReadToEnd();
}
public static void GetAndSaveToFile(string url, string filename)
{
using (FileStream stream = new FileStream(filename, FileMode.Create, FileAccess.Write))
{
byte[] data = Get(url);
stream.Write(data, 0, data.Length);
}
}
}
The HttpHelper uses an extension on the WebResponse class for reading the result to an array
public static class WebResponse_extension
{
public static byte[] ReadToEnd(this WebResponse webresponse)
{
Stream responseStream = webresponse.GetResponseStream();
using (MemoryStream memoryStream = new MemoryStream((int)webresponse.ContentLength))
{
responseStream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
}
Now you got it complete, lets use it in xaml
<Grid>
<local:CachedImage ImageUrl="http://host/image.png" />
</Grid>
That's all, it's reusable and robust.
The only disadvance is, that the image is never downloaded again until you cleanup the cache directory.
The first time the image is downloaded from the web and saved in the cache directory.
Eventually the image is loaded from the cache and assign to the source of the parent class (Image).
Kind regards,
Jeroen van Langen.
I have solved this by creating a Binding Converter using the IValueConverter interface. Given that I tried to find a solid solution for this for at least a week, I figured I should share my solution for those with this problem in the future.
Here is my blog post: Image Caching for a WPF Desktop Application
If you're just trying to cache within the same run, then a local dictionary could function as a runtime cache.
If you're trying to cache between application runs, it gets trickier.
If this is a desktop application, just save the cached images locally in the user's application data folder.
If it's an XBAP application (WPF in Browser), you'll only be able to setup a local cache in the user's Isolated Storage, due to security.
Based on this I made custom control which:
can download images asynchronously and get them from cache if image
is thread safe
was downloaded has dependency property to which you can bind to
update images, providing new names in initial feed (don’t forget to maintain cache clean operation, e.g. you can parse your feed
and asynchronously delete images with no links in feed)
I made a blog post:, and here's the code:
public class CachedImage : Image
{
static CachedImage()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CachedImage), new FrameworkPropertyMetadata(typeof(CachedImage)));
}
public readonly static DependencyProperty ImageUrlProperty = DependencyProperty.Register("ImageUrl", typeof(string), typeof(CachedImage), new PropertyMetadata("", ImageUrlPropertyChanged));
public string ImageUrl
{
get
{
return (string)GetValue(ImageUrlProperty);
}
set
{
SetValue(ImageUrlProperty, value);
}
}
private static readonly object SafeCopy = new object();
private static void ImageUrlPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var url = (String)e.NewValue;
if (String.IsNullOrEmpty(url))
return;
var uri = new Uri(url);
var localFile = String.Format(Path.Combine(Globals.CacheFolder, uri.Segments[uri.Segments.Length - 1]));
var tempFile = String.Format(Path.Combine(Globals.CacheFolder, Guid.NewGuid().ToString()));
if (File.Exists(localFile))
{
SetSource((CachedImage)obj, localFile);
}
else
{
var webClient = new WebClient();
webClient.DownloadFileCompleted += (sender, args) =>
{
if (args.Error != null)
{
File.Delete(tempFile);
return;
}
if (File.Exists(localFile))
return;
lock (SafeCopy)
{
File.Move(tempFile, localFile);
}
SetSource((CachedImage)obj, localFile);
};
webClient.DownloadFileAsync(uri, tempFile);
}
}
private static void SetSource(Image inst, String path)
{
inst.Source = new BitmapImage(new Uri(path));
}
}
Now you can bind to it:
<Cache:CachedImage ImageUrl="{Binding Icon}"/>
Just a update from Jeroen van Langen reply,
You can save a bunch of line
remove HttpHelper class and the WebResponse_extension
replace
HttpHelper.GetAndSaveToFile(url, localFile);
by
WebClient webClient = new WebClient();
webClient.DownloadFile(url, localFile);
This cachedImage works great, but..
Any advice on how I could use the same cached image type capability for ImageSource for an ImageBrush?
<Rectangle
Width="32"
Height="32"
Margin="2,1"
RadiusX="16"
RadiusY="16"
RenderOptions.BitmapScalingMode="HighQuality">
<Rectangle.Fill>
<ImageBrush ImageSource="{Binding Image}" />
</Rectangle.Fill>
</Rectangle>
Note there may be a better way to do rounded images (for say profile images)

Resources