Click here to Skip to main content
12,405,088 members (68,885 online)
Click here to Skip to main content

Stats

83.6K views
5.1K downloads
57 bookmarked
Posted

Build ReST based Web Services in .NET/C#

, 12 Jul 2009 CPOL
A ReST based Web Service for C#.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;

namespace tstWebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
    public class Part
    {
        string id;
        string name;
        string description;
        public string Id
        {
            get { return id; }
            set { id = value; }
        }
        public string Name { get { return name; } set { name = value; } }
        public string Description { get { return description; } set { description = value; } }
    }
    public class Parts : PoC.Web.Services.IReSTFulService
    {
        static System.Collections.Generic.List<Part> allParts = new System.Collections.Generic.List<Part>();
        
        static Parts()
        {
            Part p = new Part();
            p.Description = "Dell Desktop";
            p.Id = "1101";
            p.Name = "Desktop";
            allParts.Add(p);
            p = new Part();
            p.Description = "Dell Laptop";
            p.Id = "1102";
            p.Name = "Laptop";
            allParts.Add(p);
            p = new Part();
            p.Description = "XP Tablet";
            p.Id = "1103";
            p.Name = "Tablet";
            allParts.Add(p);
            p = new Part();
            p.Description = "XP Tablet2";
            p.Id = "1104";
            p.Name = "Tablet";
            allParts.Add(p);
            p = new Part();
            p.Description = "XP Tablet3";
            p.Id = "1105";
            p.Name = "Tablet";
            allParts.Add(p);
            p = new Part();
            p.Description = "XP Tablet4";
            p.Id = "1106";
            p.Name = "Tablet";
            allParts.Add(p);
            p = new Part();
            p.Description = "XP Tablet5";
            p.Id = "1107";
            p.Name = "Tablet";
            allParts.Add(p);
        }
        static object syncRoot = new object();
        #region IReSTFulService Members

        public object GetCall(string arg, HttpContext context)
        {
            if (string.IsNullOrEmpty(arg))
            {
                lock (syncRoot)
                {
                    return allParts.ToArray();
                }
            }
            else
            {
                System.Collections.Generic.List<Part> listOfItems = null;
                lock (syncRoot)
                {
                    listOfItems =
                    allParts.FindAll(delegate(Part p)
                    {
                        return p.Id.IndexOf(arg) > -1 | p.Name.ToLower().IndexOf(arg) > -1 | p.Description.ToLower().IndexOf(arg) > -1;
                    });
                }
                if (listOfItems != null) return listOfItems.ToArray();
                return null;
            }
        }
        
        public object PutCall(string arg, HttpContext context)
        {
            //Update
            //using (System.IO.StreamReader sreader = new System.IO.StreamReader(context.Request.InputStream))
            {
                //string item = sreader.ReadToEnd();
                Part ps = null;
                //Get Part
                try
                {
                    ps = PoC.Web.Services.Utilities.TypeConversion.Deserialize<Part>(context.Request.InputStream);
                }
                catch(Exception ex){ //Bad Stream
                    throw new PoC.Web.Services.InternalErrorException(503, "Bad Stream");
                }
                lock (syncRoot)
                {
                    Part orginalPart = allParts.Find(delegate(Part aP) { return aP.Id == ps.Id; });
                    if (orginalPart == null)
                    {
                        throw new PoC.Web.Services.InternalErrorException(503, "Part was not found.");
                    }
                    else
                    {

                        orginalPart.Name = ps.Name;
                        orginalPart.Description = ps.Description;
                        return "SuccessFully Updated";
                    }
                }
            }
            //throw new PoC.Web.Services.InternalErrorException(503, "Method Not Supported");
        }

        public object PostCall(string arg, HttpContext context)
        {
            Part ps = null;
            //Get Part
            try
            {
                ps = PoC.Web.Services.Utilities.TypeConversion.Deserialize<Part>(context.Request.InputStream);
            }
            catch (Exception ex)
            { //Bad Stream
                throw new PoC.Web.Services.InternalErrorException(503, "Bad Stream");
            }
            lock (syncRoot)
            {
                Part orginalPart = null;//allParts.Find(delegate(Part aP) { return aP.Name == ps.Name; });
                if (orginalPart != null)
                {
                    throw new PoC.Web.Services.InternalErrorException(503, "Part already exist.");
                }
                else
                {
                    ps.Id = System.Guid.NewGuid().ToString("N");
                    allParts.Add(ps);
                }
                return allParts.ToArray();
            }

        }

        public object DeleteCall(string arg, HttpContext context)
        {
            using (System.IO.StreamReader sreader = new System.IO.StreamReader(context.Request.InputStream))
            {
                string item = sreader.ReadToEnd();
            }
            throw new PoC.Web.Services.InternalErrorException(503, "Method Not Supported");
        }

        #endregion
    }

    public class Calculator : PoC.Web.Services.IReSTService
    {
        [PoC.Web.Services.ReSTMethod(PoC.Web.Services.HttpVerb.Get)]
        public int Sum(int a, int b)
        {
            return a + b;
        }
        [PoC.Web.Services.ReSTMethod(PoC.Web.Services.HttpVerb.Get)]
        public int Multiply(int a, int b)
        {
            return a * b;
        }
        [PoC.Web.Services.ReSTMethod(PoC.Web.Services.HttpVerb.Get)]
        public int Substract(int a, int b)
        {
            return a - b;
        }
    }
    public class ShowNTell : PoC.Web.Services.IReSTService
    {
        XmlDocument dom = new XmlDocument();
        public ShowNTell()
        {
            dom.LoadXml("<Root><Child><SubChild><Parameter></Parameter><MagicNumber>" + System.Guid.NewGuid().ToString("N") + "</MagicNumber></SubChild></Child></Root>");
        }
        [PoC.Web.Services.ReSTMethod(PoC.Web.Services.HttpVerb.Get)]
        [PoC.Web.Services.ReSTXmlResponse]
        public Employee[] Object2Xml()
        {
            Employee e1 = new Employee();
            e1.Name = "Aremac Nokin ";
            e1.Id = "11201";
            e1.Address = "123 Summer Drive";
            e1.City = "Brahman";
            e1.Zip = "00001";
            e1.JoiningDate = DateTime.Today.AddYears(-5).AddMonths(-3).AddDays(-20);
            e1.Salary = 100000.00;
            Employee e2 = new Employee();
            e2.Name = "Reyalp Sinnet";
            e2.Id = "11201";
            e2.Address = "123 Summer Drive";
            e2.City = "Brahman";
            e2.Zip = "00001";
            e2.JoiningDate = DateTime.Today.AddYears(-2).AddMonths(-1).AddDays(-40);
            e2.Salary = 200000.00;
            return new Employee[] { e1, e2 };
        }
        [PoC.Web.Services.ReSTMethod(PoC.Web.Services.HttpVerb.Get)]
        public XmlNode ReturnNode(string some_param)
        {
            dom.SelectSingleNode("//Root/Child/SubChild/Parameter").InnerText = some_param;
            return dom.SelectSingleNode("//Root/Child/SubChild");
        }

        [PoC.Web.Services.ReSTMethod(PoC.Web.Services.HttpVerb.Get)]
        public XmlDocument ReturnDom(XmlDocument param_1, int param2)
        {
            dom.SelectSingleNode("//Root/Child/SubChild/Parameter").InnerText = param2.ToString();
            if (param_1 != null && param_1.DocumentElement != null)
            {
                XmlElement elem = dom.CreateElement("NewItem");
                elem.InnerXml = param_1.DocumentElement.OuterXml;
                dom.SelectSingleNode("//Root/Child").AppendChild(elem);
            }
            return dom;
        }
    }
    public class Employee
    {
        string name;
        string id;
        string address;
        string city;
        string zip;
        DateTime joiningdate;
        double salary;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public string Id
        {
            get { return id; }
            set { id = value; }
        }
        public string Address { get { return address; } set { address = value; } }
        public string City { get { return city; } set { city = value; } }
        public string Zip { get { return zip; } set { zip = value; } }
        public DateTime JoiningDate { get { return joiningdate; } set { joiningdate = value; } }
        public double Salary { get { return salary; } set { salary = value; } }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Parag.Gadkari
United States United States
Loves coding...

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160721.1 | Last Updated 12 Jul 2009
Article Copyright 2009 by Parag.Gadkari
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid