Code for Keeps:- Store Retrieve image to/from Database

One of our early blogs was about extracting images from databases, websites and showing them on the screen.

The blog(see it here) dealt with

a) Retrieving images from the www

b) Retrieving images from the database when retrieved as a binary.

We realized there are some more scenarios to take care of here

c) Save Image to the database as a byte[]

public Byte[] BufferFromImage(BitmapImage imageSource)
     {
         MemoryStream memStream = new MemoryStream();
         JpegBitmapEncoder encoder = new JpegBitmapEncoder();
         encoder.Frames.Add(BitmapFrame.Create(imageSource));
         encoder.Save(memStream);
         return memStream.GetBuffer();
         
     }

d) Retrieve Image from byte[]( When you use Entity Framework with the Image database type you would get it back as a byte[])

public BitmapImage ConvertToImage(byte[] rawImageData)
  {
      MemoryStream stream = new MemoryStream(rawImageData);
      stream.Position = 0;
      BitmapImage bi = new BitmapImage();
      bi.BeginInit();
      bi.StreamSource = stream;
      bi.EndInit();
      return bi; 
  }
If you see any more scenarios do add comments and lets complete this list…
Cennest!

Bulb Flash:- Setting a Dangerous Cookie on the Browser!!

During a recent assignment we were trying to set an xml string in the browser cookie. The string actually being a security token had a combination of signatures and unicode characters which the browser did not seem to like too much:-)

So after we set the cookie,every time i would browse the solution i was greeted by a A potentially dangerous Request.Form value was detected from the client message and i couldn’t browse any further. Seems its .NETs way of making sure no one is trying to use malicious code to hack his way into your application..

If you are sure you want this cookie then make this change in your web.config and you will be fine!

<configuration>
<system.web>
<pages validateRequest="false" />
</system.web>
</configuration>

and

<system.web>
<httpRuntime  requestValidationMode="2.0"/>
</system.web>

Hope this bulb flash saves you some time and gray cells!!

Until Next time!

Cennest!!

Code for Keeps:- Serialization

Another one of my favorites!..Everytime i need to serialize an object i end up surfing the web to get the correct code(who wants to reinvent the wheel!!)

Also most of the time i don’t want to “save” the object on the filesystem but just in memory so my code will focus on saving and reading from memory!

First the simpler one..XMLSerialization

1. XML Serialization

Serialize the object

   private void SerializeObject(<ObjectType>obj)
   {
        XmlSerializer s = new XmlSerializer(typeof(<ObjectType>));
        StringWriter sw = new StringWriter();
        s.Serialize(sw, sessionToken);
        string serializedXml = sw.ToString();
    }

Reading from the string

 private <ObjectType>ReadFromSerializedString(string s)
  {
  XmlSerializer s = new XmlSerializer(typeof( <ObjectType>));
  return (<ObjectType>)s.Deserialize(new  StringReader(serializedString));
  }

 

However you may not be able to use XMLSerialization on all object types…one irritating requirement is that the object to be serialized should have an parameterless constructor!!. This requirement led me to try Binary serialization….

2. Binary Serialization

Serialize the object

private void SerializeObject(<ObjectType>obj)
{
    var formatter = new BinaryFormatter();
    byte[] bytes;
    using (var stream = new MemoryStream())
            {
             formatter.Serialize(stream, obj );
              stream.Seek(0, 0);
              bytes = stream.ToArray();
            }
string serializedString = Convert.ToBase64String(bytes);
}

Reading from the string

 
private <ObjectType> ReadSerializedString(string serializedString)
 {
     byte[]b =Convert.FromBase64String(serializedString);
    var formatter = new BinaryFormatter();
     <ObjectType> value;
     using (var stream = new MemoryStream(b, 0, b.Length))
     {
            value = <ObjectType>formatter.Deserialize(stream);
     }
    return value;
}

Now i won’t have to google my serialization out!..hope this helps you save some time too!

Until Next time!

Cennest!!

Creating An “Extensible” Consolidated Social Networking Platform in WPF using MEF

One of my recent projects was on Social Networking where we worked with various social networking sites like WL, Facebook, Delicious, Twitter ,Picassa, Flickr etc to bring them to a common platform for a user.

It was a pretty interesting application and i’ll try to demonstrate multiple WPF patterns we implemented in it.

One was the use of Plugin model using the “Managed Extensibility Framework”. The user could upload his photographs to multiple providers at the same time. The challenge given here was “we should be able to add another provider to the system at any time after the application is already deployed”. So at the time of development we develop for Flickr and Picassa but now YouTube is also allowing Photo upload so now we want to support You Tube but without opening up the code!!

We used the Managed Extensibility Framework for this.I’ll explain the core concepts of MEF(mostly picked up from the MEF guidelines document) and show you how we implemented this seemingly tough requirement easily.

What is MEF?

The Managed Extensibility Framework (or MEF for short) simplifies the creation of extensible applications. MEF offers discovery and composition capabilities that you can leverage to load application extensions.

  • MEF provides a standard way for the host application to expose itself and consume external extensions. Extensions, by their nature, can be reused amongst different applications. However, an extension could still be implemented in a way that is application-specific. Extensions themselves can depend on one another and MEF will make sure they are wired together in the correct order (another thing you won’t have to worry about).
  • MEF offers a set of discovery approaches for your application to locate and load available extensions.
  • MEF allows tagging extensions with additonal metadata which facilitates rich querying and filtering

MEF is all about composable parts, which come in two flavours; imports and exports.  An export is something you want to share and an import is the point at which you want to inject an export.

So in our case the “Photo Providers” are our “Exports” and the core Platform Consolidation application  had an “Import” point for them.

MEF needs to a way of knowing about what exports it has at its disposal and what imports require “composing” (or matching up to available exports).  In MEF this is the CompositionContainer which contains a Catalog of exports

So basically your “Catalog” has all the “Exports” Now how you make the Catalog  is very important to how your exports will be identified.

There are multiple Catalog Options available for WPF

Assembly Catalog

To discover all the exports in a given assembly

Directory Catalog

To discover all the exports in all the assemblies in a directory .The DirectoryCatalog will do a one-time scan of the directory and will not automatically refresh when there are changes in the directory.

Aggregate Catalog

When AssemblyCatalog and DirectoryCatalog are not enough individually and a combination of catalogs is needed then an application can use an Aggregate Catalog.An AggregateCatalog combines multiple catalogs into a single catalog.

Type Catalog

To discover all the exports in a specific set of types one would use  the Type Catalog.

Since we wanted a model where we just drop a new dll into the project and the new provider is up and running we went ahead with Directory Catalog.

Here are the 3 steps we did

1. The Imports and Exports need to agree to an Interface. So we made an IPhotoProviderInterface and the Exports i.e the PhotoProviders adhered to it.

2. Marked the Providers with the “Export” attribute for the IPhotoProviderInterface

[Export(typeof(IPhotoProviderInterface))]
public class PicassaProvider :IPhotoProviderInterface
    {
        ...
    }

On Application(Our CompositionContainer)  Startup we wrote code to read a specific directory to look for exports .

2. Create a list of IPhotoProviders which will hold instances of the providers going to be loaded and mark it with the Import Attribute

[Import]
public IEnumerable<IPhotoProviderInterface> PhotoProviders { get; set; }

3. Create a DirectoryCatalog to read the new providers…

private void LoadProviders()
{
  try
  {
      var catalog = new DirectoryPartCatalog(@".\Providers\");
      var container = new CompositionContainer(catalog);

      container.AddPart(this);
      container.Compose();
      foreach (IPhotoProviderInterface sender in PhotoProviders)
      {
          ......
      }
  }
}

From here onwards the Providers were present in the PhotoProviders list….

It was a pretty neat implementation and we got a 100% for extensibility here…MEF looks daunting with all these new keywords but its pretty simple to implement!!

If you are looking to make a scalable and extensible application…we have the expertise and the experience to help you get there….drop us a note at cennesttech@hotmail.com..

Until Next time!

Cennest

Code For Keeps:- WPF/Silverlight Retrieve Images from DB/Url

WPF and Silverlight are all about images and styling and the one thing i end up doing a lot is extracting images from Databases, websites and showing them on a screen…and the code to do this is really hard to remember. So keep this code in your safe!!

1. Get Image from a byte[]: If your image is stored in the DB you will generally get it back as a binary. You can get the byte array by doing a ToArray() on the binay

public BitmapImage ImageFromBuffer(Byte[] bytes)
       {
           MemoryStream stream = new MemoryStream(bytes);
           BitmapImage image = new BitmapImage();
           image.SetSource(stream);
           stream.Close();
           return image;
       }

2. Get Image from a Url

public BitmapImage GetImageFromUrl(string imageUrl )

{

          const int BYTESTOREAD = 100000;

        WebRequest myRequest = WebRequest.Create(new Uri(imageUrl, UriKind.Absolute));
        myRequest.Timeout = -1;
        WebResponse myResponse = myRequest.GetResponse();
        Stream ReceiveStream = myResponse.GetResponseStream();
        BinaryReader br = new BinaryReader(ReceiveStream);
        MemoryStream memstream = new MemoryStream();
        byte[] bytebuffer = new byte[BYTESTOREAD];
        int BytesRead = br.Read(bytebuffer, 0, BYTESTOREAD);

        while (BytesRead > 0)
        {
            memstream.Write(bytebuffer, 0, BytesRead);
            BytesRead = br.Read(bytebuffer, 0, BYTESTOREAD);
        }
        BitmapImage image = new BitmapImage();
        image.BeginInit();
        memstream.Seek(0, SeekOrigin.Begin);

        image.StreamSource = memstream;
        image.EndInit();

        return image

     }

Hope if helps make your UI prettier!!!

Cennest!

Code for Keeps!: Deep Copy For Custom Objects

One of the major issues i had working with database entities/custom objects in Silverlight/WPF was that since “class” is a reference type any changes made to the object would stay in all its copies!!.

Lets take an example

I have a custom class called Person and i want to show in a listbox all those who are parents.

so basically i have this piece of code.

       List<Person> personList = new List<Person>();
       private void ShowInitialParentList()
       {
           listboxParent.Datacontext = (from p in parentList
                                        where p.IsParent
                                        select p).ToList();
       }

Now for some reason i have another listbox and i want to see what happens if all of them are parents(i don’t know why…just for this example:-))

so i do this

private void AssignSampleParents()
      {
          List <Person>templist= new List<Person>;
          foreach (Person original in personList)
          {
              templist.Add(original);
          }

          foreach (person p in templist)
          {
              p.IsParent = true;
          }
          listboxSample.Datacontext = (from p in tempList
                                       where p.IsParent
                                       select p).ToList();
      }

Now even though i copied the original list using the much cumbersome ADD method functionality(you can try direct assignment or AddRange or anything else you want!) what i get is that not only does the ListBoxSample show all the persons , even the original listbox gets updated..so basically making the copy was of no use!!

The only way to get out of this is to use the “Clone” method which is NOT available by default in custom/database entity objects.

Making a customized Clone method is a LOT of work for all the custom objects in your class….so the thing to do is…

Use the following Extension method!

using System.ComponentModel;
using System.Runtime.Serialization;
using System.IO;

public static class ExtensionMethods
   {
       public static T DeepCopy<T>(this T oSource)
       {

           T oClone;
           DataContractSerializer dcs = new DataContractSerializer(typeof(T));
           using (MemoryStream ms = new MemoryStream())
           {
               dcs.WriteObject(ms, oSource);
               ms.Position = 0;
               oClone = (T)dcs.ReadObject(ms);
           }
           return oClone;
       }
   }

Now if i did the following

        foreach (Person original in personList)
          {
              templist.Add(original.DeepCopy());
          }

everything would be perfect, because the object in the tempList has NO reference to the object in the original list!!

I found this piece of code a real keep!!..It will resolve a LOT of your “Who set this property issues”!

Do let me know if you “kept” this code for keeps!..

More such snippets coming up!

Cennest!!