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,764 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.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;

namespace ContactManager.Formatters
{
    public class VCardFormatter : BufferedMediaTypeFormatter
    {
        public VCardFormatter()
        {
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/directory"));
        }

        public override void WriteToStream(Type type, object value, Stream stream, HttpContent content)
        {
            var contacts = value as IEnumerable<Contact>;
            if (contacts != null)
            {
                foreach (var contact in contacts)
                {
                    WriteContact(contact, stream);
                }
            }

            else
            {
                var singleContact = value as Contact;
                if (singleContact != null)
                {
                    WriteContact(singleContact, stream);
                }
            }
        }

        private void WriteContact(Contact contact, Stream stream)
        {
            var writer = new StreamWriter(stream);
            writer.WriteLine("BEGIN:VCARD");
            writer.WriteLine(string.Format("FN:{0}", contact.Name));
            writer.WriteLine(string.Format("ADR;TYPE=HOME;{0};{1};{2}", contact.Address, contact.City, contact.Zip));
            writer.WriteLine(string.Format("EMAIL;TYPE=PREF,INTERNET:{0}", contact.Email));
            writer.WriteLine("END:VCARD");
            writer.Flush();
        }

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

        public override bool CanWriteType(Type type)
        {
            return typeof(Contact).Equals(type) || typeof(IEnumerable<Contact>).IsAssignableFrom(type);
        }
    }
}