Резюме
В последнее сообщение , мы рассмотрели проектирование баз данных и Entity Model для ASP.Net MVC4 Mobile application. Мы будем продолжать с уровня обслуживания в этой статье.
Service Layer
Мы определим некоторые методы в нашей класса обслуживания для ввода данных в таблицы SQL наш лог.

В последнее сообщение , мы рассмотрели проектирование баз данных и Entity Model для ASP.Net MVC4 Mobile application. Мы будем продолжать с уровня обслуживания в этой статье.
Service Layer
Мы определим некоторые методы в нашей класса обслуживания для ввода данных в таблицы SQL наш лог.
- Щелкните правой кнопкой мыши проект, выберите Add-> New Folder и называем его Service.
- Щелкните правой кнопкой мыши папку Service, выберите Add, New Item и нажмите на WCF службу. Имя службы
- Обновите system.serviceModel раздел в файле web.config, чтобы она выглядела следующим образом:
<system.serviceModel> <bindings> <webHttpBinding> <binding name="customWebHttpBinding"> <security mode="None"></security> </binding> </webHttpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior
name="JSLearning.Services.BabyMonitorServiceBehavior"> <enableWebScript /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="DebugBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug
includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> <services> <service name="JSLearning.Services.BabyMonitorService"
behaviorConfiguration="DebugBehavior"> <endpoint address=""
behaviorConfiguration=
"JSLearning.Services.BabyMonitorServiceBehavior"binding="webHttpBinding"
contract="JSLearning.Services.IBabyMonitorService"
bindingConfiguration="customWebHttpBinding" /> <endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange" /> </service> </services> <serviceHostingEnvironment
multipleSiteBindingsEnabled="true" /> </system.serviceModel>
- В папке Service, добавить ServiceBase класса, а затем скопируйте и вставьте следующий код к ней. Класс ServiceBase предоставляет полезные методы для взаимодействия с моделью EDM
public class ServiceBase { private BabyLogEntities _context = null; private string _connectionString = string.Empty; protected ServiceBase() { RenewContext(); } protected ServiceBase(string connectionString) { _connectionString = connectionString; _context = new BabyLogEntities(_connectionString); } protected BabyLogEntities Context { get { return _context; } } protected void RenewContext() { if (_connectionString == string.Empty) { _connectionString =
System.Configuration.ConfigurationManager.
ConnectionStrings["BabyLogEntities"].ConnectionString; } _context = new BabyLogEntities(_connectionString); return; } }
- Редактировать BabyMonitorService.svc.cs файл и он наследует от ServiceBase.cs
- Скопируйте и вставьте следующий код в ваш интерфейс IBabyMonitorService.cs
[ServiceContract]
public interface IBabyMonitorService
{
[OperationContract]
[WebMethod]
[WebInvoke(Method = "GET", ResponseFormat =
WebMessageFormat.Json, BodyStyle =
WebMessageBodyStyle.WrappedRequest)]
string HeartBeat();
[OperationContract]
[WebMethod]
[WebInvoke(Method = "GET", ResponseFormat =
WebMessageFormat.Json, BodyStyle =
WebMessageBodyStyle.WrappedRequest)]
string AddFeedingEntry(string UserId,
string FeedType, string FeedAmount); [OperationContract] [WebMethod] [WebInvoke(Method = "GET", ResponseFormat =
WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string AddDiaperingEntry(string UserId, string DiaperType);
}
- Откройте BabyMonitorService.svc.cs файл и добавить следующий код:
public class BabyMonitorService : ServiceBase, IBabyMonitorService { public BabyMonitorService() : base() { } /// <summary> /// Check that the service is available /// </summary> /// <returns></returns> public string HeartBeat() { return "Service is alive"; } /// <summary> /// Add a feed entry /// </summary> /// <param name="UserId"></param> /// <param name="FeedType"></param> /// <param name="FeedAmount"></param> /// <returns></returns> public string AddFeedingEntry(string UserId, string FeedType,
string FeedAmount) { Models.WebServiceResponse response =
new Models.WebServiceResponse(); try { var log = new FeedingLog { ID = Guid.NewGuid(), DateCreated = DateTime.Now, FeedType = FeedType, // since IIS does not like the .
// character, we are passing
// decimals as x_y and converting to x.y
FeedAmount =
Decimal.Parse(FeedAmount.Replace("_", ".")), UserID = UserId }; RenewContext(); Context.AddToFeedingLogs(log); Context.SaveChanges(); response.IsSuccess = true; } catch (Exception ex) { response.IsSuccess = false; response.ErrorMessage = ex.Message; } return SerializeAsJSON(response); } /// <summary> /// Add an entry for a diaper change /// </summary> /// <param name="UserId"></param> /// <param name="DiaperType"></param> /// <returns></returns> public string AddDiaperingEntry(string UserId,
string DiaperType) { Models.WebServiceResponse response =
new Models.WebServiceResponse(); try { var log = new DiaperLog { ID = Guid.NewGuid(), DateCreated = DateTime.Now, DiaperType = DiaperType, UserID = UserId }; RenewContext(); Context.AddToDiaperLogs(log); Context.SaveChanges(); response.IsSuccess = true; } catch (Exception ex) { response.IsSuccess = false; response.ErrorMessage = ex.Message; } return SerializeAsJSON(response); } /// <summary> /// Serializes an object to JSON /// </summary> /// <param name="response"></param> /// <returns></returns> private string SerializeAsJSON(
Models.WebServiceResponse response)
{
using (MemoryStream s = new MemoryStream())
{
DataContractJsonSerializer ser =
new DataContractJsonSerializer(
typeof(Models.WebServiceResponse)); ser.WriteObject(s, response); s.Position = 0; using (StreamReader sr = new StreamReader(s)) { return sr.ReadToEnd(); } } } }
- Код очень прост, он использует Entity Model чтобы сделать запись в соответствующие таблицы и возвращает WebServiceResponse объект в формате JSON.
- В папке модели, добавить класс WebServiceResponse и добавьте следующий код. WebServiceResponse это хороший способ, чтобы вернуть объект в качестве ответа JSON, и она может содержать много деталей из службы, а не просто сообщение об ошибке строки. Проверьте класса обслуживания чтобы видеть, как этот объект построен.
[DataContract] public class WebServiceResponse { /// <summary> /// Indicates if the web service call was successful /// </summary> [DataMember] public bool IsSuccess = false; /// <summary> /// Contains the response message from the service /// </summary> [DataMember] public object Payload = "Object not assigned"; /// <summary> /// Contains a friendly error message if the service/// encountered an exception /// </summary> [DataMember] public string FriendlyErrorMessage = string.Empty; /// <summary> /// Contains the full text of the exception,
/// if one occurred /// </summary> [DataMember] public string ErrorMessage = string.Empty; /// <summary> /// Contains the exception trace, if one occurred /// </summary> [DataMember] public string ErrorStackTrace = string.Empty; /// <summary> /// Contains the date and time of the service
/// response in UTC format. /// </summary> [DataMember] public string UTC_DateOfResponse =
DateTime.Now.ToUniversalTime().ToString("dd MMM yyyy hh:mm:ss tt"); }- На данный момент мы должны быть в состоянии компиляции проекта и перейдите к службе.
- Можно также вызвать метода HeartBeat от предыдущих, если ваш сервис работает корректно. Обратите внимание, вам нужно сохранить ответ JSON, а затем открыть его в блокноте, чтобы увидеть результаты
Комментариев нет:
Отправить комментарий