Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Литвинов / Лабораторна робота 3.print.doc
Скачиваний:
25
Добавлен:
23.03.2015
Размер:
1.69 Mб
Скачать

3.Створення тестеру-клієнта .

Для тестування логіки створюємо проект Administration.WebService.Test типу консольний додаток.

Тестування проводимо на двох рівнях – грубому (з використанням HTTP запитів) та звичайному.

Грубий метод. Створюємо клас RawWebServiceTest. Метод TestSoap формує HTTP повідомлення з включеним в нього повідомленням SOAP, яке асинхронно відсилається з використанням методу BeginGetResponse.

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net;

using System.Text;

using System.Xml;

namespace Administration.WebService.Test

{

public class RawWebServiceTester

{

string _soapEnvelope =

@"<soap:Envelope

xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'

xmlns:xsd='http://www.w3.org/2001/XMLSchema'

xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>

<soap:Body></soap:Body></soap:Envelope>";

private XmlDocument CreateSoapEnvelope(string content)

{

StringBuilder sb = new StringBuilder(_soapEnvelope);

sb.Insert(sb.ToString().IndexOf("</soap:Body>"), content);

// create an empty soap envelope

XmlDocument soapEnvelopeXml = new XmlDocument();

soapEnvelopeXml.LoadXml(sb.ToString());

return soapEnvelopeXml;

}

private HttpWebRequest CreateWebRequest(string url, string action)

{

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

webRequest.Headers.Add("SOAPAction", action);

webRequest.ContentType = "text/xml;charset=\"utf-8\"";

webRequest.Accept = "text/xml";

webRequest.Method = "POST";

return webRequest;

}

private void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)

{

using (Stream stream = webRequest.GetRequestStream())

{

soapEnvelopeXml.Save(stream);

}

}

public void TestSoap(String _url, String _action)

{

string _outputPath = @"C:\1\output.xml";

string content = @"<GetUser xmlns=""http://tempuri.org/"">

<login >admin</login>

<password >admin</password>

</GetUser>";

XmlDocument soapEnvelopeXml = CreateSoapEnvelope(content);

HttpWebRequest webRequest = CreateWebRequest(_url, _action);

InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);

// begin async call to web request.

IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);

// suspend this thread until call is complete. You might want to

// do something usefull here like update your UI.

asyncResult.AsyncWaitHandle.WaitOne();

// get the response from the completed web request.

string soapResult;

using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))

using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))

{

soapResult = rd.ReadToEnd();

}

File.WriteAllText(_outputPath, soapResult);

}

}

}

Створюємо TestRunner.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Administration.WebService.Test

{

class TestRunner

{

static void Main(string[] args)

{

RawWebServiceTester rawWebServiceTester = new RawWebServiceTester();

WebServiceTester webServiceTester = new WebServiceTester();

rawWebServiceTester.TestSoap("http://localhost/AdministrationWebService/AdministrationService.asmx", "http://tempuri.org/GetUser");

Console.ReadKey();

}

}

}

В результаті отримуємо файл C:\1\output.xml.

  <?xml version="1.0" encoding="utf-8" ?>

- <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

- <soap:Body>

- <GetUserResponse xmlns="http://tempuri.org/">

- <GetUserResult>

  <ID>1</ID>

  <Active>1</Active>

  <Login>admin</Login>

  <Password>admin</Password>

  </GetUserResult>

  </GetUserResponse>

  </soap:Body>

  </soap:Envelope>

Звичайний метод побудови клієнта складається в наступному.

В проекті додаємо посилання на веб-сервіс.

Рис.

Створюємо клас

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Administration.WebService.Test.AdministrationServiceProxy;

namespace Administration.WebService.Test

{

public class WebServiceTester

{

public void GetUser()

{

//Administration

AdministrationServiceSoapClient administrationServiceSoapClient =

new AdministrationServiceSoapClient();

User user = administrationServiceSoapClient.GetUser("admin", "admin" );

Console.WriteLine("ID: " + user.ID.ToString() + "\n" +

"Login: " + user.Login.ToString() + "\n" +

"Password: " + user.Password.ToString() + "\n" +

"Active: " + user.Active.ToString()

);

}

}

}

Змінюємо TestRunner

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Administration.WebService.Test

{

class TestRunner

{

static void Main(string[] args)

{

RawWebServiceTester rawWebServiceTester = new RawWebServiceTester();

WebServiceTester webServiceTester = new WebServiceTester();

//rawWebServiceTester.TestSoap("http://localhost/AdministrationWebService/AdministrationService.asmx",

// "http://tempuri.org/GetUser");

webServiceTester.GetUser();

Console.ReadKey();

}

}

}

Запускаємо тест.

Рис. Результати тестування.

Завдання

На мінімальний бал:

1.Реалізувати всі приклади, що наведені в лабораторній роботі. Пояснити особливості, варіанту організації системи.

Іншим:

  1. Реалізувати метод, який повертає колекцію користувачів, методи додавання та видалення користувача.

  2. Реалізувати кешування довідників (наприклад, вулиць, стран, регіонів).

  3. Дослідити властивості веб-сервісу пов’язані з включенням режиму сесії, кешування. Провести стрес тестування, дослідити затримки обробки запитів.

  4. Реалізувати зв'язок сервісів при реалізації задачі отримання всіх даних по пацієнту в розподіленій системі. Підсистеми лабораторія, стаціонар, поліклініка існують відокремлено – задача збору всіх даних по пацієнту по запиту.

  5. Повернути список пацієнтів за завданими умовами. Наприклад, всіх пацієнтів з відповідним діагнозом.