Contact Manager Web API

This sample uses ASP.NET Web API to build a simple contact manager application. The application consists of a contact manager web API that is used by an ASP.NET MVC application, a Windows Phone application, and a Windows 8 app to display and manage a list of contacts.

C# (1.9 MB)
 
 
 
 
 
4.4 Star
(37)
93,762 times
Add to favorites
8/16/2012
E-mail Twitter del.icio.us Digg Facebook

Solution explorer

C#
using ContactManager.Models;
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;

namespace ContactManager.Formatters
{
    public class ContactPngFormatter : BufferedMediaTypeFormatter
    {
        public ContactPngFormatter()
        {
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/png"));
        }

        public override void WriteToStream(Type type, object value, Stream stream, HttpContent content)
        {
            var contact = value as Contact;
            if (contact != null)
            {
                var imageId = contact.ContactId % 8;
                if (imageId == 0)
                {
                    imageId++;
                }

                var path = string.Format(@"Images\Image{0}.png", imageId);
                path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
                using (var fileStream = new FileStream(path, FileMode.Open))
                {
                    byte[] bytes = new byte[fileStream.Length];
                    fileStream.Read(bytes, 0, (int)fileStream.Length);
                    stream.Write(bytes, 0, (int)fileStream.Length);
                }
            }
        }

        public override bool CanReadType(Type type)
        {
            return false;
        }

        public override bool CanWriteType(Type type)
        {
            return typeof(Contact).Equals(type);
        }
    }
}