Monday 24 September 2012

Silverlight - Local File System Access


I just made a quick test if the local file System can be accessed by Silverlight 5.0 In- Browser application and Out-of-Browser.

Good news is yes; now its possible in both the cases. Only requirement is you should check the require elevated trust while running In Browser or Out of Browser.

Find attached the sample application - Here I am accessing My Pictures. So to see something create folder here and copy some images. You should the screen like below -



Note: 
1. Earlier to Silverlight 5 i.e Silverlight 4 : If Silverlight is running within the browser or Out-Of-Browser in normal mode, then file access is limited to usage of theOpenFileDialog and SaveFileDialog controls. In both cases, the user is presented with a prompt to load (or save) a file, and the Silverlight application only has access to the file’s stream containing it’s data, not to the file structure itself.

2. It was only limited to trusted location like My Documents folder, means it was only possible to read/write in My Documents if application is running Out-of-Browser. Now using Silverlight 5 you can do such operation in any files or folders.

3. Also, befor silverlight 5.0 require elevated trust was available only with the Out-of-Browser.

Sunday 23 September 2012

XDocument in Silverlight

When working with data, it often comes in an XML format. So we have to serialize and deserialize it in order to use it. There are several ways of doing that – for example: DOM, XQuery, XSLT. DOM is the oldest from the three, but still can do the work. XQuery and XSLT are not very easy to use and require some time to master. In .NET 3.5 a big programming model improvement was made with the LINQ - Language-Integrated Query. It can be used for objects, databases and XML.

Introduction

LINQ to XML allows us to create, read and edit XML files and what’s more important - it’s done in a very easy and understandable way. To use LINQ to XML you should add a reference to the System.Xml.Linq.dll (for the XDocument and the other classes) and use the System.Linq namespace (for the LINQ syntax).

Important methods of XElement and XDocument

  • Add(object content) – adds the new content as a child of the element
  • Remove() – Remove this element from its parent
  • Descendents( XName name ) – returns a collection of all descendents of this element, which names match the argument, in document order
  • Element( XName name ) – returns the first child that has a matching name
  • Elements( XName name ) - returns a collection of all children of this element, which name matches the argument, in document order
  • Nodes() – returns a collection of all children of the current element in document order

Creating an XML file

So let’s have a simple class Person:
 public class Person
 {
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public Location Address { get; set; }
 }
 
 public class Location
 {
      public string Country { get; set; }
      public string City { get; set; }
  }
And we create an object of type Person:
 Person p1 = new Person()
             {
                 FirstName = "Martin",
                 LastName = "Mihaylov",
                 Address = new Location()
                 {
                     City = "Sofia",
                     Country = "Bulgaria"
                 }
              };
Now let’s try to create an XML from it. For that purpose we use XElement and XAttribute objects:
 XElement persons =
         new XElement( "persons",
             new XElement( "person",
                 new XElement( "firstName", p1.FirstName ),
                 new XElement( "lastName", p1.LastName ),
                 new XElement( "address",
                     new XAttribute( "city", p1.Address.City ),
                     new XAttribute( "country", p1.Address.Country ) ) ) );
We simply create an element “persons” using the XElement object and then nest other elements in it. We can also create properties for the elements thanks to the XAttribute object. We can also use the XDeclaration object to define our xml document and XComment to add a comment to the xml document. Here it is:
 XDocument myXml = new XDocument( new XDeclaration( "1.0", "utf-8", "yes" ),
                 new XComment( "A Comment in the XML" ), persons );
So the final output should look like this:
 <?xml version="1.0" encoding="utf-8" standalone="yes"?>
 <!-- A Comment in the XML -->
 <persons>
     <person>
           <firstName>Martin</firstName>
           <lastName>Mihaylov</lastName>
           <address city="Sofia" country="Bulgaria" />
     </person>
 </persons>

 

Adding an element to the XDocument

First we find the element we want to add something to and then we use its Add method to add our new element. Here is an example:
 myXml.Element( "persons" ).Add( new XElement( "person",
                         new XElement( "firstName", p2.FirstName ),
                         new XElement( "lastName", p2.LastName ),
                         new XElement( "address",
                             new XAttribute( "city", p2.Address.City ),
                             new XAttribute( "country", p2.Address.Country ) ) ) );

 

Removing an element form the XDocument

To remove an element or attribute you must navigate to the desired element and then call its Remove method:
 myXml.Element( "persons" ).Element( "person" ).Remove();
This will remove the first element with name “person” in “persons”.

Reading an XML file

Before reading you should load your XML file to an XElement or XDocument object. This can be done with the Load method. You can input from string, from TextReader, from XMLReader and of course from file. Here is an Example:
 XDocument myXML = XDocument.Load( "MyXML.xml" );
Now let’s try to read the contents of an XML file. For this example we use the XML string we’ve already created in the beginning of the article. Thanks to LINQ we can use the standard query operators: from, in, select. Because of that to take the information you need from an XML file becomes fairly easy:
 List<Person> personsList =
             ( from person in myXml.Descendants( "person" )
              where (( string )person.Element( "address" ).Attribute( "country" )).Equals( "Bulgaria" )
              select new Person()
                  {
                      FirstName = person.Element( "firstName" ).Value,
                      LastName = person.Element( "lastName" ).Value,
                      Address = new Location()
                      {
                           City = person.Element( "address" ).Attribute( "city" ).Value,
                           Country = person.Element( "address" ).Attribute( "country" ).Value
                       }
                   } ).ToList();
The Descendants method returns all child elements that have name “person” (in our case). Then from each descendent that has an "address" element with "country" property set to "Bulgaria" we create a new object of type Person and set its properties. The output is a list of objects.

Query your data

Notice how it uses the XDocument.Descendants() method. That method looks through the XDocument and all of its child nodes - the descendants - and returns them in document order. When you pass it a name, it filters the list.
One important thing to keep in mind about XDocument.Descendants() is that is uses deferred execution. That means it returns a sequence (an IEnmerable, to be specific), but it doesn't actually descend through the XML document and find all of the descendants until its iterator is executed. If you use a foreach loop to iterate through the descendants, each iteration only reads to the next descendant.

Using LINQ to read XML data from an RSS feed

You can do some pretty powerful things with LINQ to XML, because so much data is stored and transmitted as XML. Like RSS feeds, for example! Open up any RSS feed - like this one from our blog, Building Better Software - and view its source, and you'll see XML data. And that means you can read it into an XDocument and query it with LINQ.
One nice thing about the XDocument.Load() method is that when you pass it a string, you're giving it a URI. A lot of the time, you'll just pass it a simple filename. But a URL will work equally well. Here's how you can read the title of a blog from its RSS feed, using the <rss>, <channel>, and <title> tags:
XDocument ourBlog = XDocument.Load("http://www.stellman-greene.com/feed");
Console.WriteLine(ourBlog.Element("rss").Element("channel").Element("title").Value);
That means it's easy to write a LINQ to XML query to read data from an RSS feed. Here's how we'll do it:
1.       Create a new console application
2.       Make sure you've got using System.Xml.Linq; at the top of the code
3.       We'll use XDocument.Load() to load the XML data from the URL.
4.       A simple LINQ query can extract the articles into instances of a Post class that we'll create
5.       Instead of using anonymous types, the select new clause will select new Post objects
When you use the XDocument.Element() method, you're really calling the Element() method of its base class, XContainer. The XElement class that use used earlier also extends XContainer, and the Element() method returns an XContainer.
We'll take advantage of that by creating a Post class with a constructor that takes an XContainer object and uses its Element() method to get values. Note its GetElementValue() method that either returns an element's Value or, if that element doesn't exist, returns an empty string. (Again, remember to add using System.Xml.Linq; to the top of the code, for both this and the Main() method below!)
class Post
{
     public string Title { get; private set; }
     public DateTime? Date { get; private set; }
     public string Url { get; private set; }
     public string Description { get; private set; }
     public string Creator { get; private set; }
     public string Content { get; private set; }
 
     private static string GetElementValue(XContainer element, string name)
     {
          if ((element == null) || (element.Element(name) == null))
              return String.Empty;
          return element.Element(name).Value;
      }
 
     public Post(XContainer post)
     {
          // Get the string properties from the post's element values
          Title = GetElementValue(post, "title");
          Url = GetElementValue(post, "guid");
          Description = GetElementValue(post, "description");
          Creator = GetElementValue(post, 
              "{http://purl.org/dc/elements/1.1/}creator");
          Content = GetElementValue(post, 
              "{http://purl.org/dc/elements/1.0/modules/content}encoded");
  
          // The Date property is a nullable DateTime? if the pubDate element
          // can't be parsed into a valid date,the Date property is set to null
          DateTime result;
          if (DateTime.TryParse(GetElementValue(post, "pubDate"), out result))
              Date = (DateTime?)result;
      }
 
     public override string ToString()
     {
          return String.Format("{0} by {1}", Title ?? "no title", Creator ?? "Unknown");
      }
}
Did you notice how the Post constructor passes uses "{http://purl.org/dc/elements/1.1/}creator" as the name for creator? If you go back to the RSS feed source and search for "creator", you'll find a tag that looks like this:
<dc:creator>Andrew Stellman</dc:creator>
See that "dc:"? At the top of the post, the tag has this attribute:
xmlns:dc="http://purl.org/dc/elements/1.1/"
That's an XML namespace. Put them together and you'll get the element's complete name:
{http://purl.org/dc/elements/1.1/}creator
Now you're ready for the LINQ query. Notice how it uses select new Post(post) to pass each XElement returned by ourBlog.Descendants("item") into the Post constructor.
static void Main(string[] args)
{
     // Load the blog posts and print the title of the blog
     XDocument ourBlog = XDocument.Load("http://www.stellman-greene.com/feed");
     Console.WriteLine(ourBlog
         .Element("rss")
         .Element("channel")
         .Element("title")
         .Value);
 
     // Query <item>s in the XML RSS data and select each one into a new Post()
     IEnumerable<Post> posts =
         from post in ourBlog.Descendants("item")
         select new Post(post);
 
     // Print each post to the console
     foreach (var post in posts)
         Console.WriteLine(post.ToString());
}
When you run your program, it connects to the blog, retrieves the RSS feed, and prints the list of articles to the console.

Avoiding Memory Leaks - Silverlight



RAM is a critical resource of computer. Even though modern desktops and even laptops are equipped with good amount of RAM, there is always a risk of memory leak.

Saving an Object on the Stack or the Heap
In .NET, there are two kinds of objects: Those held by value and those held by reference. To make things a little more complicated, there are also two kinds of memory in a computer: the stack and the heap.

Value types are simple types such as int, bool, double and other primitive types. These values belong to the object that created them, but no other object can reference them. Instead, if an object attempts to access them, a copy is created.

Reference types on the other hand can be referenced by multiple objects. A reference to such an object is sometimes known as a pointer (C++ programming language), although nowadays C# developers rather speak of a reference to an object. Reference types are always stored on the heap memory. This kind of memory is optimized for larger objects that have a longer lifetime.

On the other hand, the stack is a kind of memory that is optimized for faster access and frequent cleanups. Although the stack is easy to clean up, the heap requires special attention, with the help of the so-called garbage collector (GC).

Collecting Garbage and Leaking Memory
.NET is a managed environment, which means that the .NET application does not typically access the computer’s hardware directly. Instead, application programming interfaces (APIs) are used. For the developer, this is interesting because the risk of crashes is reduced compared to older technologies such as unmanaged MFC applications written in C++ for instance.

A good example of this is memory management. Developers writing in non-managed languages such as C/C++ had to manage memory manually, deleting unused objects explicitly and freeing the memory. In the contrary, the garbage collector used by .NET monitors periodically which objects are not used anymore, and removes them from memory. Garbage collection is a very fascinating topic: On one hand, the garbage collection must occur from time to time to avoid that the computer runs out of memory. On the other hand, collecting garbage is a slow process, and running the GC too often will slow down the application and the computer.

Finding Which Objects Can Be Collected On every cycle, the garbage collector is looking for objects that the application is not using anymore. In the great lines, here is how GC works:
- Starting at a root object, all the children, then the children’s children (and so on) are marked (typically by setting a flag on the objects). For instance, if an object has an array of other objects, these other objects are reachable and thus are marked.
- Of course, certain objects are marked multiple times because more than one object is keeping a reference to them. This is not a problem because if there is at least one reference to this object, it will be spared.
- Then, all objects are inspected. Those without the flag set are unreachable by any other object. They are collected, and the memory they were using is freed.

One can see why this process is taking time. Also, during the inspection, it is crucial that the tree of objects is not modified. During the garbage collection time, no other operation may run.

In the past few years, GC has been very much optimized and improved with new algorithms. Concepts like this of generation help the GC to identify faster which objects are more likely to be unused by the application. Fundamentally, however, one fact remains true: If an object holds a reference to another child object, the child is considered in use by the application. Note that this is the case even if the object has been forgotten and is not actually needed by the application anymore. It is easy to understand that keeping track of these references and attempting to free them when possible will help to optimize memory.

Freeing an Object
For the developer, freeing an object amounts to making sure that all the references to that object are set to null:
- For local variables inside a block (such as a loop, a method, and so on), the reference will automatically be set to null when the block is exited.
- For global variables, the reference should be set to null manually to make sure that the object can be garbage collected (given of course that no other references to that object are found in the application).
For example consider the classes
21
Note: Sorting Objects in Generations-In short, the concept of generation specifies that objects that “survived” garbage collection a first time will be assigned to generation 1, and will be visited less often by the garbage collector than new objects (in generation 0). Similarly, objects that survived a generation 1 garbage collection will be assigned to generation 2, and will be visited even less often. This speeds up the garbage collection by assuming that older objects are less likely to be modified often than new objects.


public class MyCustomObject
 {
 private MyChildObject _child;
 public MyCustomObject(MyChildObject child)
 {
 _child = child;
 }
 // ...
 }

 public class MyOtherObject
 {
 private MyChildObject _child;
 public MyOtherObject(MyChildObject child)
 {
 _child = child;
 }
 // ...
 }

 public class MyChildObject
 {
 // ...
 }

Creating and Freeing the Classes

 public partial class MainPage : UserControl
 {
 private MyCustomObject _custom;
 private MyOtherObject _other;

 public MainPage()
 {
 InitializeComponent();

 var child = new MyChildObject();
 _custom = new MyCustomObject(child);
 _other = new MyOtherObject(child);
 // ...
 _other = null; // free the reference
 }
 }

- Both _custom and _other are kept as reference by the MainPage class.
- An instance of MyChildObject is created. Because it is local, this reference will be deleted when the block exits; that is when the constructor finishes execution.
- However, this instance has been passed to the MyCustomObject and to the
MyOtherObject constructors who in turn store a reference to that instance.
- Reference named _other is set to null explicitly. Because no one else keeps a reference to that instance, it will be collected the next time that the GC runs. However, the instance of MyChildObject is still referenced by the MyCustomObject instance, and therefore it cannot be freed.

Here we see that it is critical to explicitly free large objects by setting all their references to null, so that the GC considers them as unused. Forgetting even just one reference will prevent the memory to be freed.

Living a Shorter Life
 In-browser Silverlight applications typically have a shorter life than, for example, WPF applications running on the desktop. Because of this, the risk of getting a really critical memory leak in an in-browser Silverlight application is smaller: When the web page hosting the plug in is either refreshed or navigated away from, the memory is cleaned up and the computer is not at risk.


However, Silverlight 4 and the new advanced OOB applications are much more similar to desktop applications than to web applications. Their lifetime is typically longer, and a memory leak in these applications is much more dangerous. Generally speaking, it is good to remember that Silverlight applications are rich applications, and that regardless of where and how they are running, memory leaks should be avoided absolutely.

Unregistering Event Handlers
A typical mistake done by .NET programmers is related to event handling -

 public class MyObjectWithEvents
 {
 public event EventHandler<EventArgs> SomethingHappened;
 // ...
 }

 public partial class MainPage : UserControl
 {
 public MainPage()
 {
 InitializeComponent();
 var myObject = new MyObjectWithEvents();
 myObject.SomethingHappened += HandleSomethingHappened;
 // …
 }

 private void HandleSomethingHappened(object sender, EventArgs e)
 {
 // …
 }
 }
- An instance of MyObjectWithEvents is created. Note that it is stored as a local variable, and therefore will be garbage collected as soon as the block (the MainPage constructor) is finished executing.
- Next assigned an event handler (the HandleSomethingChanged method) to the SomethingChanged event of the MyObjectWithEvents instance.

This simple operation caused a potential memory leak: An event handler is creating a strong reference between the object that raises the event (in that case, the myObject instance) and the object that handles the event (MainPage). When the constructor exits, myObject cannot be collected for deletion by the GC because of this strong reference.
To solve the issue, the event handler must be removed before the block exits with the line of code as below –

myObject.SomethingHappened -= HandleSomethingHappened;

Properly removing all the event handlers on unused references before exiting a block or before a class is deleted is a good practice that reduces the memory leaks and ensures that your application will run more smoothly and provide a better user experience.

Using Commands Instead
In contrast to events, the Command property of a Button control is set through a Binding, which creates a less strong dependency between two objects. Even though the Command references another object (for example, a view-model), this does not prevent the viewmodel object to be garbage collected if needed. Using commands rather than events is a good practice because of the looser dependency that it creates between two objects.

Disposing Objects
Another kind of objects should be cleaned up after the application is done using them: the types implementing the IDisposable interface. When an object is defined as
IDisposable by its developer, it is a clear indication that this object might have used resources that should be properly cleaned up. For example, this might be an access to the file system (for the Stream, StreamReader, StreamWriter, and other classes), a connection to a database, and so forth. Closing and disposing such objects used to be an annoying process but in more recent versions of .NET (and in Silverlight), it has become very easy thanks to the using keyword. For example, a StreamReader and its Stream are automatically closed and disposed by the code –

var dialog = new OpenFileDialog();
if (dialog.ShowDialog() == true)
{
using (var stream = dialog.File.OpenRead())
{
using (var reader = new StreamReader(stream))
{
       // Read the file
}
}
}

Using Weak References
One way to avoid strong references between objects is to use the WeakReference class. This special class keeps a reference to an object but does not prevent it to be garbage collected.
To avoid blocking the MyChildObject instance we can do the following - 

 public class MyCustomObject
 {
 private WeakReference _childReference;
 public MyCustomObject(MyChildObject child)
 {
            _childReference = new WeakReference(child);
 }
 // ...

 public void UseChild()
 {
 if (_childReference != null  && _childReference.IsAlive)
 {
             (_childReference.Target as MyChildObject).DoSomething();
 }
 }
 }
- Line 3 declares a WeakReference instead of storing the instance of MyChildObject as an attribute directly.
- Line 7 constructs a new WeakReference instance and passes it the child.
- Finally, when the child needs to be used, line 15 makes sure that the MyChildObject instance is still alive. Because WeakReference does not prevent the GC to delete the child object, this step is necessary to avoid calling disposed objects.
- If the object is still alive, the Target property of the WeakReference is used to access the stored object.

Using a WeakReference is more convoluted than using an attribute directly. Although this class is very useful in some cases, it must be used with care. In many cases indeed, an object referenced by another object should not be allowed to be deleted. This is exactly the intent of the reference: to signal that the referenced object is still needed. Instead, the WeakReference class can be used when two objects should have a way to communicate, but neither object is responsible for the other object’s lifetime.

Finding a Leak
If, in spite of all the precautions mentioned in this section, a memory leak is suspected in an application, you can use the WinDbg utility to find the cause. Also, Visual Studio Premium and Ultimate support some limited profiling of memory garbage collection as well as allocation and object lifetime.