using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Xml.Linq;
namespace WebServiceCallConsoleApp
{
class Program
{
static void Main(string[] args)
{
string selection;
string valueToBeConverted;
string convertedValue;
Console.Title = "Temperature Conversion";
Console.WriteLine("Select Conversion");
Console.WriteLine("-----------------");
Console.WriteLine("1) Fahrenheit to Celsius");
Console.WriteLine("2) Celsius to Fahrenheit\n");
selection = Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Enter Value to Convert");
Console.WriteLine("----------------------");
valueToBeConverted = Console.ReadLine();
Console.WriteLine("");
convertedValue = ConvertValue(Int32.Parse(selection), valueToBeConverted);
Console.WriteLine("Conversion Result");
Console.WriteLine("-----------------");
Console.WriteLine(convertedValue);
// Exit application
Console.WriteLine("");
Console.WriteLine("Press any key to exit!");
Console.ReadLine();
}
private static string ConvertValue(int selection, string valueToBeConverted)
{
string value;
string uriString;
string returnValue;
string soapAction = "";
string displayText = "";
string resultName = "";
uriString = "http://www.w3schools.com/webservices/tempconvert.asmx";
switch (selection)
{
case 1: // Convert Fahrenheit to Celsius
soapAction = "http://tempuri.org/FahrenheitToCelsius";
displayText = " Celsius";
resultName = "FahrenheitToCelsiusResult";
break;
case 2: // Convert Celsius to Fahrenheit
soapAction = "http://tempuri.org/CelsiusToFahrenheit";
displayText = " Fahrenheit";
resultName = "CelsiusToFahrenheitResult";
break;
}
try
{
HttpWebRequest httpRequest = (HttpWebRequest) WebRequest.Create(new Uri(uriString));
httpRequest.Method = "POST";
httpRequest.ContentType = "text/xml; charset=utf-8";
httpRequest.Headers.Add(String.Format("SOAPAction: \"{0}\"", soapAction));
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ConsoleApplication1.SoapAction.xml");
using (StreamReader reader = new StreamReader(stream))
{
string soapActionXml = reader.ReadToEnd().Replace("string", valueToBeConverted);
byte[] buffer = Encoding.UTF8.GetBytes(soapActionXml);
httpRequest.ContentLength = buffer.Length;
httpRequest.ReadWriteTimeout = 10;
httpRequest.ProtocolVersion = HttpVersion.Version11;
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse) httpRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
value = responseStreamReader.ReadToEnd();
XDocument document = XDocument.Parse(value);
string elementName = "{http://tempuri.org/}" + resultName;
returnValue = document.Descendants(elementName).FirstOrDefault().Value;
}
}
catch (Exception ex)
{
returnValue = "Error : " + ex.ToString();
}
return returnValue;
}
}
}
|