Azure table storage using repository pattern and unit of work pattern - repository-pattern

I'm trying to build a reusable code for accessing Azure Table Storage using repository pattern and unit of work pattern.
What I want to achieve is to instantiate an unit of work and then use that for different repositories.
Something like this:
MyUnitOfWork uow = new MyUnitOfWork();
uow.Users.Add(User user);
uow.Users.GetAllUsers();
uow.Users.FindUser(User user);
uow.Users.Delete(User user);
.......
uow.Products.Add(Product product);
uow.Products.Delete(Product product);
.......
uow.Invoices.Add(Invoice invoice);
.......
uow.Save();
I have some issues understanding how to implement this using TableServiceContext
Here is what I did so far ...
The model:
public class User : TableServiceEntity
{
public User(string partitionKey, string rowKey)
: base(partitionKey, rowKey)
{
}
public User()
: this(Guid.NewGuid().ToString(), String.Empty)
{
}
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
IRepository Interface:
public interface IRepository<T> where T : TableServiceEntity
{
IQueryable<T> Query { get; }
//bool CreateIfNotExist();
//bool DeleteIfExist();
//void AddEntity(T obj);
//void AddEntity(IEnumerable<T> objs);
//void AddOrUpdateEntity(T obj);
//void AddOrUpdateEntity(IEnumerable<T> objs);
//void DeleteEntity(T obj);
//void DeleteEntity(IEnumerable<T> objs);
}
Interface Unit Of Work:
public interface ITableUow
{
void Save();
IUserRepository Users { get; }
}
Interface User Repository:
public interface IUserRepository: IRepository<User>
{
IQueryable<User> GetUsers();
}
Azure Table Repository:
public class AzureTableRepository<T> : IRepository<T> where T : TableServiceEntity
{
public AzureTableRepository(TableServiceContext context)
{
if (context != null)
{
TableContext = context;
}
}
protected TableServiceContext TableContext { get; set; }
public IQueryable<T> Query
{
get { throw new NotImplementedException(); }
}
}
User Repository:
public class UserRepository : AzureTableRepository<User>, IUserRepository
{
public UserRepository(TableServiceContext context)
: base(context)
{
}
public IQueryable<User> GetUsers()
{
throw new NotImplementedException();
}
}
Azure Table Unit Of Work:
public class AzureTableUow: ITableUow
{
public void Save()
{
}
public IUserRepository Users
{
get { throw new NotImplementedException(); }
}
}

Related

Unable to resolve service for type 'Api.Repositories.UnitOfWork' while attempting to activate 'Api.ServicesBusiness.EquipoServices'

I want to make a webapi and I'm trying to do it through the services way, I have a repository generic and another 2 repository and a unit of work, apparently everything goes fine, but when I run and test the webapi from postman I got that error:
InvalidOperationException: Unable to resolve service for type 'Api.Repository.Repositories.UnitOfWork' while attempting to activate 'Api.ServicesBusiness.Implementacion.EquipoServices'.
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, bool throwIfCallSiteNotFound)
Here is the my dbcontect:
public class AppDbContext : DbContext
{
public AppDbContext()
{
}
public AppDbContext(DbContextOptions<AppDbContext> option) :base(option)
{
}
public DbSet<Equipo> Equipos { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\Express;Database=SoftballLeague;Trusted_Connection=True");
}
}
}
Here is the interface of my generic repository:
public interface IGenericRepository<T> where T : class
{
Task<T> AddAsyn(T t);
Task<T> UpdateAsyn(T t, object key);
}
Here is the implementation of my generic repository:
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
private readonly AppDbContext _context;
private readonly DbSet<T> _dbSet;
public GenericRepository(AppDbContext context)
{
_context = context;
_dbSet = _context.Set<T>();
}
public virtual async Task<T> AddAsyn(T t)
{
_dbSet.Add(t);
await _context.SaveChangesAsync();
return t;
}
public virtual async Task<T> UpdateAsyn(T t, object key)
{
if (t == null)
return null;
T exist = await _dbSet.FindAsync(key);
if (exist != null)
{
_context.Entry(exist).CurrentValues.SetValues(t);
await _context.SaveChangesAsync();
}
return exist;
}
}
Here is the interface of my equipo repository:
public interface IEquipoRepository:IGenericRepository<Team>
{
int GetAverageTeam(string name);
int GetTeamHit(string name);
}
Here is the implementation of my equipo repository:
public class EquipoRepository : GenericRepository<Team>, IEquipoRepository
{
private readonly AppDbContext dbContext;
public EquipoRepository(AppDbContext context) : base(context)
{
this.dbContext = context;
}
public int GetAverageTeam(string name)
{
int teamAverage = 0;
var resultAverage = this.dbContext.Equipos
//.SelectMany(bItem => bItem.)
.Where(equipo=>equipo.Nombre==name)
.SelectMany(equipo => equipo.jugadores)
.Average(jugador => jugador.Average);
if (resultAverage.HasValue)
teamAverage =Convert.ToInt32(Math.Round(resultAverage.Value));
return teamAverage;
}
public int GetTeamHit(string name)
{
int resultTotal = 0;
var result = this.dbContext.Equipos
//.SelectMany(bItem => bItem.)
.Where(equipo => equipo.Nombre == name)
.SelectMany(equipo => equipo.jugadores)
.Sum(jugador => jugador.Cant_Hits_Conectados);
if (result.HasValue)
resultTotal = result.Value;
return resultTotal;
}
}
Here is the interface of my unit of work:
public interface IUnitOfWork:IDisposable
{
Task Commit();
}
Here is the implementation of my unit of work:
public class UnitOfWork : IUnitOfWork
{
private readonly AppDbContext _DbContext;
private EquipoRepository equipoRepository ;
public UnitOfWork(AppDbContext dbContext)
{
this._DbContext = dbContext;
this.equipoRepository = new EquipoRepository(this._DbContext);
}
public EquipoRepository GetEquipoRepository{
get {
if(this.equipoRepository==null)
this.equipoRepository= new EquipoRepository(this._DbContext);
return this.equipoRepository;
}
}
public async Task Commit()
{
await this._DbContext.SaveChangesAsync();
}
public void Dispose()
{
this._DbContext.Dispose();
}
}
Here is the implementation of services interfaces IEquipoServices:
public interface IEquipoServices
{
ICollection<EstadisticaEquipoModel>AveragePorEquipo(string name);
int Total2bleConectados(string name);
}
Here is the implementation of services EquipoServices which is the one who throws the error:
public class EquipoServices : IEquipoServices
{
private readonly UnitOfWork unit;
public EquipoServices(UnitOfWork unitOfWorkFactory)
{
this.unit = unitOfWorkFactory;
}
public ICollection<EstadisticaEquipoModel> AveragePorEquipo(string name)
{
var equipoAverage= this.unit.GetEquipoRepository.GetAverageEquipo(name);
return equipoAverage;
}
public int AveragePorEquipo(string name)
{
var result = this.unit.GetEquipoRepository.GetEquipoTotal2bleConectados(name);
return result;
}
}
This is the controller, here I am just running the ListadoEquipos() method:
[Route("api/[controller]")]
public class EquipoController : ControllerBase
{
private readonly IEquipoServices equipoService;
private readonly IMapper _mapper;
public EquipoController(IEquipoServices eqService, IMapper mapper)
{
this.equipoService = eqService;
this._mapper = mapper;
}
[HttpGet("list")]
public IEnumerable<string> ListadoEquipos()
{
return new string[] { "value1", "value2" };
}
}
This is the configuration in the startup.cs file:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options=>options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));
services.AddTransient<IUnitOfWork, UnitOfWork>();
services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
services.AddSingleton<IEquipoServices, EquipoServices>();
//services.AddScoped<IJu, JugadorService>();
services.AddAutoMapper(typeof(Startup));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
You registered IUnitOfWork, but you're injecting UnitOfWork. The service collection doesn't know how to inject UnitOfWork directly.
Long and short, inject IUnitOfWork instead:
private readonly IUnitOfWork unit;
public EquipoServices(IUnitOfWork unitOfWorkFactory)

How to write Unit test for ViewModel that contains RxJava/RxAndroid

I'm trying to refactor one pretty old project, so I started implementing new architecture (MVVM) with Dagger2, RxJava, RxAndroid... Now everything is connected and working fine, now the problem is, I have no idea how to write a Unit test for my ViewModel..
I want to start with Login screen first, so I created a LoginViewModel, but first let me show you what I did..
I have a DataModule that provides 2 classes, RestApiRepository and ViewModelFactory. RestApiRepository looks like this:
public class RestApiRepository {
private RestClient restClient;
public RestApiRepository(RestClient restClient) {
this.restClient = restClient;
}
public Observable<AuthResponseEntity> authenticate(String header, AuthRequestEntity requestEntity) {
return restClient.postAuthObservable(header, requestEntity);
}
}
Rest client with api call for login:
public interface RestClient {
#POST(AUTH_URL)
Observable<AuthResponseEntity> postAuthObservable(#Header("Authorization") String authKey, #Body AuthRequestEntity requestEntity);
}
Second class from DataModule is ViewModelFactory:
#Singleton
public class ViewModelFactory extends ViewModelProvider.NewInstanceFactory implements ViewModelProvider.Factory {
private RestApiRepository repository;
#Inject
public ViewModelFactory(RestApiRepository repository) {
this.repository = repository;
}
#NonNull
#Override
public <T extends ViewModel> T create(#NonNull Class<T> modelClass) {
if (modelClass.isAssignableFrom(LoginViewModel.class)) {
return (T) new LoginViewModel(repository);
}
throw new IllegalArgumentException("Unknown class name");
}
}
And finally, LoginViewModel:
public class LoginViewModel extends ViewModel {
private final CompositeDisposable disposable = new CompositeDisposable();
private final MutableLiveData<AuthResponseEntity> responseLiveData = new MutableLiveData<>();
private RestApiRepository restApiRepository;
private SchedulerProvider provider;
public LoginViewModel(RestApiRepository restApiRepository, SchedulerProvider provider) {
this.restApiRepository = restApiRepository;
this.provider = provider;
}
public MutableLiveData<AuthResponseEntity> getResponseLiveData() {
return responseLiveData;
}
#Override
protected void onCleared() {
disposable.clear();
}
public void auth(String token, AuthRequestEntity requestEntity) {
if (token != null && requestEntity != null) {
disposable.add(restApiRepository.authenticate(token, requestEntity)
.subscribeOn(provider.io())
.observeOn(provider.ui())
.subscribeWith(new DisposableObserver<AuthResponseEntity>() {
#Override
public void onNext(AuthResponseEntity authResponseEntity) {
responseLiveData.setValue(authResponseEntity);
}
#Override
public void onError(Throwable e) {
AuthResponseEntity authResponseEntity = new AuthResponseEntity();
authResponseEntity.setErrorMessage(e.getMessage());
responseLiveData.setValue(authResponseEntity);
}
#Override
public void onComplete() {
}
}
));
}
}
}
So, I'm sure everything is connected well, I can successfuly login...
For the RxAndroid test issues, I found somewhere that I have to use this Scheduler provider like this:
public class AppSchedulerProvider implements SchedulerProvider {
public AppSchedulerProvider() {
}
#Override
public Scheduler computation() {
return Schedulers.trampoline();
}
#Override
public Scheduler io() {
return Schedulers.trampoline();
}
#Override
public Scheduler ui() {
return Schedulers.trampoline();
}
}
Below is my LoginViewModelTest class, but I don't know how to handle RxJava/RxAndroid inside the tests..
#RunWith(MockitoJUnitRunner.class)
public class LoginViewModelTest {
#Mock
private RestApiRepository restApiRepository;
#Mock
private MutableLiveData<AuthResponseEntity> mutableLiveData;
private LoginViewModel loginViewModel;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
AppSchedulerProvider schedulerProvider = new AppSchedulerProvider();
loginViewModel = Mockito.spy(new LoginViewModel(restApiRepository, schedulerProvider));
}
#Test
public void authenticate_error() {
String token = "token";
AuthRequestEntity requestEntity = Mockito.mock(AuthRequestEntity.class);
Mockito.doReturn(Observable.error(new Throwable())).when(restApiRepository).authenticate(token, requestEntity);
loginViewModel.auth(token, requestEntity);
AuthResponseEntity responseEntity = Mockito.mock(AuthResponseEntity.class);
responseEntity.setErrorMessage("Error");
Mockito.verify(mutableLiveData).setValue(responseEntity);
}
}
So, I wanted to write a test for failed case when onError is called, but when I run it, I get this error:
exclude patterns:io.reactivex.exceptions.UndeliverableException: The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with. Further reading: https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#error-handling | java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.
You can mock the behaviour of restApiRepository:
Mockito.when(restApiRepository.authenticate(token, requestEntity)).thenReturn(Observable.error(error));
and verify that responseLiveData.setValue is being called with the appropriate parameters

Request.GetOwinContext().getManager<ApplicationUserManager> returns null when unit testing Account controller web api

I am trying to write some unit tests for my account controller web apis which make use of UserManager but I keep receiving null on the line in the title in the following section:
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
I have tried so many different ways to fix this as I have read that I need to Mock some of the parts of ApplicationUser but have not managed to get any of them to fix my problem. Below is some of the code I have implemented following a tutorial to unit test:
public interface IStoreAppContext : IDisposable
{
//IDbSet<User> Users { get; }
DbSet<User> u { get; }
DbSet<SportProgram> SportContext { get; set; }
int SaveChanges();
void MarkAsModified(User item);
}
}
The api I am trying to unit test in my account controller is:
(This line below "var user..." is where the problem starts. it calls the line in the title of this question)
[Route("userProfile/{username}")]
public IHttpActionResult getUserProfile(String username)
{
var user = UserManager.FindByName(username);
if (user != null)
{
db2.MarkAsModified(user);
return Ok(user);
}
else
{
return NotFound();
}
}
Then in my TestProject I have the following context class:
class TestStoreAppContext : IStoreAppContext
{
public TestStoreAppContext()
{
this.u = new TestProductDbSet();
}
public DbSet<User> u { get; set; }
public DbSet<SportProgram> SportContext { get; set; }
public int SaveChanges()
{
return 0;
}
public void MarkAsModified(User item) { }
public void Dispose() { }
}
}
Finally in my test controller where i test the api:
[TestMethod()]
public void getUserProfileTest()
{
var context = new TestStoreAppContext();
context.u.Add(GetDemoProduct());
var controller = new AccountController(context);
var result = controller.getUserProfile("john") as OkNegotiatedContentResult<User>;
Assert.AreEqual("john", result.Content.UserName);
}
The GetDemoProduct called above:
User GetDemoProduct()
{
return new User()
{
Id = "3",
UserName = "john",
Password = "Password-1",
};
}
Can anyone point me in the right direction please?

How do I unit test handlers with NServiceBus?

This should be simple and I'm probably missing something. I'm working from here: http://support.nservicebus.com/customer/portal/articles/856297-unit-testing
The following always fails:
[TestFixture]
public class MyTestFixture
{
[Test]
public void RoundTrip() {
Test.Initialize();
var correlationId = Guid.NewGuid();
Test.Handler(bus => new MyHandler(bus))
.ExpectReply<IEventThatHappened>(m => m.CorrelationId == correlationId)
.OnMessage<MyCommand>(m => new MyCommand(correlationId));
}
}
public interface IEventThatHappened : IEvent
{
Guid CorrelationId { get; set; }
}
public class MyCommand : ICommand
{
public Guid CorrelationId { get; private set; }
public MyCommand(Guid correlationId) {
CorrelationId = correlationId;
}
}
public class MyHandler : IHandleMessages<MyCommand>
{
private readonly IBus _bus;
public MyHandler(IBus bus) {
if (bus == null) {
throw new ArgumentNullException("bus");
}
_bus = bus;
}
public void Handle(MyCommand message) {
_bus.Send<IEventThatHappened>(m => m.CorrelationId = message.CorrelationId);
}
}
If I set a breakpoint inside my handler, the message.CorrelationId == Guid.Empty. The exception thrown during the test is:
System.Exception : ExpectedReplyInvocation not fulfilled.
Calls made:
SendInvocation
I've tried using bus.Send, bus.Publish, bus.Reply but each one fails with the corresponding Expected*Invocation .
Why is the message.CorrelationId == Guid.Empty instead of the value I supplied? Why doesn't Test.Handler<> detect that I've called Send/Reply/Publish in my handler?
NOTE: Using NServiceBus 3.3 from Nuget.
There are a couple issues here.
In your handler, you are trying to Bus.Send() an event (the IEventThatHappened implements IEvent and is even named like an event), which is not allowed. Commands are Sent, Events are Published.
Your test is using ExpectReply, which is what you would expect if the handler were doing Bus.Reply(). Assuming you fixed #1, I believe you would be looking for .ExpectPublish().
So first you need to work out what it really is you're meaning to do!
You need to Reply instead of Send!
Here is the test that passes:
[TestFixture]
public class MyTestFixture
{
[Test]
public void RoundTrip()
{
Test.Initialize();
var correlationId = Guid.NewGuid();
var myCommand = new MyCommand(correlationId);
Test.Handler(bus => new MyHandler(bus))
.ExpectReply<IEventThatHappened>(m => m.CorrelationId == correlationId)
.OnMessage(myCommand);
}
}
public interface IEventThatHappened : IEvent
{
Guid CorrelationId { get; set; }
}
public class MyCommand : ICommand
{
public Guid CorrelationId { get; private set; }
public MyCommand(Guid correlationId)
{
CorrelationId = correlationId;
}
}
public class MyHandler : IHandleMessages<MyCommand>
{
private readonly IBus _bus;
public MyHandler(IBus bus)
{
if (bus == null)
{
throw new ArgumentNullException("bus");
}
_bus = bus;
}
public void Handle(MyCommand message)
{
_bus.Reply<IEventThatHappened>(m => m.CorrelationId = message.CorrelationId);
}
}

Silverlight & RIA Services: Managing Users

I want to manage users and Roles in the cliente side, but i cannot find the way to accomplish this. Links or code will be very appreciated.
Sorry for this abandoned question, i have solved this issue many days ago now, and i fill i should post the answer here because i couldnt find a complete answer in the web and this can help some soul in distress over there. Except for a link that i cannot remember right now but,my apologise to the blog owner for not remember even his name, however, here is the full history:
First create a class to wrap MembershipUser and another one to wrap MembsershipRole:
public class MembershipServiceUser
{
public string Comment { get; set; }
[Editable(false)]
public DateTime CreationDate { get; set; }
[Key]
[Editable(false, AllowInitialValue = true)]
public string Email { get; set; }
public bool IsApproved { get; set; }
[Editable(false)]
public bool IsLockedOut { get; set; }
[Editable(false)]
public bool IsOnline { get; set; }
public DateTime LastActivityDate { get; set; }
[Editable(false)]
public DateTime LastLockoutDate { get; set; }
public DateTime LastLoginDate { get; set; }
[Editable(false)]
public DateTime LastPasswordChangedDate { get; set; }
[Editable(false)]
public string PasswordQuestion { get; set; }
[Key]
[Editable(false, AllowInitialValue = true)]
public string UserName { get; set; }
public MembershipServiceUser() { }
public MembershipServiceUser(MembershipUser user)
{
this.FromMembershipUser(user);
}
public void FromMembershipUser(MembershipUser user)
{
this.Comment = user.Comment;
this.CreationDate = user.CreationDate;
this.Email = user.Email;
this.IsApproved = user.IsApproved;
this.IsLockedOut = user.IsLockedOut;
this.IsOnline = user.IsOnline;
this.LastActivityDate = user.LastActivityDate;
this.LastLockoutDate = user.LastLockoutDate;
this.LastLoginDate = user.LastLoginDate;
this.LastPasswordChangedDate = user.LastPasswordChangedDate;
this.PasswordQuestion = user.PasswordQuestion;
this.UserName = user.UserName;
}
public MembershipUser ToMembershipUser()
{
MembershipUser user = Membership.GetUser(this.UserName);
if (user.Comment != this.Comment) user.Comment = this.Comment;
if (user.IsApproved != this.IsApproved) user.IsApproved = this.IsApproved;
if (user.LastActivityDate != this.LastActivityDate) user.LastActivityDate = this.LastActivityDate;
if (user.LastLoginDate != this.LastLoginDate) user.LastLoginDate = this.LastLoginDate;
return user;
}
}
//Roles
public class MembershipServiceRole {
public MembershipServiceRole() { }
public MembershipServiceRole(string rolename) {
RoleName = rolename;
}
[Key]
[Editable(true, AllowInitialValue = true)]
public string RoleName { get; set; }
}
Second, create a class derived from DomainService to manipulate users and roles wrappers:
[EnableClientAccess(RequiresSecureEndpoint = false /* This should be set to true before the application is deployed */)]
public class MembershipService : DomainService
{
protected override void OnError(DomainServiceErrorInfo errorInfo)
{
TimeoutHelper.HandleAuthenticationTimeout(errorInfo, this.ServiceContext.User);
}
[RequiresRole("Administrator")]
public IEnumerable<MembershipServiceUser> GetUsers()
{
return Membership.GetAllUsers().Cast<MembershipUser>().Select(u => new MembershipServiceUser(u));
}
[RequiresRole("Administrator")]
public IEnumerable<MembershipServiceUser> GetUsersByEmail(string email)
{
return Membership.FindUsersByEmail(email).Cast<MembershipUser>().Select(u => new MembershipServiceUser(u));
}
[RequiresRole("Administrator")]
public MembershipServiceUser GetUsersByName(string userName)
{
MembershipServiceUser retVal = null;
retVal = Membership.FindUsersByName(userName)
.Cast<MembershipUser>()
.Select(u => new MembershipServiceUser(u))
.FirstOrDefault();
return retVal;
}
[Invoke(HasSideEffects = true)]
public void CreateUser(MembershipServiceUser user, string password)
{
if (string.IsNullOrEmpty(user.Email)) {
user.Email = "cambiar#dominio.com";
}
Membership.CreateUser(user.UserName, password, user.Email);
}
[RequiresRole("Administrator")]
public void DeleteUser(MembershipServiceUser user)
{
Membership.DeleteUser(user.UserName);
}
[RequiresRole("Administrator")]
public void UpdateUser(MembershipServiceUser user)
{
Membership.UpdateUser(user.ToMembershipUser());
}
[RequiresRole("Administrator")]
[Update(UsingCustomMethod = true)]
public void ChangePassword(MembershipServiceUser user, string newPassword)
{
MembershipUser u = user.ToMembershipUser();
u.ChangePassword(u.ResetPassword(), newPassword);
}
[RequiresRole("Administrator")]
public void ResetPassword(MembershipServiceUser user)
{
user.ToMembershipUser().ResetPassword();
}
[RequiresRole("Administrator")]
public void UnlockUser(MembershipServiceUser user)
{
user.ToMembershipUser().UnlockUser();
}
#region Roles
[RequiresRole("Administrator")]
public IEnumerable<MembershipServiceRole> GetRoles() {
return Roles.GetAllRoles().Cast<string>().Select(r => new MembershipServiceRole(r));
}
[RequiresRole("Administrator")]
public IEnumerable<MembershipServiceRole> GetRolesForUser(string userName) {
return Roles.GetRolesForUser(userName).Cast<string>().Select(r => new MembershipServiceRole(r));
}
[RequiresRole("Administrator")]
public void CreateRole(MembershipServiceRole role) {
Roles.CreateRole(role.RoleName);
}
[RequiresRole("Administrator")]
public void DeleteRole(MembershipServiceRole role) {
Roles.DeleteRole(role.RoleName);
}
[RequiresRole("Administrator")][Invoke]
public void AddUserToRole(string userName, string roleName) {
if (!Roles.IsUserInRole(userName,roleName))
Roles.AddUserToRole(userName, roleName);
}
[RequiresRole("Administrator")]
[Invoke]
public void RemoveUserFromRole(string userName, string roleName) {
if (Roles.IsUserInRole(userName, roleName))
Roles.RemoveUserFromRole(userName, roleName);
}
#endregion //Roles
}
Third: Use the service the same way you do for your domains clases
Cheers!!!