ServiceStack GetRequestFilterAttributes NullReference - c#

I'm trying to use the new API approach for ServiceStack and I'm building a test console application to host it. So far I have the route instantiating the request DTO, but before the request reaches my service's Any method, I get this exception:
Error Code NullReferenceException
Message Object reference not set to an instance of an object.
Stack Trace at ServiceStack.WebHost.Endpoints.Utils.FilterAttributeCache.GetRequestFilterAttributes(Type requestDtoType) at
ServiceStack.WebHost.Endpoints.EndpointHost.ApplyRequestFilters(IHttpRequest httpReq, IHttpResponse httpRes, Object requestDto) at
ServiceStack.WebHost.Endpoints.RestHandler.ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, String operationName)
Below is my test Service using IReturn and Service (at this point I'm only trying to return hard-coded results to see it working)
[DataContract]
public class AllAccounts : IReturn<List<Account>>
{
public AllAccounts()
{
}
}
[DataContract]
public class AccountTest : IReturn<string>
{
public AccountTest()
{
this.Id = 4;
}
[DataMember]
public int Id { get; set; }
}
public class AccountService : Service
{
public AccountService()
{
}
public object Any(AccountTest test)
{
return "hello";
}
public object Any(AllAccounts request)
{
var ret = new List<Account> {new Account() {Id = 3}};
return ret;
}
}
All ServiceStack references come from NuGet. I get the same error with either route. Any suggestions?

It might help to see your AppHost code and the code in your Configure() method. Nothing you provided in the code above stands out. Below is how I would set up a simple Console app using the code/classes you have provided.
Initialize and Start the ServiceStack AppHost
class Program
{
static void Main(string[] args)
{
var appHost = new AppHost();
appHost.Init();
appHost.Start("http://*:1337/");
System.Console.WriteLine("Listening on http://localhost:1337/ ...");
System.Console.ReadLine();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
}
}
Inherit from AppHostHttpListenerBase and Configure (not configuring anything for this example)
public class AppHost : AppHostHttpListenerBase
{
public AppHost() : base("Test Console", typeof(AppHost).Assembly) { }
public override void Configure(Funq.Container container)
{
}
}
Dto/Request classes
public class Account
{
public int Id { get; set; }
}
[Route("/AllAccounts")]
[DataContract]
public class AllAccounts : IReturn<List<Account>>
{
public AllAccounts()
{
}
}
[Route("/AccountTest")]
[DataContract]
public class AccountTest : IReturn<string>
{
public AccountTest()
{
this.Id = 4;
}
[DataMember]
public int Id { get; set; }
}
Service code to handle your requests - URLS: localhost:1337/AllAccounts & localhost:1337/AccountTest
public class AccountService : Service
{
public AccountService()
{
}
public object Any(AccountTest test)
{
return "hello";
}
public object Any(AllAccounts request)
{
var ret = new List<Account> { new Account() { Id = 3 } };
return ret;
}
}

Related

.NET - It is possible to use DI with the State Pattern?

I'm studying design patterns in .NET and currently i'm trying to implement the State Pattern. But today i got to a problem and i can't figure out how to fix this situation.
I have some state classes, all of them implementing the state interface. One of the last states should connect to a data base, through a service injected by the .NET API Startup class, to persist the data and finish up the process.
The problem is... because of the dependency injection that i need to be in the final state, i can't instanciate this state object to progress to this point. I don't know how to continue from there. I don't know if i'm using the pattern wrong or if the use of dependency injection in this pattern is the problem. I can't give all the details of the problem because my studie's project is a little big mess at this moment, so i made a quick mimic of the structure i'm trying to build in my application.
States interface and the OperatingClass who will execute the state behaviour:
public interface IOperationState
{
public int ExecuteOperation(OperatingClass operatingClass);
}
public class OperatingClass
{
public IOperationState OperationState { get; set; }
public int id { get; set; }
public double value { get; set; }
public OperatingClass(int id) //constructor
{
this.id = id;
value = 0;
OperationState = new StartingState();
}
public int Execute()
{
return OperationState.ExecuteOperation(this);
}
}
Main Service: is the service who my controller calls after receive the API Post Method:
public class MainService
{
public int ExecuteFullOperation(int id)
{
//Receives an id and execute the state transition till the end;
var operatingClass = new OperatingClass(id);
return operatingClass.Execute();
}
}
The classes who represents the states and do the respective actions:
public class StartingState : IOperationState
{
public int ExecuteOperation(OperatingClass operatingClass)
{
// Do something...
operatingClass.OperationState = new MiddleState();
return operatingClass.Execute();
}
}
public class MiddleState : IOperationState
{
public int ExecuteOperation(OperatingClass operatingClass)
{
//Do something with the value... let's supose the result is 123, but it does not matter rn;
operatingClass.value = 123;
//Here is the problem: FinalState needs the PersistenceService, who
//receives a injected class to acess the database;
operatingClass.OperationState = new FinalState();
//I want to execute it and return the sucess or failure of the persistence.
return operatingClass.Execute();
}
}
public class FinalState : IOperationState
{
private readonly IPersistenceService PersistenceService;
public FinalState(IPersistenceService persistenceService)
{
PersistenceService = persistenceService;
}
public int ExecuteOperation(OperatingClass operatingClass)
{
return PersistenceService.PersistData(operatingClass.id, operatingClass.value) ? 200 : 503;
}
}
Additional info: i made the PersistenceService be injected in the Startup.cs as a Transient (i dont know how to make it in another way at this moment).
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IPersistenceService, PersistenceService>();
// Irrelevant configurations for the question.
services.AddControllers();
}
Please, help me if you can. I'm having a hard time trying to figure it out by myself.
Thank you for your patience and for your time reading it.
Firstly, we need some simple factory which will supply all necessary dependencies by their type. So let's create types for states:
public enum StateType
{
Start,
Middle,
Final
}
And simple factory:
public class StateFactory
{
private Dictionary<StateType, IOperationState> _stateByType;
// you can inject these dependencies through DI like that:
// public StateFactory(StartingState startingState,
// MiddleState middleState, FinalState finalState,
// PersistenceService persistenceService)
public StateFactory()
{
_stateByType = new Dictionary<StateType, IOperationState>()
{
{ StateType.Start, new StartingState(this) },
{ StateType.Middle, new MiddleState(this) },
{ StateType.Final, new FinalState(new PersistenceService()) }
};
}
public IOperationState GetByType(StateType stateType) =>
_stateByType[stateType];
}
Then we should register all our dependencies:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IPersistenceService, PersistenceService>();
services.AddTransient<StartingState>();
services.AddTransient<MiddleState>();
services.AddTransient<FinalState>();
services.AddTransient<MainService>();
services.AddTransient<OperatingClass>();
services.AddTransient<PersistenceService>();
services.AddTransient<StateFactory>();
}
Our states would look like this:
public class StartingState : IOperationState
{
private StateFactory _factory;
public StartingState(StateFactory stateFactory)
{
_factory = stateFactory;
}
public int ExecuteOperation(OperatingClass operatingClass)
{
// Do something...
// operatingClass.OperationState = new MiddleState();
operatingClass.OperationState = _factory.GetByType(StateType.Middle);
return operatingClass.Execute();
}
}
And MiddleState would look like this:
public class MiddleState : IOperationState
{
private StateFactory _factory;
public MiddleState(StateFactory stateFactory)
{
_factory = stateFactory;
}
public int ExecuteOperation(OperatingClass operatingClass)
{
//Do something with the value... let's supose the result is 123,
// but it does not matter rn;
operatingClass.value = 123;
//Here is the problem: FinalState needs the PersistenceService, who
//receives a injected class to acess the database;
operatingClass.OperationState = _factory.GetByType(StateType.Final);
//I want to execute it and return the sucess or failure of the persistence.
return operatingClass.Execute();
}
}
And Final state should look like this:
public class FinalState : IOperationState
{
private readonly IPersistenceService _persistenceService;
public FinalState(IPersistenceService persistenceService)
{
_persistenceService = persistenceService;
}
public int ExecuteOperation(OperatingClass operatingClass)
{
return _persistenceService
.PersistData(operatingClass.id, operatingClass.value)
? 200
: 503;
}
}
And other classes sush as OperatingClass would use StateFactory too:
public class OperatingClass
{
public IOperationState OperationState { get; set; }
public int id { get; set; }
public double value { get; set; }
public OperatingClass(int id, StateFactory stateFactory) //constructor
{
this.id = id;
value = 0;
// OperationState = new StartingState();
OperationState = stateFactory.GetByType(StateType.Start);
}
public int Execute()
{
return OperationState.ExecuteOperation(this);
}
}
And it is necessary to create concrete example of PersistenceService:
public interface IPersistenceService
{
bool PersistData(int id, double value);
}
public class PersistenceService : IPersistenceService
{
public bool PersistData(int id, double value)
{
throw new NotImplementedException();
}
}

Can't get the state after signing in with fluxor an Blazor

I want to implement state management into an application Blazor assembly, so I added Fluxor as library.
I've created an abstract root state which contain the shared propreties:
public abstract class RootState
{
public RootState(bool isLoading, string currentErrorMessage)
=> (IsLoading, CurrentErrorMessage) = (isLoading, currentErrorMessage);
public bool IsLoading { get; }
public string CurrentErrorMessage { get; }
public bool HasCurrentErrors => !string.IsNullOrWhiteSpace(CurrentErrorMessage);
}
Then, I created the Login State which inherits from Rootstate:
public class LoginState : RootState
{
public bool IsAuthenticated { get; set; }
public LoginResponseDto UserData { get; set; }
public LoginState(bool isLoading, string currentErrorMessage, bool isAuthenticated, LoginResponseDto userData)
:base(isLoading, currentErrorMessage)
{
IsAuthenticated = isAuthenticated;
UserData = userData;
}
}
After that, I created the feature class :
public class LoginFeature : Feature<LoginState>
{
public override string GetName() => nameof(LoginState);
protected override LoginState GetInitialState()
=> new LoginState(false, null, false, null);
}
Then the actions:
public class LoginAction
{
public LoginDto LoginDto { get; }
public LoginAction(LoginDto LoginDto)
{
this.LoginDto = LoginDto;
}
}
public class LoginAccessFailure : FailureAction
{
public LoginAccessFailure(string errorMessage)
:base(errorMessage)
{
}
}
public abstract class FailureAction
{
public string ErrorMessage { get; }
protected FailureAction(string errorMessage) => ErrorMessage = errorMessage;
}
After that I created the Reducer and Effect:
public class LoginReducer
{
[ReducerMethod]
public static LoginState ReduceLoginAction(LoginState state, LoginAction action)
=> new LoginState(true, null, false, state.UserData);
[ReducerMethod]
public static LoginState ReduceLoginSuccessAction(LoginState state, LoginActionSuccess action)
{
Console.WriteLine("State from Reducer", action);
var result = new LoginState(false, null, action.IsAuthenticated, action.UserData);
Console.WriteLine("Result from Reducer", result);
return result;
}
[ReducerMethod]
public static LoginState ReduceLoginFailureAction(LoginState state, LoginAccessFailure action)
=> new LoginState(false, action.ErrorMessage, false, null);
}
Effect:
public class LoginEffect : Effect<LoginAction>
{
private readonly IAccountService _accountService;
public LoginEffect(IAccountService accountService)
{
_accountService = accountService;
}
public override async Task HandleAsync(LoginAction action, IDispatcher dispatcher)
{
try
{
var loginResponse = await _accountService.Login(action.LoginDto);
await Task.Delay(TimeSpan.FromMilliseconds(1000));
dispatcher.Dispatch(new LoginActionSuccess(loginResponse, true));
}
catch (Exception e)
{
dispatcher.Dispatch(new LoginAccessFailure(e.Message));
}
}
}
When I want to call the dispatcher with this instruction dispatcher.Dispatch(new LoginAction(new LoginDto { Email = "test#email.com", Password = "test" })); I've got the result in the DevTools but there is not data in IState<LoginState> so I can't access to the state.
There is any error on my code please ?
Things to check
You have [Inject] before your private IMyState<T> MyState { get; set; }
You have a <StoreInitializer/> component in your main app component.
Your component descends from FluxorComponent or you manually subscribe to MyState.StateChanged and call InvokeAsync(StateHasChanged)

Change business layer class to be loosely coupled

I have below code I am working on. I am working on data access adon.net layer. I have problem with my business layer class called UserBAL. The problem is that I am creating instance of dal and dbmanager inside constructor of UserBAL. How can I change this to be loosely coupled for UserBAL? Hope you get my point.
public interface IEntity
{
int Id { get; set; }
int DoSomething(string one, int two);
}
public class User : IEntity
{
public int Id { get; set; }
public int DoSomething(string one, int two)
{
throw new NotImplementedException();
}
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
public class UserBal //busines logic
{
private readonly IRepositoryDal<User> _userRepositoryDal;
public UserBal()
{
_userRepositoryDal = new UserRepositoryDal(new DbManager("sqlserver?"));
}
public IEnumerable<User> SearchByName(string name)
{
return _userRepositoryDal.SearchByName(name);
}
}
interface IRepositoryDal<T> where T : IEntity
{
IEnumerable<T> SearchByName(string username);
T SearchById(string id);
void Update(T entity);
void Remove(T entity);
void Add(T entity);
}
public class UserRepositoryDal: IRepositoryDal<User>
{
private readonly IDbManager _dbManager;
public UserRepositoryDal(IDbManager dbManager)
{
//read from either singleton or configuration file !!
_dbManager = dbManager;
}
public IEnumerable<User> SearchByName(string username)
{
var parameters = new List<IDbDataParameter>
{
_dbManager.CreateParameter("#FirstName", 50, username, DbType.String),
};
var userDataTable = _dbManager.GetDataTable("storedpr2",
CommandType.StoredProcedure, parameters.ToArray());
foreach (DataRow dr in userDataTable.Rows)
{
var user = new User
{
Id = int.Parse(dr["Id"].ToString()),
Firstname = dr["Firstname"].ToString(),
Lastname = dr["LastName"].ToString(),
Email = dr["Email"].ToString()
};
yield return user;
}
}
public User SearchById(string id)
{
var parameters = new List<IDbDataParameter>
{
_dbManager.CreateParameter("#Id", 50, id, DbType.Int32),
};
var userDataTable = _dbManager.GetDataTable("storedpr2",
CommandType.StoredProcedure, parameters.ToArray());
return new User
{
Id = int.Parse(userDataTable.Rows[0]["Id"].ToString()),
Firstname = userDataTable.Rows[0]["Firstname"].ToString(),
Lastname = userDataTable.Rows[0]["LastName"].ToString(),
Email = userDataTable.Rows[0]["Email"].ToString()
};
}
public void Update(User entity)
{
throw new System.NotImplementedException();
}
public void Remove(User entity)
{
throw new System.NotImplementedException();
}
public void Add(User entity)
{
throw new System.NotImplementedException();
}
}
public partial class FrmLogin : Form
{
private readonly UserBal _userBal;
public FrmLogin()
{
InitializeComponent();
_userBal = new UserBal();
}
}
You should use dependency injection, and for required dependencies, you can use constructor injection, e.g:
public class UserBal
{
private readonly IRepositoryDal<User> _userRepositoryDal;
public UserBal(IRepositoryDal<User> userRepositoryDal)
{
_userRepositoryDal = userRepositoryDal
?? throw new ArgumentNullException(nameof(userRepositoryDal));
}
...
}
Dependency injection is the way to go. Here's a simplified example of your situation.
Given your classes could be like this:
public interface IEntity { }
public interface IRepositoryDal<T> where T : IEntity { }
public interface IDbManager { }
public class User : IEntity { }
public class UserBal //busines logic
{
[Injectivity.Attributes.Inject]
private IRepositoryDal<User> _userRepositoryDal;
}
public class UserRepositoryDal: IRepositoryDal<User>
{
[Injectivity.Attributes.Inject]
private IDbManager _dbManager;
}
public class DbManager : IDbManager
{
[Injectivity.Attributes.Construct()]
public DbManager([Injectivity.Attributes.Key("dbKey", typeof(string))] string x)
{
Console.WriteLine($"DbManager created with parameter \"{x}\"");
}
}
...then this code:
var context = Injectivity.Context.CreateRoot();
context.SetConfig<string>("dbKey", "sqlserver?");
context.SetFactory<IDbManager, DbManager>();
context.SetFactory<IRepositoryDal<User>, UserRepositoryDal>();
context.SetFactory<UserBal, UserBal>();
var user = context.Resolve<UserBal>();
...will produce this output:
DbManager created with parameter "sqlserver?"
Now, I've used a DI container that I wrote a number of years back. It's very flexible.
So the call to context.Resolve<UserBal>(); runs down the chain of seeing what needs to be injected to create all of the instances of all of the objects. Ultimately the creation of UserBal requires the DbManager to be created and hence the output.
You would normally not explicitly register each factory. Normally you would put attributes on all of the classes you want to register and then use context.Register(Assembly.LoadFrom("My.DLL")); or create an XML config file and call context.LoadConfig(XDocument.Load("config.xml"));.
You can even do things like this:
context.SetDecorator<IRepositoryDal<User>, UserRepositoryDalDecorator>();
This will cause all calls to context.Resolve<IRepositoryDal<User>>() or [Inject] attributes to automatically wrap the real instances in this decorator. Ideal to intercepting method calls for debugging purposes.

Avoid Casting in following Code by using Generics

I am new to generics and just wondering if it's possible to avoid the casting in the following code using better OO approach.
public class CollectorFactory
{
public static MyCollector Create(ICredential credential)
{
return new MyCollector(credential);
}
}
public class MyCollector {
public MyCredential Credential { get; set; }
public MyCollector(ICredential credential)
{
this.Credential = (MyCredential)credential;
}
public void Show()
{
Console.WriteLine(this.Credential.Username);
Console.WriteLine(this.Credential.AuthToken);
}
}
public class MyCredential : ICredential
{
public string Username{ get; set; }
public string AuthToken { get; set; }
}
public interface ICredential
{
}
Is there a way to save the casting of ICredential to MyCredential in MyCollector's Constructor? I don't have option to put Username and AuthToken in ICredential as it's implemented by two different Credentials that both have different set of properties. CollectorFactory will be returning different MyCollector instances in the future and both need to have different credentials.
Any help would be really appreciated.
I don't think it's possible given that you're implementing different credentials and trying to use them for ICredential as well.
Here is a way of doing this using generics. Please read my comments in the code.
public class CollectorFactory<T>
{
public T Create(ICredential credential)
{
return (T)Activator.CreateInstance(typeof(T), credential);
}
}
public class MyCollector : BaseCollector
{
public dynamic Credential { get; private set; }
public MyCollector(ICredential credential)
: base(credential)
{
this.Credential = credential;
}
// Having this method here limits your ability to make it more generic.
// Consider moving this to MyCredential since it refers to specific properties in MyCredential.
// If that is not what you want, then you must do a type check before calling methods/ accessing props in Credentials.
public void Show()
{
Console.WriteLine(this.Credential.Username);
Console.WriteLine(this.Credential.AuthToken);
}
}
public class MyCredential : ICredential
{
public string Username { get; set; }
public string AuthToken { get; set; }
}
public abstract class BaseCollector : ICredentialCollector
{
protected BaseCollector(ICredential credential)
{
if (credential == null)
{
throw new ArgumentNullException(nameof(credential));
}
}
}
public interface ICredentialCollector
{
}
public interface ICredential
{
}
// test implementation
public class TestClass
{
public void AuthFactoryTest()
{
// test auth instance
MyCredential auth = new MyCredential() {AuthToken = "asfgasdgdfg", Username = "xuser"};
// Create test factory
var fact = new CollectorFactory<MyCollector>();
var myCollector = fact.Create(auth);
// Do what you need to do to collector object
myCollector.Show();
}
}
Generics isn't the solution in this case. The issue here is that your factory is returning a specific type (MyCollector). A solution around this would be the following:
public class CollectorFactory
{
public static ICollector Create(MyCredential credential)
{
return new MyCollector(credential);
}
public static ICollector Create(OtherCredential credential)
{
return new OtherCollector(credential);
}
}
public interface ICollector
{
void Show();
}
public class MyCollector : ICollector
{
public MyCredential Credential { get; set; }
public MyCollector(MyCredential credential)
{
this.Credential = credential;
}
public void Show()
{
Console.WriteLine(this.Credential.Username);
Console.WriteLine(this.Credential.AuthToken);
}
}
public class MyCredential : ICredential
{
public string Username{ get; set; }
public string AuthToken { get; set; }
}
public interface ICredential
{
}
The above is pretty much the canonical example of the Factory design pattern.
Instead of overloads you could also do typechecking in the factory:
public class CollectorFactory
{
public static ICollector Create(ICredential credential)
{
if(credential.GetType() == typeof(MyCredential))
return new MyCollector((MyCredential) credential);
if(credential.GetType() == typeof(OtherCredential ))
return new OtherCollector((OtherCredential ) credential);
}
}

Integrating FluentValidation validator with base Entity class

I want to use AbstractValidator<T> inside base entity class.
[Serializable]
public abstract class Entity<T> where T : Entity<T>
{
public virtual Boolean Validate(AbstractValidator<T> validator)
{
return validator.Validate(this as ValidationContext<T>).IsValid;
}
// other stuff..
}
But one of my tests fails saying that Validate() method couldn't accept null as a paramter.
[Test]
public void CategoryDescriptionIsEmpty()
{
var category = new Category
{
Title = "some title",
Description = String.Empty
};
Assert.False(category.Validate(this.validator) == true);
}
[SetUp]
public void Setup()
{
this.validator = new CategoryValidator();
}
I'm using Visual Web Developer and at the moment can't install C# Developer Express to create console application to debug the error. Since that I don't know how do I debug inside the unit test. Alternatively it would be great if some explanation could be given!
Thanks!
This topic is old, but I found useful and made a little diferent:
public abstract class WithValidation<V> where V : IValidator
{
private IValidator v = Activator.CreateInstance<V>();
public bool IsValid => !(Errors.Count() > 0);
public IEnumerable<string> Errors
{
get
{
var results = v.Validate(this);
List<string> err = new List<string>();
if (!results.IsValid)
foreach (var item in results.Errors)
err.Add(item.ErrorMessage);
return err;
}
}
}
public class Client : WithValidation<ClientValidator>
{
public Guid Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class ClientValidator : AbstractValidator<Client>
{
public ClientValidator()
{
RuleFor(c => c.Name).NotNull();
RuleFor(c => c.Age).GreaterThan(10);
}
}
So you can use easier now like:
Client c = new Client();
var isvalid = c.IsValid;
IList<string> errors = c.Errors;
Ok!
So solution to my problem is next (at least this works as expected):
public abstract class Entity<T> where T : Entity<T>
{
public Boolean IsValid(IValidator<T> validator)
{
// var context = new ValidationContext(this);
// var instance = context.InstanceToValidate as T;
// return validator.Validate(instance).IsValid;
return validator.Validate(this as T).IsValid;
}
}
public class Rambo : Entity<Rambo>
{
public Int32 MadnessRatio { get; set; }
public Boolean CanHarmEverything { get; set; }
}
public class RamboValidator : AbstractValidator<Rambo>
{
public RamboValidator()
{
RuleFor(r => r.MadnessRatio).GreaterThan(100);
}
}
class Program
{
public static void Main(String[] args)
{
var ramboInstance = new Rambo {
MadnessRatio = 90
};
Console.WriteLine("Is Rembo still mad?");
Console.WriteLine(ramboInstance.IsValid(new RamboValidator()));
Console.ReadKey();
}
}

Categories