Estoy utilizando WCF para crear un servicio.
DataContract:
using System;
using System.Runtime.Serialization;
using ConnectionPG.Classes;
using Npgsql;
namespace MyHouseService.Services.User {
[DataContract]
public class User {
[DataMember]
public int Id { get; set; }
[DataMember]
public string NickName { get; set; }
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public string Password { get; set; }
[DataMember]
public DateTime BirthDate { get; set; }
[DataMember]
public bool LogicalDelete { get; set; }
[DataMember]
public string Email { get; set; }
[DataMember]
public string PhoneNumber { get; set; }
public static void SetUser(User obj, NpgsqlDataReader rs) {
obj.Id = CFunctionsBd.CargarInt(rs, "id");
obj.NickName = CFunctionsBd.CargarString(rs, "nickname");
obj.FirstName = CFunctionsBd.CargarString(rs, "firstname");
obj.LastName = CFunctionsBd.CargarString(rs, "lastname");
obj.Password = CFunctionsBd.CargarString(rs, "password");
obj.BirthDate = CFunctionsBd.CargarDateTime(rs, "birthdate");
obj.LogicalDelete = CFunctionsBd.CargarBoolean(rs, "logicaldelete");
obj.Email = CFunctionsBd.CargarString(rs, "email");
obj.PhoneNumber = CFunctionsBd.CargarString(rs, "phonenumber");
}
}
}
La clase CFuncionesBD
se encarga de realizar peticiones a la base de datos y manejar los datos devueltos por esta de forma genérica.
ServiceContract:
using System.Collections.Generic;
using System.ServiceModel;
namespace MyHouseService.Services.User {
[ServiceContract]
public interface IWSUser {
[OperationContract]
bool ExistByEmail(string email);
[OperationContract]
bool ExistById(int id);
[OperationContract]
List<User> GetActives();
[OperationContract]
List<User> GetAll();
[OperationContract]
bool Insert(User obj);
[OperationContract]
User ReadById(int id);
[OperationContract]
bool RemoveById(int id);
[OperationContract]
bool Update(User obj);
}
}
Implementación:
using System.Collections.Generic;
using ConnectionPG.Classes;
using MyHouseService.Exceptions;
using Npgsql;
namespace MyHouseService.Services.User {
public class WSUser : IWSUser {
private NpgsqlConnection connection = CConnection.Instancia.Conexion;
public bool ExistByEmail(string email) {
NpgsqlCommand cmd = new NpgsqlCommand { Connection = connection };
cmd.Parameters.AddWithValue("@email", email);
cmd.CommandText = "SELECT * FROM users WHERE email = @email AND logicaldelete = FALSE";
return CFunctionsBd.ExecuteExist(cmd);
}
public bool ExistById(int id) {
NpgsqlCommand cmd = new NpgsqlCommand { Connection = connection };
cmd.Parameters.AddWithValue("@id", id);
cmd.CommandText = "SELECT * FROM users WHERE id = @id AND logicaldelete = FALSE";
return CFunctionsBd.ExecuteExist(cmd);
}
public List<User> GetActives() {
NpgsqlCommand cmd = new NpgsqlCommand { Connection = connection };
cmd.CommandText = "SELECT * FROM users WHERE logicaldelete = FALSE";
return CFunctionsBd.ExecuteSelectList<User>(cmd, User.SetUser);
}
public List<User> GetAll() {
NpgsqlCommand cmd = new NpgsqlCommand { Connection = connection };
cmd.CommandText = "SELECT * FROM users";
return CFunctionsBd.ExecuteSelectList<User>(cmd, User.SetUser);
}
public bool Insert(User obj) {
if (!ExistByEmail(obj.Email)) {
NpgsqlCommand cmd = new NpgsqlCommand { Connection = connection };
cmd.Parameters.AddWithValue("@nickname", obj.NickName);
cmd.Parameters.AddWithValue("@firstname", obj.FirstName);
cmd.Parameters.AddWithValue("@lastname", obj.LastName);
cmd.Parameters.AddWithValue("@password", obj.Password);
cmd.Parameters.AddWithValue("@birthdate", obj.BirthDate);
cmd.Parameters.AddWithValue("@logicaldelete", obj.LogicalDelete);
cmd.Parameters.AddWithValue("@email", obj.Email);
cmd.Parameters.AddWithValue("@phonenumber", obj.Email);
cmd.CommandText = "INSERT INTO users (nickname, firstname, lastname, password, birthdate, logicaldelete, email, phonenumber) " +
"\n VALUES \n" +
"(@nickname, @firstname, @lastname, @password,@birthdate, @logicaldelete, @email, @phonenumber)";
return CFunctionsBd.ExecuteNonQuery(cmd);
} else {
throw new ExceptionExistEmail(obj.Email);
}
}
public User ReadById(int id) {
NpgsqlCommand cmd = new NpgsqlCommand { Connection = connection };
cmd.Parameters.AddWithValue("@id", id);
cmd.CommandText = "SELECT * FROM users WHERE id = @id AND logicaldelete = FALSE";
User user = new User { Id = id };
return CFunctionsBd.ExecuteSelect(cmd, user, User.SetUser) ? user : null;
}
public bool RemoveById(int id) {
NpgsqlCommand cmd = new NpgsqlCommand { Connection = connection };
cmd.Parameters.AddWithValue("@id", id);
cmd.CommandText = "UPDATE users \n" +
"SET (logicaldelete = TRUE)\n" +
"WHERE id = @id";
return CFunctionsBd.ExecuteNonQuery(cmd);
}
public bool Update(User obj) {
NpgsqlCommand cmd = new NpgsqlCommand { Connection = connection };
cmd.Parameters.AddWithValue("@id", obj.Id);
cmd.Parameters.AddWithValue("@nickname", obj.NickName);
cmd.Parameters.AddWithValue("@firstname", obj.FirstName);
cmd.Parameters.AddWithValue("@lastname", obj.LastName);
cmd.Parameters.AddWithValue("@password", obj.Password);
cmd.Parameters.AddWithValue("@birthdate", obj.BirthDate);
cmd.Parameters.AddWithValue("@logicaldelete", obj.LogicalDelete);
cmd.Parameters.AddWithValue("@email", obj.Email);
cmd.Parameters.AddWithValue("@phonenumber", obj.Email);
cmd.CommandText = "UPDATE users \n " +
"SET (nickname = @nickname, " +
"firstname = @firstname, " +
"lastname = @lastname, " +
"password = @password, " +
"birthdate = @birthdate, " +
"logicaldelete = @logicaldelete, " +
"email = @email, " +
"phonenumber = @phonenumber)\n " +
"WHERE id = @id";
return CFunctionsBd.ExecuteNonQuery(cmd);
}
}
}
Exception:
using System;
namespace MyHouseService.Exceptions {
public class ExceptionExistEmail : Exception {
public ExceptionExistEmail(string email) : base(string.Format("El Email ya existe {0}", email)) { }
}
}
Al ejecutar este servicio para probar las funciones de consulta a la base de datos funciona correctamente.
Lo publico en localhost en IIS y hago referencia al servicio publicado desde mi proyecto Xamarin Forms y al ejecutar el programa corro automáticamente las siguientes líneas:
WSUserClient client = new WSUserClient();
client.OpenAsync();
User user = client.ReadByIdAsync(1).Result;
client.CloseAsync();
La declaración y asignación de la variable user va al servicio, el cual va a la base de datos y debería devolver los datos del usuario en la base de datos con el ID 1, el cual existe. Pero cuando va a buscar al servicio, la funcion ReadById()
me lanza el siguiente error:
System.ServiceModel.EndpointNotFoundException: 'System error.'
Actualizacion:
Si ejecuto el servicio desde Visual Studio me abre mi navegador web con esta página:
En cambio, si navego al servicio desde IIS, el navegador que me abre es completamente blanco.