using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

using System.Web.Script.Serialization;  // needed for JSON serializers

using System.IO;                        // needed for Stream and Stream Reader

using System.Net;                       // needed for the Web Request

using Core2WebAPI;                      // needed for the Team class

 

namespace WebAPIClient

{

    public partial class TeamWebAPI_Example2 : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

 

        }

 

        protected void btnStoreTeam_Click(object sender, EventArgs e)

        {

            Team theTeam = new Team();

            theTeam.Name = txtTeamName.Text;

            theTeam.University = txtUniversity.Text;

            theTeam.Mascot = txtMascot.Text;

 

            // Serialize a Team object into a JSON string.

            JavaScriptSerializer js = new JavaScriptSerializer();

            String jsonTeam = js.Serialize(theTeam);

 

            try

            {

                // Setup an HTTP POST Web Request and get the HTTP Web Response from the server.

                WebRequest request = WebRequest.Create("http://cis-iis2.temple.edu/Users/Pascucci/CIS3342/CoreWebAPI/api/teams/");

                request.Method = "POST";

                request.ContentLength = jsonTeam.Length;

                request.ContentType = "application/json";

 

                // Write the JSON data to the Web Request

                StreamWriter writer = new StreamWriter(request.GetRequestStream());

                writer.Write(jsonTeam);

                writer.Flush();

                writer.Close();

 

                // Read the data from the Web Response, which requires working with streams.

                WebResponse response = request.GetResponse();

                Stream theDataStream = response.GetResponseStream();

                StreamReader reader = new StreamReader(theDataStream);

                String data = reader.ReadToEnd();

                reader.Close();

                response.Close();

 

                if (data == "true")

                    lblMessage.Text = "The team was successfully saved to the database.";

 

                else

                    lblMessage.Text = "The team wasn't saved to the database.";

 

            }

            catch (Exception ex)

            {

                lblMessage.Text = "Error: " + ex.Message;

            }

        }

    }

}