Search Results

Search found 24 results on 1 pages for 'isolatedstoragefile'.

Page 1/1 | 1 

  • pattern matching in .Net consistent with IsolatedStorageFile.GetFileNames() pattern matching

    - by Mick N
    Is the pattern matching logic used by this API exposed for reuse somewhere in the .Net Framework? Something of the form FilePatternMatch( string searchPattern, stringfileNameToTest ) is what I'm looking for. I'm implementing a temporary workaround for WP7 not filtering the results for this overload and I'd like the solution to both provide a consistent experience and avoid reinventing this functionality if it is exposed. If the behaviour is not exposed for reuse, a regular expression solution (like glob pattern matching in .NET) will suffice and would save me spending the time to test the fine details of what the behaviour should be. Perhaps one of the answers posted in the thread linked above is correct. Since I haven't confirmed the exact behaviour as yet, I wasn't able to determine this at a glance. Feel free to point me to one of those answers if you know it is behaviouraly an exact match to the API referenced in the question title. I could assume the pattern matching is consistent with how DOS handled * and ? in 8.3 file names (I'm familiar with behavioural nuances of that implementation), but it's reasonable to assume Microsoft has evolved pattern matching behaviour for file names in the decade+ since so I thought I would check before proceeding on that assumption.

    Read the article

  • Silverlight 4.0: How to increase quota in Isolated File Storage

    - by xscape
    Got this line of code here but its not working. using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { long newSpace = isf.Quota + spaceRequest; try { if(true == isf.IncreaseQuotaTo(newSpace)) { Debug.WriteLine("success"); } else { Debug.WriteLine("unsuccessful"); } } catch (Exception e) { throw; } }

    Read the article

  • Why does this silverlight code get a "catastrophic failure" when reading a BitmapImage out of Isolat

    - by Edward Tanguay
    In a Silverlight app, I save a Bitmap like this: public static void SaveBitmapImageToIsolatedStorageFile(OpenReadCompletedEventArgs e, string fileName) { using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf)) { Int64 imgLen = (Int64)e.Result.Length; byte[] b = new byte[imgLen]; e.Result.Read(b, 0, b.Length); isfs.Write(b, 0, b.Length); isfs.Flush(); isfs.Close(); isf.Dispose(); } } } and read it back out like this: public static BitmapImage LoadBitmapImageFromIsolatedStorageFile(string fileName) { string text = String.Empty; using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isf.FileExists(fileName)) return null; using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream isoStream = isoStore.OpenFile(fileName, FileMode.Open)) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(isoStream); return bitmapImage; // "Catastrophic Failure: HRESULT: 0x8000FFFF (E_UNEXPECTED))" } } } } but this always gives me a "Catastrophic Failure: HRESULT: 0x8000FFFF (E_UNEXPECTED))" error. I've seen this error before when I tried to read a png file* off a server which was actually a **text file, so I assume the Bitmap is not being saved correctly, I got the code here. Can anyone see how the BitmapImage is not being saved correctly? Or why it would be giving me this error?

    Read the article

  • C# IsolatedStorage Not Working

    - by Don
    I am building a C# .NET (VS2010) IE8 add-on application but am having some trouble saving data using IsolatedStorage. No exceptions occur but, after writing the data, when I try to read the contents back it is blank, and I can find no evidence that it actually saved. Could anyone point out any problems with the following code please that would explain why it doesn't work? //Write IsolatedStorageFile app_isoStore = IsolatedStorageFile.GetStore( IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null); IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream( "app_started.txt", FileMode.OpenOrCreate, FileAccess.Write, app_isoStore); StreamWriter iswriter = new StreamWriter(isoStream); iswriter.WriteLine("Run"); iswriter.Close(); //app_isoStore.Dispose(); app_isoStore.Close(); //Read IsolatedStorageFile app_isoStoreCheck = IsolatedStorageFile.GetStore( IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null); IsolatedStorageFileStream isoReadStream = new IsolatedStorageFileStream( "app_started.txt", FileMode.Open, FileAccess.Read, app_isoStoreCheck); StreamReader isreader = new StreamReader(isoReadStream); string rdata = isreader.ReadToEnd(); isreader.Close(); //app_isoStoreCheck.Dispose(); app_isoStoreCheck.Close(); Should I be using: IsolatedStorageFile.GetStore(IsolatedStorageScope.User| IsolatedStorageScope.Domain|IsolatedStorageScope.Assembly, null,null) instead of: IsolatedStorageFile.GetStore(IsolatedStorageScope.User| IsolatedStorageScope.Assembly, null, null) What's the difference between the two GetStore examples above please?

    Read the article

  • Silverlight with Visual Studio 2010 Isolated Storage Error

    - by Greg Finzer
    I am getting an error when trying to access isolated storage when running a Silverlight unit test project in VS2010. Test method Silverlight_Binary_Serialization_Tests.SerializationTests.SerializeBytesTest threw exception: System.IO.IsolatedStorage.IsolatedStorageException: Unable to determine application identity of the caller. Here is the line it is failing on: private readonly IsolatedStorageFile _store = IsolatedStorageFile.GetUserStoreForApplication();

    Read the article

  • I Get the error message while write data in file --Cannot access the disposable object .Object name

    - by kunal rai
    This was the code: public static void SaveFile(Stream stream, string fileName = "") { using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication()) { IsolatedStorageFileStream fs = file.CreateFile(fileName); var filesize = stream.Length; var getContent = new byte[(int)filesize]; stream.Read(getContent, 0, (int)filesize); fs.Write(getContent, 0, (int)filesize); fs.Close(); } }

    Read the article

  • Silverlight doesn't prompt to increase quota

    - by Sung Meister
    I am trying out Silverlight's Isolated Storage feature. Currently running Silverlight thru ASP.NET page. I have written some code to request an additional storage but I am not being prompted to add more. private void requestButton_Click(object sender, RoutedEventArgs e) { using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) { if (store.AvailableFreeSpace >= 1000*1024) return; long usedSpace = store.Quota - store.AvailableFreeSpace; if (store.IncreaseQuotaTo(usedSpace + 1000*1024)) statusTextBlock.Text = string.Format("Quota has been increased to {0}", store.Quota); else statusTextBlock.Text = "You have denied quota increase... you Inglorious Basterd..."; } } Silverlight's Application Storage tab doeslist the localhost ASP.NET page hosting Silverlight as shown below. According to the screenshot, http://localhost:54389 has 1.0MB of available storage area. Is there a restriction set on localhost websites that a prompt is ignored? What are the required steps for Silverlight to prompt users to increase quota?

    Read the article

  • Is there a better way than this to find out if an IsolatedStorage file exists or not?

    - by Edward Tanguay
    I'm using IsolatedStorage in a Silverlight application for caching, so I need to know if the file exists or not which I do with the following method. I couldn't find a FileExists method for IsolatedStorage so I'm just catching the exception, but it seems to be a quite general exception, I'm concerned it will catch more than if the file doesn't exist. Is there a better way to find out if a file exists in IsolatedStorage than this: public static string LoadTextFromIsolatedStorageFile(string fileName) { string text = String.Empty; using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { try { using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Open, isf)) { using (StreamReader sr = new StreamReader(isfs)) { string lineOfData = String.Empty; while ((lineOfData = sr.ReadLine()) != null) text += lineOfData; } } return text; } catch (IsolatedStorageException ex) { return ""; } } }

    Read the article

  • Is there anyway to reduce IsolatedStorage capacity in Silverlight?

    - by Edward Tanguay
    With this code I can have Silverlight ask the user if he wants to increase IsolatedStorage: private void Button_IncreaseIsolatedStorage_Click(object sender, RoutedEventArgs e) { IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication(); long newStorageCapacityInBytes = FileHelpers.GetMaxiumumSpace() + SystemHelpers.GetAmountOfStorageToIncreaseWhenNeededInBytes(); store.IncreaseQuotaTo(newStorageCapacityInBytes); Message = "IsolatedStorage increased. " + FileHelpers.GetSpaceLeftMessage(); } But if I try to set it to an amount less than it current is, I get an error that this is not possible. 1. Is there a workaround for this, i.e. can I reduce the amount of IsolatedStorage? 2. When the user agrees to increasing IsolatedStorage, can other applications use this capacity or just the application in which he increased it?

    Read the article

  • Confused with the Isolated Storage with Multiple Assemblies Access

    - by Peter Lee
    I googled and searched a lot, but I got no luck. I have a WindowsFormsApplication.exe and ConsoleApplication.exe. I want both of them to access to the same IsolatedStorage, is it possible? I tried using this in ConsoleApplication.exe: IsolatedStorageFile isoStore = IsolatedStorageFile.GetMachineStoreForApplication(); but I got: IsolatedStorageException: Unable to determine application identity of the caller. How can I fix this? Or can I use this way? P.S.: This is NOT a ClickOnce app.

    Read the article

  • Record video file with 'thumbnail' image in Windows phone 8

    - by Deepak
    I'm trying to create a video capturing application store video file with 'thumbnail' image in Windows phone 8. I got some hint from the following link : How to get the thumbnail of a recorded video - windows phone 8?. But the result is quite annoying. I think there is some problem with the function. void captureSource_CaptureImageCompleted(object sender, CaptureImageCompletedEventArgs e) { using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { WriteableBitmap wb = e.Result; string fileName = "CameraMovie.jpg"; if (isoStore.FileExists(fileName)) isoStore.DeleteFile(fileName); IsolatedStorageFileStream file = isoStore.CreateFile(fileName); Extensions.SaveJpeg(wb, file, wb.PixelWidth, wb.PixelHeight, 0, 85); file.Close(); captureSource.Stop(); fileSink.CaptureSource = null; fileSink.IsolatedStorageFileName = null; } } e.Result has some invalid data in it.while i bind it to an image control it shows some annoying image. Anyone please help me.

    Read the article

  • How to save and retrieve data as key-value pairs or files in isolated storage?

    - by kaleidoscope
    One can use isolated storage to store data locally on the user's computer. There are two ways to use isolated storage. The first way is to save or retrieve data as key/value pairs by using the IsolatedStorageSettings class. The second way is to save or retrieve files by using the IsolatedStorageFile class. More details can be found at http://silverlight.net/learn/quickstarts/isolatedstorage/   Rituraj, J

    Read the article

  • Isolated storage misunderstand

    - by Costa
    Hi this is a discussion between me and me to understand isolated storage issue. can you help me to convince me about isolated storage!! This is a code written in windows form app (reader) that read the isolated storage of another win form app (writer) which is signed. where is the security if the reader can read the writer's file, I thought only signed code can access the file! If all .Net applications born equal and have all permissions to access Isolated storage, where is the security then? If I can install and run Exe from isolated storage, why I don't install a virus and run it, I am trusted to access this area. but the virus or what ever will not be trusted to access the rest of file system, it only can access the memory, and this is dangerous enough. I cannot see any difference between using app data folder to save the state and using isolated storage except a long nasty path!! I want to try give low trust to Reader code and retest, but they said "Isolated storage is actually created for giving low trusted application the right to save its state". Reader code: private void button1_Click(object sender, EventArgs e) { String path = @"C:\Documents and Settings\All Users\Application Data\IsolatedStorage\efv5cmbz.ewt\2ehuny0c.qvv\StrongName.5v3airc2lkv0onfrhsm2h3uiio35oarw\AssemFiles\toto12\ABC.txt"; StreamReader reader = new StreamReader(path); var test = reader.ReadLine(); reader.Close(); } Writer: private void button1_Click(object sender, EventArgs e) { IsolatedStorageFile isolatedFile = IsolatedStorageFile.GetMachineStoreForAssembly(); isolatedFile.CreateDirectory("toto12"); IsolatedStorageFileStream isolatedStorage = new IsolatedStorageFileStream(@"toto12\ABC.txt", System.IO.FileMode.Create, isolatedFile); StreamWriter writer = new StreamWriter(isolatedStorage); writer.WriteLine("Ana 2akol we ashrab kai a3eesh wa akbora"); writer.Close(); writer.Dispose(); }

    Read the article

  • How to handle not-enough-isolatedstorage issue deep in data loader?

    - by Edward Tanguay
    I have a silverlight application which loads data from many external data sources into IsolatedStorage, and while loading any of these sources if it does not have enough IsolatedStorage, it ends up in a catch statement. At that point in that catch statement I would like to ask the user to click a button to approve silverlight to increase the IsolatedStorage capacity. The problem is, although I have a "SwitchPage()" method with which I display a page, if I access it at this point it is too deep in the loading process and the application always goes into an endless loop, hangs and crashes. I need a way to branch out of the application completely somehow to an independent UserControl which has a button and code behind which does the increase logic. What is a solution for an application to be able to branch out of a loading process catch statement like this, display a user control which has a button to ask the user to increase the IsolatedStorage? public static void SaveBitmapImageToIsolatedStorageFile(OpenReadCompletedEventArgs e, string fileName) { try { using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf)) { Int64 imgLen = (Int64)e.Result.Length; byte[] b = new byte[imgLen]; e.Result.Read(b, 0, b.Length); isfs.Write(b, 0, b.Length); isfs.Flush(); isfs.Close(); isf.Dispose(); } } } catch (IsolatedStorageException) { //handle: present user with button to increase isolated storage } catch (TargetInvocationException) { //handle: not saved } }

    Read the article

  • Windows Phone 7 development: Using isolated storage

    - by DigiMortal
    In my previous posting about Windows Phone 7 development I showed how to use WebBrowser control in Windows Phone 7. In this posting I make some other improvements to my blog reader application and I will show you how to use isolated storage to store information to phone. Why isolated storage? Isolated storage is place where your application can save its data and settings. The image on right (that I stole from MSDN library) shows you how application data store is organized. You have no other options to keep your files besides isolated storage because Windows Phone 7 does not allow you to save data directly to other file system locations. From MSDN: “Isolated storage enables managed applications to create and maintain local storage. The mobile architecture is similar to the Silverlight-based applications on Windows. All I/O operations are restricted to isolated storage and do not have direct access to the underlying operating system file system. Ultimately, this helps to provide security and prevents unauthorized access and data corruption.” Saving files from web to isolated storage I updated my RSS-reader so it reads RSS from web only if there in no local file with RSS. User can update RSS-file by clicking a button. Also file is created when application starts and there is no RSS-file. Why I am doing this? I want my application to be able to work also offline. As my code needs some more refactoring I provide it with some next postings about Windows Phone 7. If you want it sooner then please leave me a comment here. Here is the code for my RSS-downloader that downloads RSS-feed and saves it to isolated storage file calles rss.xml. public class RssDownloader {     private string _url;     private string _fileName;       public delegate void DownloadCompleteDelegate();     public event DownloadCompleteDelegate DownloadComplete;       public RssDownloader(string url, string fileName)     {         _url = url;         _fileName = fileName;     }       public void Download()     {         var request = (HttpWebRequest)WebRequest.Create(_url);         var result = (IAsyncResult)request.BeginGetResponse(ResponseCallback, request);            }       private void ResponseCallback(IAsyncResult result)     {         var request = (HttpWebRequest)result.AsyncState;         var response = request.EndGetResponse(result);           using(var stream = response.GetResponseStream())         using(var reader = new StreamReader(stream))         using(var appStorage = IsolatedStorageFile.GetUserStoreForApplication())         using(var file = appStorage.OpenFile("rss.xml", FileMode.OpenOrCreate))         using(var writer = new StreamWriter(file))         {             writer.Write(reader.ReadToEnd());         }           if (DownloadComplete != null)             DownloadComplete();     } } Of course I modified RSS-source for my application to use rss.xml file from isolated storage. As isolated storage files also base on streams we can use them everywhere where streams are expected. Reading isolated storage files As isolated storage files are opened as streams you can read them like usual files in your usual applications. The next code fragment shows you how to open file from isolated storage and how to read it using XmlReader. Previously I used response stream in same place. using(var appStorage = IsolatedStorageFile.GetUserStoreForApplication()) using(var file = appStorage.OpenFile("rss.xml", FileMode.Open)) {     var reader = XmlReader.Create(file);                      // more code } As you can see there is nothing complex. If you have worked with System.IO namespace objects then you will find isolated storage classes and methods to be very similar to these. Also mention that application storage and isolated storage files must be disposed after you are not using them anymore.

    Read the article

  • Isolated Storage Made Easy

    In its most simple form Isolated Storage allows you to save name value pairs and retrieve them at some other time the next time your app runs. Granted we could get into XML and text files etc but I'm going to stick with just name value pairs. Lets take a look at this line:private void PresistKeyValue(string _Key, string _Value){StreamWriter MyWriter = new StreamWriter(new IsolatedStorageFileStream(_Key, FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication()));MyWriter.Write(_Value);MyWriter.Close();}Nice...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Does IsolatedStorageFileStream.Lock work under SIlverlight4?

    - by Noah
    Silverlight uses an IsolatedStorageFileStream to open files. The IsolatedStorageFileStreamunder NET.4 claims to support the Lock Method (Inherited from FileStream) The following code IsolatedStorageFile isf; IsolatedStorageFileStream lockStream = new IsolatedStorageFileStream( "my.lck", FileMode.OpenOrCreate, isf ); lockStream.Lock( 0, 0 ); generates the following error, wrapped for readability, under VS2010 and Silverlight 4 'System.IO.IsolatedStorage.IsolatedStorageFileStream' does not contain a definition for 'Lock' and no extension method 'Lock' accepting a first argument of type 'System.IO.IsolatedStorage.IsolatedStorageFileStream' could be found (are you missing a using directive or an assembly reference?)

    Read the article

  • Silverlight isolated storage: what identifies an "application"?

    - by Joe White
    The docs for Silverlight's IsolatedStorageFile.GetUserStoreForApplication just say that the isolated storage is specific to the "application", and that each different application will have its own storage independent of all other "applications" (but with one quota for the entire domain). That's great, but I haven't found anything yet that explains just what "application" is supposed to mean (either in the Silverlight docs or the regular .NET Framework docs). What information does Silverlight, in particular, use to decide that "this is application A" and "this is application B"? Does it just go off the URI to the .xap file, or what?

    Read the article

  • WPF: isolated storage file path too long

    - by user342961
    Hi, I'm deploying my WPF app with ClickOnce. When developing locally in Visual Studio, I store files in the isolated storage by calling IsolatedStorageFile.GetUserStoreForDomain(). This works just fine and the generated path is C:\Users\Frederik\AppData\Local\IsolatedStorage\phqduaro.crw\hux3pljr.cnx\StrongName.kkulk3wafjkvclxpwvxmpvslqqwckuh0\Publisher.ui0lr4tpq53mz2v2c0uqx21xze0w22gq\Files\FilerefData\-581750116 (189 chars) But when I deploy my app with ClickOnce, the generated path becomes too long, resulting in a DirectoryNotFoundException when creating the isolated storage directory. The generated path with ClickOnce is: C:\Users\Frederik\AppData\Local\Apps\2.0\Data\OQ0LNXJT.R5V\8539ABHC.ODN\exqu..tion_e07264ceafd7486e_0001.0000_b8f01b38216164a0\Data\StrongName.wy0cojdd3mpvq45404l3gxdklugoanvi\Publisher.ui0lr4tpq53mz2v2c0uqx21xze0w22gq\Files\FilerefData\-581750116 (247 chars) When I browse the folders all but the last directory of the path exists. Then when trying to create a folder at this location windows tells me I can't create a directory because the resulting path name will be too long. How can I shorten the path generated by the IsolatedStorage?

    Read the article

  • ANTS Memory Profiler 7.0 Review

    - by Michael B. McLaughlin
    (This is my first review as a part of the GeeksWithBlogs.net Influencers program. It’s a program in which I (and the others who have been selected for it) get the opportunity to check out new products and services and write reviews about them. We don’t get paid for this, but we do generally get to keep a copy of the software or retain an account for some period of time on the service that we review. In this case I received a copy of Red Gate Software’s ANTS Memory Profiler 7.0, which was released in January. I don’t have any upgrade rights nor is my review guided, restrained, influenced, or otherwise controlled by Red Gate or anyone else. But I do get to keep the software license. I will always be clear about what I received whenever I do a review – I leave it up to you to decide whether you believe I can be objective. I believe I can be. If I used something and really didn’t like it, keeping a copy of it wouldn’t be worth anything to me. In that case though, I would simply uninstall/deactivate/whatever the software or service and tell the company what I didn’t like about it so they could (hopefully) make it better in the future. I don’t think it’d be polite to write up a terrible review, nor do I think it would be a particularly good use of my time. There are people who get paid for a living to review things, so I leave it to them to tell you what they think is bad and why. I’ll only spend my time telling you about things I think are good.) Overview of Common .NET Memory Problems When coming to land of managed memory from the wilds of unmanaged code, it’s easy to say to one’s self, “Wow! Now I never have to worry about memory problems again!” But this simply isn’t true. Managed code environments, such as .NET, make many, many things easier. You will never have to worry about memory corruption due to a bad pointer, for example (unless you’re working with unsafe code, of course). But managed code has its own set of memory concerns. For example, failing to unsubscribe from events when you are done with them leaves the publisher of an event with a reference to the subscriber. If you eliminate all your own references to the subscriber, then that memory is effectively lost since the GC won’t delete it because of the publishing object’s reference. When the publishing object itself becomes subject to garbage collection then you’ll get that memory back finally, but that could take a very long time depending of the life of the publisher. Another common source of resource leaks is failing to properly release unmanaged resources. When writing a class that contains members that hold unmanaged resources (e.g. any of the Stream-derived classes, IsolatedStorageFile, most classes ending in “Reader” or “Writer”), you should always implement IDisposable, making sure to use a properly written Dispose method. And when you are using an instance of a class that implements IDisposable, you should always make sure to use a 'using' statement in order to ensure that the object’s unmanaged resources are disposed of properly. (A ‘using’ statement is a nicer, cleaner looking, and easier to use version of a try-finally block. The compiler actually translates it as though it were a try-finally block. Note that Code Analysis warning 2202 (CA2202) will often be triggered by nested using blocks. A properly written dispose method ensures that it only runs once such that calling dispose multiple times should not be a problem. Nonetheless, CA2202 exists and if you want to avoid triggering it then you should write your code such that only the innermost IDisposable object uses a ‘using’ statement, with any outer code making use of appropriate try-finally blocks instead). Then, of course, there are situations where you are operating in a memory-constrained environment or else you want to limit or even eliminate allocations within a certain part of your program (e.g. within the main game loop of an XNA game) in order to avoid having the GC run. On the Xbox 360 and Windows Phone 7, for example, for every 1 MB of heap allocations you make, the GC runs; the added time of a GC collection can cause a game to drop frames or run slowly thereby making it look bad. Eliminating allocations (or else minimizing them and calling an explicit Collect at an appropriate time) is a common way of avoiding this (the other way is to simplify your heap so that the GC’s latency is low enough not to cause performance issues). ANTS Memory Profiler 7.0 When the opportunity to review Red Gate’s recently released ANTS Memory Profiler 7.0 arose, I jumped at it. In order to review it, I was given a free copy (which does not include upgrade rights for future versions) which I am allowed to keep. For those of you who are familiar with ANTS Memory Profiler, you can find a list of new features and enhancements here. If you are an experienced .NET developer who is familiar with .NET memory management issues, ANTS Memory Profiler is great. More importantly still, if you are new to .NET development or you have no experience or limited experience with memory profiling, ANTS Memory Profiler is awesome. From the very beginning, it guides you through the process of memory profiling. If you’re experienced and just want dive in however, it doesn’t get in your way. The help items GAHSFLASHDAJLDJA are well designed and located right next to the UI controls so that they are easy to find without being intrusive. When you first launch it, it presents you with a “Getting Started” screen that contains links to “Memory profiling video tutorials”, “Strategies for memory profiling”, and the “ANTS Memory Profiler forum”. I’m normally the kind of person who looks at a screen like that only to find the “Don’t show this again” checkbox. Since I was doing a review, though, I decided I should examine them. I was pleasantly surprised. The overview video clocks in at three minutes and fifty seconds. It begins by showing you how to get started profiling an application. It explains that profiling is done by taking memory snapshots periodically while your program is running and then comparing them. ANTS Memory Profiler (I’m just going to call it “ANTS MP” from here) analyzes these snapshots in the background while your application is running. It briefly mentions a new feature in Version 7, a new API that give you the ability to trigger snapshots from within your application’s source code (more about this below). You can also, and this is the more common way you would do it, take a memory snapshot at any time from within the ANTS MP window by clicking the “Take Memory Snapshot” button in the upper right corner. The overview video goes on to demonstrate a basic profiling session on an application that pulls information from a database and displays it. It shows how to switch which snapshots you are comparing, explains the different sections of the Summary view and what they are showing, and proceeds to show you how to investigate memory problems using the “Instance Categorizer” to track the path from an object (or set of objects) to the GC’s root in order to find what things along the path are holding a reference to it/them. For a set of objects, you can then click on it and get the “Instance List” view. This displays all of the individual objects (including their individual sizes, values, etc.) of that type which share the same path to the GC root. You can then click on one of the objects to generate an “Instance Retention Graph” view. This lets you track directly up to see the reference chain for that individual object. In the overview video, it turned out that there was an event handler which was holding on to a reference, thereby keeping a large number of strings that should have been freed in memory. Lastly the video shows the “Class List” view, which lets you dig in deeply to find problems that might not have been clear when following the previous workflow. Once you have at least one memory snapshot you can begin analyzing. The main interface is in the “Analysis” tab. You can also switch to the “Session Overview” tab, which gives you several bar charts highlighting basic memory data about the snapshots you’ve taken. If you hover over the individual bars (and the individual colors in bars that have more than one), you will see a detailed text description of what the bar is representing visually. The Session Overview is good for a quick summary of memory usage and information about the different heaps. You are going to spend most of your time in the Analysis tab, but it’s good to remember that the Session Overview is there to give you some quick feedback on basic memory usage stats. As described above in the summary of the overview video, there is a certain natural workflow to the Analysis tab. You’ll spin up your application and take some snapshots at various times such as before and after clicking a button to open a window or before and after closing a window. Taking these snapshots lets you examine what is happening with memory. You would normally expect that a lot of memory would be freed up when closing a window or exiting a document. By taking snapshots before and after performing an action like that you can see whether or not the memory is really being freed. If you already know an area that’s giving you trouble, you can run your application just like normal until just before getting to that part and then you can take a few strategic snapshots that should help you pin down the problem. Something the overview didn’t go into is how to use the “Filters” section at the bottom of ANTS MP together with the Class List view in order to narrow things down. The video tutorials page has a nice 3 minute intro video called “How to use the filters”. It’s a nice introduction and covers some of the basics. I’m going to cover a bit more because I think they’re a really neat, really helpful feature. Large programs can bring up thousands of classes. Even simple programs can instantiate far more classes than you might realize. In a basic .NET 4 WPF application for example (and when I say basic, I mean just MainWindow.xaml with a button added to it), the unfiltered Class List view will have in excess of 1000 classes (my simple test app had anywhere from 1066 to 1148 classes depending on which snapshot I was using as the “Current” snapshot). This is amazing in some ways as it shows you how in stark detail just how immensely powerful the WPF framework is. But hunting through 1100 classes isn’t productive, no matter how cool it is that there are that many classes instantiated and doing all sorts of awesome things. Let’s say you wanted to examine just the classes your application contains source code for (in my simple example, that would be the MainWindow and App). Under “Basic Filters”, click on “Classes with source” under “Show only…”. Voilà. Down from 1070 classes in the snapshot I was using as “Current” to 2 classes. If you then click on a class’s name, it will show you (to the right of the class name) two little icon buttons. Hover over them and you will see that you can click one to view the Instance Categorizer for the class and another to view the Instance List for the class. You can also show classes based on which heap they live on. If you chose both a Baseline snapshot and a Current snapshot then you can use the “Comparing snapshots” filters to show only: “New objects”; “Surviving objects”; “Survivors in growing classes”; or “Zombie objects” (if you aren’t sure what one of these means, you can click the helpful “?” in a green circle icon to bring up a popup that explains them and provides context). Remember that your selection(s) under the “Show only…” heading will still apply, so you should update those selections to make sure you are seeing the view you want. There are also links under the “What is my memory problem?” heading that can help you diagnose the problems you are seeing including one for “I don’t know which kind I have” for situations where you know generally that your application has some problems but aren’t sure what the behavior you have been seeing (OutOfMemoryExceptions, continually growing memory usage, larger memory use than expected at certain points in the program). The Basic Filters are not the only filters there are. “Filter by Object Type” gives you the ability to filter by: “Objects that are disposable”; “Objects that are/are not disposed”; “Objects that are/are not GC roots” (GC roots are things like static variables); and “Objects that implement _______”. “Objects that implement” is particularly neat. Once you check the box, you can then add one or more classes and interfaces that an object must implement in order to survive the filtering. Lastly there is “Filter by Reference”, which gives you the option to pare down the list based on whether an object is “Kept in memory exclusively by” a particular item, a class/interface, or a namespace; whether an object is “Referenced by” one or more of those choices; and whether an object is “Never referenced by” one or more of those choices. Remember that filtering is cumulative, so anything you had set in one of the filter sections still remains in effect unless and until you go back and change it. There’s quite a bit more to ANTS MP – it’s a very full featured product – but I think I touched on all of the most significant pieces. You can use it to debug: a .NET executable; an ASP.NET web application (running on IIS); an ASP.NET web application (running on Visual Studio’s built-in web development server); a Silverlight 4 browser application; a Windows service; a COM+ server; and even something called an XBAP (local XAML browser application). You can also attach to a .NET 4 process to profile an application that’s already running. The startup screen also has a large number of “Charting Options” that let you adjust which statistics ANTS MP should collect. The default selection is a good, minimal set. It’s worth your time to browse through the charting options to examine other statistics that may also help you diagnose a particular problem. The more statistics ANTS MP collects, the longer it will take to collect statistics. So just turning everything on is probably a bad idea. But the option to selectively add in additional performance counters from the extensive list could be a very helpful thing for your memory profiling as it lets you see additional data that might provide clues about a particular problem that has been bothering you. ANTS MP integrates very nicely with all versions of Visual Studio that support plugins (i.e. all of the non-Express versions). Just note that if you choose “Profile Memory” from the “ANTS” menu that it will launch profiling for whichever project you have set as the Startup project. One quick tip from my experience so far using ANTS MP: if you want to properly understand your memory usage in an application you’ve written, first create an “empty” version of the type of project you are going to profile (a WPF application, an XNA game, etc.) and do a quick profiling session on that so that you know the baseline memory usage of the framework itself. By “empty” I mean just create a new project of that type in Visual Studio then compile it and run it with profiling – don’t do anything special or add in anything (except perhaps for any external libraries you’re planning to use). The first thing I tried ANTS MP out on was a demo XNA project of an editor that I’ve been working on for quite some time that involves a custom extension to XNA’s content pipeline. The first time I ran it and saw the unmanaged memory usage I was convinced I had some horrible bug that was creating extra copies of texture data (the demo project didn’t have a lot of texture data so when I saw a lot of unmanaged memory I instantly figured I was doing something wrong). Then I thought to run an empty project through and when I saw that the amount of unmanaged memory was virtually identical, it dawned on me that the CLR itself sits in unmanaged memory and that (thankfully) there was nothing wrong with my code! Quite a relief. Earlier, when discussing the overview video, I mentioned the API that lets you take snapshots from within your application. I gave it a quick trial and it’s very easy to integrate and make use of and is a really nice addition (especially for projects where you want to know what, if any, allocations there are in a specific, complicated section of code). The only concern I had was that if I hadn’t watched the overview video I might never have known it existed. Even then it took me five minutes of hunting around Red Gate’s website before I found the “Taking snapshots from your code" article that explains what DLL you need to add as a reference and what method of what class you should call in order to take an automatic snapshot (including the helpful warning to wrap it in a try-catch block since, under certain circumstances, it can raise an exception, such as trying to call it more than 5 times in 30 seconds. The difficulty in discovering and then finding information about the automatic snapshots API was one thing I thought could use improvement. Another thing I think would make it even better would be local copies of the webpages it links to. Although I’m generally always connected to the internet, I imagine there are more than a few developers who aren’t or who are behind very restrictive firewalls. For them (and for me, too, if my internet connection happens to be down), it would be nice to have those documents installed locally or to have the option to download an additional “documentation” package that would add local copies. Another thing that I wish could be easier to manage is the Filters area. Finding and setting individual filters is very easy as is understanding what those filter do. And breaking it up into three sections (basic, by object, and by reference) makes sense. But I could easily see myself running a long profiling session and forgetting that I had set some filter a long while earlier in a different filter section and then spending quite a bit of time trying to figure out why some problem that was clearly visible in the data wasn’t showing up in, e.g. the instance list before remembering to check all the filters for that one setting that was only culling a few things from view. Some sort of indicator icon next to the filter section names that appears you have at least one filter set in that area would be a nice visual clue to remind me that “oh yeah, I told it to only show objects on the Gen 2 heap! That’s why I’m not seeing those instances of the SuperMagic class!” Something that would be nice (but that Red Gate cannot really do anything about) would be if this could be used in Windows Phone 7 development. If Microsoft and Red Gate could work together to make this happen (even if just on the WP7 emulator), that would be amazing. Especially given the memory constraints that apps and games running on mobile devices need to work within, a good memory profiler would be a phenomenally helpful tool. If anyone at Microsoft reads this, it’d be really great if you could make something like that happen. Perhaps even a (subsidized) custom version just for WP7 development. (For XNA games, of course, you can create a Windows version of the game and use ANTS MP on the Windows version in order to get a better picture of your memory situation. For Silverlight on WP7, though, there’s quite a bit of educated guess work and WeakReference creation followed by forced collections in order to find the source of a memory problem.) The only other thing I found myself wanting was a “Back” button. Between my Windows Phone 7, Zune, and other things, I’ve grown very used to having a “back stack” that lets me just navigate back to where I came from. The ANTS MP interface is surprisingly easy to use given how much it lets you do, and once you start using it for any amount of time, you learn all of the different areas such that you know where to go. And it does remember the state of the areas you were previously in, of course. So if you go to, e.g., the Instance Retention Graph from the Class List and then return back to the Class List, it will remember which class you had selected and all that other state information. Still, a “Back” button would be a welcome addition to a future release. Bottom Line ANTS Memory Profiler is not an inexpensive tool. But my time is valuable. I can easily see ANTS MP saving me enough time tracking down memory problems to justify it on a cost basis. More importantly to me, knowing what is happening memory-wise in my programs and having the confidence that my code doesn’t have any hidden time bombs in it that will cause it to OOM if I leave it running for longer than I do when I spin it up real quickly for debugging or just to see how a new feature looks and feels is a good feeling. It’s a feeling that I like having and want to continue to have. I got the current version for free in order to review it. Having done so, I’ve now added it to my must-have tools and will gladly lay out the money for the next version when it comes out. It has a 14 day free trial, so if you aren’t sure if it’s right for you or if you think it seems interesting but aren’t really sure if it’s worth shelling out the money for it, give it a try.

    Read the article

1