How to return a BadRequest from a Controller? - asp.net

I have a form that allow to the user to update his profile. When the form is submitted an ajax request is raised:
$.ajax({
url: url,
data: formData,
type: 'POST',
success: function (response) {
alert(true);
},
error: function (jqXHR, textStatus, errorThrown) {
//Handle error
}
});
inside the ajax request I need to check if an error happened, if yes, based on the generated error I want display a different exception message.
Now the main problem is that the method called return a ViewModel of the updated user, something like:
publi class UserController : Controller
{
private readonly IUserRepository _repo;
public UserController(IUserRepository repo)
{
_repo = repo;
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UpdateUser(UserProfileViewModel updateUser)
{
if(ModelState.IsValid)
{
updateUser = await _repo.UpdateUserAsync(updateUser);
}
return RedirectToAction("Profile");
}
The controller have a dependency injection of IUserRepository which actually handle the logic to update the user, eg:
public async Task<User> UpdateUserAsync(UserProfileViewModel updatedUser)
{
if(updatedUser.FirstName == "")
throw new Exception("FirstName not filled");
}
as you can see from the example above, if the FirstName is not filled, then an exception is thrown.
I want avoid the use of the exception; after some research I found BadRequest(), the problem is that BadRequest seems missing from AspNetCore, seems only available in the API version.
Someone have a good way to manage that?

#poke and #agua from mars are completely right; you should use model validation. If, however, your validation is a bit more complex and you have to handle it in your service, you can use this pattern. First, create a class that represents not just the data, but an indicator of the service's success in getting the data.
public class Result<T>
{
public bool HasError { get; set; }
public T Data { get; set; }
}
This above is very simplistic; you'd likely want more information.
Then, in your service, change the signature to return a Result<T> and add code to create the appropriate one:
public async Task<Result<User>> UpdateUserAsync(UserProfileViewModel updatedUser) {
if (updatedUser.FirstName == "")
return new Result<User> {
HadError = true,
Data = (User)null
};
// do something to save
return new Result<User> {
HadError = false,
Data = updatedUser
};
}
And then update your action to receive the Result<T> and return the appropriate result:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UpdateUser(UserProfileViewModel updateUser) {
var result = new Result<User> {
HadError = true,
Data = (User) null
};
if (ModelState.IsValid) {
result = await _repo.UpdateUserAsync(updateUser);
}
return result.HadError ? BadRequest() : RedirectToAction("Profile");
}
Again, for something like a required property, there are much better methods. I've found the above pattern useful when errors occur in the service and I want to communicate that fact to the controller/action/UI.

As poke told you, use can use model validation by decorating your UserProfileViewModel.FirstName with Required attribute :
public class UserProfileViewModel
{
[Required]
public string Name { get; set; }
}
I add filters to my configuration to factorize the code.
One to check model:
/// <summary>
/// Check api model state filter
/// </summary>
public class ApiCheckModelStateFilter : IActionFilter
{
private readonly PathString _apiPathString = PathString.FromUriComponent("/api");
/// <summary>
/// Called after the action executes, before the action result.
/// </summary>
/// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ActionExecutedContext" />.</param>
public void OnActionExecuted(ActionExecutedContext context)
{
}
/// <summary>
/// Called before the action executes, after model binding is complete.
/// </summary>
/// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext" />.</param>
/// <exception cref="InvalidOperationException"></exception>
public void OnActionExecuting(ActionExecutingContext context)
{
if (!context.HttpContext.Request.Path.StartsWithSegments(_apiPathString))
{
return;
}
var state = context.ModelState;
if (!state.IsValid)
{
var message = string.Join("; ", state.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
throw new InvalidOperationException(message);
}
}
}
And another one to manage status code depending on exception:
/// <summary>
/// Api exception filter
/// </summary>
public class ApiExceptionFilter : IExceptionFilter, IAsyncExceptionFilter
{
private readonly PathString _apiPathString = PathString.FromUriComponent("/api");
private readonly ILogger<ApiExceptionFilter> _logger;
/// <summary>
/// Initialize a new instance of <see cref="ApiExceptionFilter"/>
/// </summary>
/// <param name="logger">A logger</param>
public ApiExceptionFilter(ILogger<ApiExceptionFilter> logger)
{
_logger = logger;
}
/// <summary>
/// Called after an action has thrown an <see cref="T:System.Exception" />.
/// </summary>
/// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ExceptionContext" />.</param>
/// <returns>
/// A <see cref="T:System.Threading.Tasks.Task" /> that on completion indicates the filter has executed.
/// </returns>
public Task OnExceptionAsync(ExceptionContext context)
{
Process(context);
return Task.CompletedTask;
}
/// <summary>
/// Called after an action has thrown an <see cref="T:System.Exception" />.
/// </summary>
/// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ExceptionContext" />.</param>
public void OnException(ExceptionContext context)
{
Process(context);
}
private void Process(ExceptionContext context)
{
var e = context.Exception;
_logger.LogError(e, e.Message);
if (!context.HttpContext.Request.Path.StartsWithSegments(_apiPathString))
{
return;
}
else if (e is EntityNotFoundException)
{
context.Result = WriteError(HttpStatusCode.NotFound, e);
}
else if (e is InvalidOperationException)
{
context.Result = WriteError(HttpStatusCode.BadRequest, e);
}
else if (e.GetType().Namespace == "Microsoft.EntityFrameworkCore")
{
context.Result = WriteError(HttpStatusCode.BadRequest, e);
}
else
{
context.Result = WriteError(HttpStatusCode.InternalServerError, e);
}
}
private IActionResult WriteError(HttpStatusCode statusCode, Exception e)
{
var result = new ApiErrorResult(e.Message, e)
{
StatusCode = (int)statusCode,
};
return result;
}
}
It returns an ApiErrorResult with the error message in the reason phrase:
/// <summary>
/// Api error result
/// </summary>
/// <seealso cref="Microsoft.AspNetCore.Mvc.ObjectResult" />
public class ApiErrorResult : ObjectResult
{
private readonly string _reasonPhrase;
/// <summary>
/// Initializes a new instance of the <see cref="ApiErrorResult"/> class.
/// </summary>
/// <param name="reasonPhrase">The reason phrase.</param>
/// <param name="value">The value.</param>
public ApiErrorResult(string reasonPhrase, object value) : base(value)
{
_reasonPhrase = reasonPhrase;
}
/// <inheritdoc />
public override async Task ExecuteResultAsync(ActionContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var reasonPhrase = _reasonPhrase;
reasonPhrase = reasonPhrase.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)[0];
context.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = reasonPhrase;
await base.ExecuteResultAsync(context);
}
}
Thoses filters are set upped in the Startup ConfigureServices method:
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services">A service collection</param>
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(configure =>
{
var filters = configure.Filters;
filters.Add<ApiExceptionFilter>();
filters.Add<ApiCheckModelStateFilter>();
})
.AddJsonOptions(configure =>
{
configure.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
This way I don't need to check if the model is valid in controllers methods:
[HttpPost]
[ValidateAntiForgeryToken]
public Task<IActionResult> UpdateUser(UserProfileViewModel updateUser) => _repo.UpdateUserAsync(updateUser);

Related

How to fix: OnNavigatedFrom(NavigationParameters)': no suitable method found to override

3 month project about to be scrapped because of this.
Makes zero sense why this does not work.
I've tried rebooting etc. I have a sample project with the same versions of Forms etc which works.
I've tried taking the AppMapViewModelBase from that project into mine and the error still there.
Any ideas?
using System;
using System.ComponentModel;
using Prism;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using Xamarin.Essentials;
using Xamarin.Forms;
namespace bla.Infrastructure {
public abstract class AppMapViewModelBase : BindableBase, IInitialize, INavigationAware, IConfirmNavigation, IDestructible
{
private bool _isBusy;
public bool IsBusy
{
get => _isBusy;
set => SetProperty(ref _isBusy, value);
}
private int _cartItemCount;
public int CartItemCount
{
// get => _password;
get { return App.Current.CartItemCount; }
//set => SetProperty(ref _cartItemCount, value);
set
{
_cartItemCount = value;
App.Current.CartItemCount = value;
RaisePropertyChanged();
}
}
const string RootUriPrependText = "/";
DelegateCommand<string> _navigateAbsoluteCommand;
DelegateCommand<string> _navigateCommand;
DelegateCommand<string> _navigateModalCommand;
DelegateCommand<string> _navigateNonModalCommand;
private bool _isNotConnected;
public bool IsNotConnected
{
get
{
if (DesignMode.IsDesignModeEnabled)
{
return false;
}
else
{
return _isNotConnected;
}
}
set
{
SetProperty(ref _isNotConnected, value);
}
}
/// <summary>
/// Gets the navigate absolute command.
/// </summary>
/// <value>The navigate absolute command.</value>
public DelegateCommand<string> NavigateAbsoluteCommand => _navigateAbsoluteCommand ?? (_navigateAbsoluteCommand = new DelegateCommand<string>(NavigateAbsoluteCommandExecute, CanNavigateAbsoluteCommandExecute));
/// <summary>
/// Gets the navigate command.
/// </summary>
/// <value>The navigate command.</value>
public DelegateCommand<string> NavigateCommand => _navigateCommand ?? (_navigateCommand = new DelegateCommand<string>(NavigateCommandExecute, CanNavigateCommandExecute));
/// <summary>
/// Gets the navigate modal command.
/// </summary>
/// <value>The navigate modal command.</value>
public DelegateCommand<string> NavigateModalCommand => _navigateModalCommand ?? (_navigateModalCommand = new DelegateCommand<string>(NavigateModalCommandExecute, CanNavigateModalCommandExecute));
/// <summary>
/// Gets the navigate non modal command.
/// </summary>
/// <value>The navigate non modal command.</value>
public DelegateCommand<string> NavigateNonModalCommand => _navigateNonModalCommand ?? (_navigateNonModalCommand = new DelegateCommand<string>(NavigateNonModalCommandExecute, CanNavigateNonModalCommandExecute));
/// <summary>
/// Gets the navigation service.
/// </summary>
/// <value>The navigation service.</value>
protected INavigationService NavigationService { get; }
/// <summary>
/// Initializes a new instance of the <see cref="AppMapViewModelBase"/> class.
/// </summary>
/// <param name="navigationService">The navigation service.</param>
/// <exception cref="System.ArgumentNullException">navigationService</exception>
protected AppMapViewModelBase(INavigationService navigationService)
{
if (navigationService == null)
{
throw new ArgumentNullException(nameof(navigationService));
}
this.NavigationService = navigationService;
Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
IsNotConnected = Connectivity.NetworkAccess != NetworkAccess.Internet;
}
void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
{
if (e.NetworkAccess != NetworkAccess.Internet)
{
//NavigationService.NavigateAsync("NavigationPage/NoInternet");
}
IsNotConnected = e.NetworkAccess != NetworkAccess.Internet;
}
/// <summary>
/// Determines whether this instance accepts being navigated away from. This method is invoked by Prism before a navigation operation and is a member of IConfirmNavigation.
/// </summary>
/// <param name="parameters">The navigation parameters.</param>
/// <returns><c>True</c> if navigation can continue, <c>False</c> if navigation is not allowed to continue</returns>
public virtual bool CanNavigate(INavigationParameters parameters)
{
return true;
}
/// <summary>
/// Determines whether this instance can execute the NavigateAbsoluteCommand.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns><c>true</c> if this instance can execute NavigateAbsoluteCommand; otherwise, <c>false</c>.</returns>
protected virtual bool CanNavigateAbsoluteCommandExecute(string uri)
{
return !String.IsNullOrEmpty(uri);
}
/// <summary>
/// Determines whether this instance can execute the NavigateAbsoluteCommand.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns><c>true</c> if this instance can execute NavigateAbsoluteCommand; otherwise, <c>false</c>.</returns>
protected virtual bool CanNavigateCommandExecute(string uri)
{
return !String.IsNullOrEmpty(uri);
}
/// <summary>
/// Determines whether this instance can execute the NavigateModalCommand.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns><c>true</c> if this instance can execute NavigateModalCommand; otherwise, <c>false</c>.</returns>
protected virtual bool CanNavigateModalCommandExecute(string uri)
{
return !String.IsNullOrEmpty(uri);
}
/// <summary>
/// Determines whether this instance can execute the NavigateNonModalCommand.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns><c>true</c> if this instance can execute NavigateNonModalCommand; otherwise, <c>false</c>.</returns>
protected virtual bool CanNavigateNonModalCommandExecute(string uri)
{
return !String.IsNullOrEmpty(uri);
}
/// <summary>
/// <p>Invoked by Prism Navigation when the instance is removed from the navigation stack.</p>
/// <p>Deriving class can override and perform any required clean up.</p>
/// </summary>
public virtual void Destroy()
{
}
/// <summary>
/// Navigates to the uri after creating a new navigation root. (Effectively replacing the Application MainPage.)
/// </summary>
/// <param name="uri">The uri text.</param>
/// <returns>Task.</returns>
protected virtual async void NavigateAbsoluteCommandExecute(string uri)
{
if (!CanNavigateAbsoluteCommandExecute(uri))
{
return;
}
if (!uri.StartsWith(RootUriPrependText))
{
uri = string.Concat(RootUriPrependText, uri);
}
await this.NavigationService.NavigateAsync(uri, null, false,false);
}
/// <summary>
/// Navigates to the uri.
/// </summary>
/// <param name="uri">The uri text.</param>
/// <returns>Task.</returns>
protected virtual async void NavigateCommandExecute(string uri)
{
if (!CanNavigateCommandExecute(uri))
{
return;
}
await this.NavigationService.NavigateAsync(uri);
}
/// <summary>
/// Navigates to the uri using a Modal navigation.
/// </summary>
/// <param name="uri">The uri text.</param>
/// <returns>Task.</returns>
protected virtual async void NavigateModalCommandExecute(string uri)
{
if (!CanNavigateModalCommandExecute(uri))
{
return;
}
await this.NavigationService.NavigateAsync(uri,null, useModalNavigation: true,animated:false);
}
/// <summary>
/// Navigates to the uri using Non-Modal navigation.
/// </summary>
/// <param name="uri">The uri text.</param>
/// <returns>Task.</returns>
protected virtual async void NavigateNonModalCommandExecute(string uri)
{
if (!CanNavigateNonModalCommandExecute(uri))
{
return;
}
await this.NavigationService.NavigateAsync(uri,null, useModalNavigation: false,false);
}
/// <summary>
/// Invoked by Prism immediately after the ViewModel has been created.
/// </summary>
/// <param name="parameters">The parameters.</param>
public virtual void InitializeAsync(INavigationParameters parameters)
{
}
/// <summary>
/// Invoked by Prism after navigating away from viewmodel's page.
/// </summary>
/// <param name="parameters">The parameters.</param>
public virtual void OnNavigatedFrom(INavigationParameters parameters)
{
}
/// <summary>
/// Invoked by Prism after navigating to the viewmodel's page.
/// </summary>
/// <param name="parameters">The parameters.</param>
public virtual void OnNavigatedTo(INavigationParameters parameters)
{
}
public virtual void Initialize(INavigationParameters parameters)
{
}
}
}
The signature of the method is wrong.
The prefix I is missing before NavigationParameters, because OnNavigatedFrom expects an interface of type INavigationParameters as parameter:
Change NavigationParameters to INavigationParameters
public override void OnNavigatedFrom (INavigationParameters navigationParameters)
{
}

Blazor multi-user questionaire

I need to create an app thats basically functions like a multi-user realtime questionnaire or trivia.
I've gotten to the point where i've created a questionnaire and associated users to it, but i'm hitting a road block on how to go forward.
Basically what i need to do next is
For each question in the questionnaire:
1) have the server send the users a question
2) wait for all of the users to respond or a set timeout period
3) display to the users a question result page
I was wondering how i should attempt to do something like this. Any help or resources would be wonderful
I am building a chat application that has something very similar using Server Side Blazor.
The way I did was I inject a class I created called SubscriberService:
#inject Services.SubscriberService SubscriberService
Then in my ConfigureServices method in Startup.cs I add this:
services.AddSingleton<SubscriberService>();
The Add Singleton means only 1 instance will be created for all your browser instances (users).
This makes my Subscriber Services available to all my subcribers, which is just a name, Guid Id and a callback delegate
#region using statements
using DataJuggler.UltimateHelper.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
#endregion
namespace BlazorChat.Services
{
#region class SubscriberService
/// <summary>
/// This class is used to subscribe to services, so other windows get a notification a new message
/// came in.
/// </summary>
public class SubscriberService
{
#region Private Variables
private int count;
private Guid serverId;
private List<SubscriberCallback> subscribers;
#endregion
#region Constructor
/// <summary>
/// Create a new instance of a 'SubscriberService' object.
/// </summary>
public SubscriberService()
{
// Create a new Guid
this.ServerId = Guid.NewGuid();
Subscribers = new List<SubscriberCallback>();
}
#endregion
#region Methods
#region BroadcastMessage(SubscriberMessage message)
/// <summary>
/// This method Broadcasts a Message to everyone that ins't blocked.
/// Note To Self: Add Blocked Feature
/// </summary>
public void BroadcastMessage(SubscriberMessage message)
{
// if the value for HasSubscribers is true
if ((HasSubscribers) && (NullHelper.Exists(message)))
{
// Iterate the collection of SubscriberCallback objects
foreach (SubscriberCallback subscriber in Subscribers)
{
// if the Callback exists
if ((subscriber.HasCallback) && (subscriber.Id != message.FromId))
{
// to do: Add if not blocked
// send the message
subscriber.Callback(message);
}
}
}
}
#endregion
#region GetSubscriberNames()
/// <summary>
/// This method returns a list of Subscriber Names ()
/// </summary>
public List<string> GetSubscriberNames()
{
// initial value
List<string> subscriberNames = null;
// if the value for HasSubscribers is true
if (HasSubscribers)
{
// create the return value
subscriberNames = new List<string>();
// Get the SubscriberNamesl in alphabetical order
List<SubscriberCallback> sortedNames = Subscribers.OrderBy(x => x.Name).ToList();
// Iterate the collection of SubscriberService objects
foreach (SubscriberCallback subscriber in sortedNames)
{
// Add this name
subscriberNames.Add(subscriber.Name);
}
}
// return value
return subscriberNames;
}
#endregion
#region Subscribe(string subscriberName)
/// <summary>
/// method returns a message with their id
/// </summary>
public SubscriberMessage Subscribe(SubscriberCallback subscriber)
{
// initial value
SubscriberMessage message = null;
// If the subscriber object exists
if ((NullHelper.Exists(subscriber)) && (HasSubscribers))
{
// Add this item
Subscribers.Add(subscriber);
// return a test message for now
message = new SubscriberMessage();
// set the message return properties
message.FromName = "Subscriber Service";
message.FromId = ServerId;
message.ToName = subscriber.Name;
message.ToId = subscriber.Id;
message.Data = Subscribers.Count.ToString();
message.Text = "Subscribed";
}
// return value
return message;
}
#endregion
#region Unsubscribe(Guid id)
/// <summary>
/// This method Unsubscribe
/// </summary>
public void Unsubscribe(Guid id)
{
// if the value for HasSubscribers is true
if ((HasSubscribers) && (Subscribers.Count > 0))
{
// attempt to find this callback
SubscriberCallback callback = Subscribers.FirstOrDefault(x => x.Id == id);
// If the callback object exists
if (NullHelper.Exists(callback))
{
// Remove this item
Subscribers.Remove(callback);
// create a new message
SubscriberMessage message = new SubscriberMessage();
// set the message return properties
message.FromId = ServerId;
message.FromName = "Subscriber Service";
message.Text = callback.Name + " has left the conversation.";
message.ToId = Guid.Empty;
message.ToName = "Room";
// Broadcast the message to everyone
BroadcastMessage(message);
}
}
}
#endregion
#endregion
#region Properties
#region Count
/// <summary>
/// This property gets or sets the value for 'Count'.
/// </summary>
public int Count
{
get { return count; }
set { count = value; }
}
#endregion
#region HasSubscribers
/// <summary>
/// This property returns true if this object has a 'Subscribers'.
/// </summary>
public bool HasSubscribers
{
get
{
// initial value
bool hasSubscribers = (this.Subscribers != null);
// return value
return hasSubscribers;
}
}
#endregion
#region ServerId
/// <summary>
/// This property gets or sets the value for 'ServerId'.
/// </summary>
public Guid ServerId
{
get { return serverId; }
set { serverId = value; }
}
#endregion
#region Subscribers
/// <summary>
/// This property gets or sets the value for 'Subscribers'.
/// </summary>
public List<SubscriberCallback> Subscribers
{
get { return subscribers; }
set { subscribers = value; }
}
#endregion
#endregion
}
#endregion
}
Here is my SubscriberCallback.cs:
#region using statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
#endregion
namespace BlazorChat
{
#region class SubscriberCallback
/// <summary>
/// This class is used to register a subscriber with the ChatService
/// </summary>
public class SubscriberCallback
{
#region Private Variables
private string name;
private Guid id;
private Callback callback;
private List<Guid> blockedList;
#endregion
#region Constructor
/// <summary>
/// Create a new instance of a SubscriberCallback instance
/// </summary>
public SubscriberCallback(string name)
{
// store the Name
Name = name;
// Create the Id
Id = Guid.NewGuid();
// create a BlockedList
BlockedList = new List<Guid>();
}
#endregion
#region Methods
#region ToString()
/// <summary>
/// This method is used to return the Name of the Subscriber when ToString is called.
/// </summary>
/// <returns></returns>
public override string ToString()
{
// return the Name when ToString is called
return this.Name;
}
#endregion
#endregion
#region Properties
#region BlockedList
/// <summary>
/// This property gets or sets the value for 'BlockedList'.
/// </summary>
public List<Guid> BlockedList
{
get { return blockedList; }
set { blockedList = value; }
}
#endregion
#region Callback
/// <summary>
/// This property gets or sets the value for 'Callback'.
/// </summary>
public Callback Callback
{
get { return callback; }
set { callback = value; }
}
#endregion
#region HasBlockedList
/// <summary>
/// This property returns true if this object has a 'BlockedList'.
/// </summary>
public bool HasBlockedList
{
get
{
// initial value
bool hasBlockedList = (this.BlockedList != null);
// return value
return hasBlockedList;
}
}
#endregion
#region HasCallback
/// <summary>
/// This property returns true if this object has a 'Callback'.
/// </summary>
public bool HasCallback
{
get
{
// initial value
bool hasCallback = (this.Callback != null);
// return value
return hasCallback;
}
}
#endregion
#region HasName
/// <summary>
/// This property returns true if the 'Name' exists.
/// </summary>
public bool HasName
{
get
{
// initial value
bool hasName = (!String.IsNullOrEmpty(this.Name));
// return value
return hasName;
}
}
#endregion
#region Id
/// <summary>
/// This property gets or sets the value for 'Id'.
/// </summary>
public Guid Id
{
get { return id; }
set { id = value; }
}
#endregion
#region Name
/// <summary>
/// This property gets or sets the value for 'Name'.
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
#endregion
#endregion
}
#endregion
}
And here is my delegate class:
/// <summary>
/// This delegate is used by the SubscriberService to send messages to any subscribers
/// </summary>
/// <returns></returns>
public delegate void Callback(SubscriberMessage message);
Then in my component I call methods like this:
// Send this message to all clients
SubscriberService.BroadcastMessage(message);
And each client has a listen method:
SubscriberCallback callback = new SubscriberCallback(SubscriberName);
callback.Callback = Listen;
callback.Name = SubscriberName;
// Get a message back
SubscriberMessage message = SubscriberService.Subscribe(callback);
Here is my Listen method, it just waits for messages;
using DataJuggler.UltimateHelper.Core; // Nuget package
public void Listen(SubscriberMessage message)
{
// if the message exists (part of DataJuggler.UltimateHelper.Core Nuget Package)
// Same as (message != null)
if (NullHelper.Exists(message))
{
// if the message contains Joined the conversation
if ((message.Text.Contains("joined the conversation")) ||
(message.Text.Contains("left the conversation")))
{
// this updates my list of 'Whose On' whenever a user joins or leaves
// Get the Names again
this.Names = SubscriberService.GetSubscriberNames();
// Update the UI
Refresh();
}
else
{
// my display message code is here
}
}
And finally here is my Subscriber message:
#region using statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
#endregion
namespace BlazorChat
{
#region class SubscriberMessage
/// <summary>
/// This class is used to send information between components / pages.
/// </summary>
public class SubscriberMessage
{
#region Private Variables
private string text;
private Guid fromId;
private Guid toId;
private string fromName;
private string toName;
private object data;
private string valid;
private DateTime sent;
private string invalidReason;
#endregion
#region Properties
#region Data
/// <summary>
/// This property gets or sets the value for 'Data'.
/// </summary>
public object Data
{
get { return data; }
set { data = value; }
}
#endregion
#region FromId
/// <summary>
/// This property gets or sets the value for 'FromId'.
/// </summary>
public Guid FromId
{
get { return fromId; }
set { fromId = value; }
}
#endregion
#region FromName
/// <summary>
/// This property gets or sets the value for 'FromName'.
/// </summary>
public string FromName
{
get { return fromName; }
set { fromName = value; }
}
#endregion
#region HasText
/// <summary>
/// This property returns true if the 'Text' exists.
/// </summary>
public bool HasText
{
get
{
// initial value
bool hasText = (!String.IsNullOrEmpty(this.Text));
// return value
return hasText;
}
}
#endregion
#region InvalidReason
/// <summary>
/// This property gets or sets the value for 'InvalidReason'.
/// </summary>
public string InvalidReason
{
get { return invalidReason; }
set { invalidReason = value; }
}
#endregion
#region Sent
/// <summary>
/// This property gets or sets the value for 'Sent'.
/// </summary>
public DateTime Sent
{
get { return sent; }
set { sent = value; }
}
#endregion
#region Text
/// <summary>
/// This property gets or sets the value for 'Text'.
/// </summary>
public string Text
{
get { return text; }
set { text = value; }
}
#endregion
#region ToId
/// <summary>
/// This property gets or sets the value for 'ToId'.
/// </summary>
public Guid ToId
{
get { return toId; }
set { toId = value; }
}
#endregion
#region ToName
/// <summary>
/// This property gets or sets the value for 'ToName'.
/// </summary>
public string ToName
{
get { return toName; }
set { toName = value; }
}
#endregion
#region Valid
/// <summary>
/// This property gets or sets the value for 'Valid'.
/// </summary>
public string Valid
{
get { return valid; }
set { valid = value; }
}
#endregion
#endregion
}
#endregion
}
BlazorChat is a sample project I am still working on as part of my Nuget package:
DataJuggler.Blazor.Components, which contains a Sprite component, ProgressBar and Validation component.
The full code is here in the Samples folder of this project if I left anything out.
https://github.com/DataJuggler/DataJuggler.Blazor.Components
Documentation and SQL scripts are missing, so sorry, its a work in progress.

Angular POST to Web API

So I am trying to create a register page with my existing web API.
There are a few post methods on the AccountController, but I have commented them all out apart from 2. Here is what they look like:
/// <summary>
/// Handles all account related functions.
/// </summary>
[Authorize]
[RoutePrefix("Account")]
public class AccountController : ApiController
{
private const string LocalLoginProvider = "Local";
private readonly IUnitOfWork unitOfWork;
private readonly UserService<User> service;
private readonly UserLoginService userLoginService;
private readonly RoleService<User> roleService;
private readonly ISecureDataFormat<AuthenticationTicket> accessTokenFormat;
/// <summary>
/// Parameterless Constructor which references the startup config auth options access token format.
/// </summary>
public AccountController()
: this(StartupConfig.OAuthOptions.AccessTokenFormat)
{
}
/// <summary>
/// Constructor with the access token format parameter.
/// </summary>
/// <param name="accessTokenFormat">The parameter for specifying the access token format.</param>
public AccountController(ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
{
this.unitOfWork = new UnitOfWork<DatabaseContext>();
this.service = new UserService<User>(this.unitOfWork, false, true);
this.userLoginService = new UserLoginService(this.unitOfWork);
this.roleService = new RoleService<User>(this.unitOfWork);
this.accessTokenFormat = accessTokenFormat;
}
// POST api/account/register
/// <summary>
/// Registers a new user with the system.
/// </summary>
/// <param name="model">The model representing the user.</param>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
[Route("Register")]
[ResponseType(typeof(r3plica.Identity.IdentityResult))]
public async Task<IHttpActionResult> Register(RegisterBindingViewModel model)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var user = new User
{
UserName = model.Email,
Email = model.Email
};
var result = await service.CreateAsync(user, model.Password);
var errorResult = GetErrorResult(result);
if (errorResult != null)
return errorResult;
await this.unitOfWork.SaveChangesAsync();
return Ok(user.Id);
}
// POST api/account/logout
/// <summary>
/// Logs the current user out.
/// </summary>
/// <returns></returns>
[HttpPost]
[Route("Logout")]
public IHttpActionResult Logout()
{
Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
return Ok();
}
}
and my angular controller looks like this:
.controller('RegisterController', ['$state', 'Api', function ($state, api) {
var self = this;
self.model = {
email: '',
password: '',
confirmPassword: ''
};
self.register = function () {
api.post('account/register', self.model).then(function (response) {
console.log(response);
}, function (error) {
alert('error!');
});
};
}]);
If I comment out the Logout function in my AccountController, then try to register, it registers fine and all the fields are populated and correct.
If I uncomment Logout and send the same form, I get an error:
Multiple actions were found that match the request:
Register on type AccountController
Logout on type AccountController
As you can see Logout is parameterless, so I am not sure why I am getting this error. Can someone tell me what I am doing wrong?
It turns out that there is a very important line of code that is required in your WebApiConfig
config.MapHttpAttributeRoutes();
Without this, having a route set up would be ignored, so saying that this bit of code:
[Route("Register")]
would not be hit. Because both Register and Logout were decorated with [HttpPost], it meant that they were being treated as the same.

HttpModule Init method were not called

Recently I was implementing a HttpMoudle. and stuck with the error which is said System.NullReferenceException: Object reference not set to an instance of an object.
Here is my code .
public class MyHttpModuler : IHttpModule
{
private static IAuthProvider authProvider=null;
#region IHttpModule members
/// <summary>
/// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
/// </summary>
public void Dispose()
{
authProvider.Dispose();
authProvider = null;
}
public void Init(HttpApplication application)
{
authProvider = new BasicAuthProvider("achievo");
application.BeginRequest += new EventHandler(Application_BeginRequest);
}
private void Application_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpRequest request = app.Request;
HttpResponse response = app.Response;
TryAuthenticate(app);
}
#endregion
#region private method
/// <summary>
/// Tries to authenticate the user
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
private bool TryAuthenticate(HttpApplication context)
{
string authHeader = context.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authHeader))
{
if (authHeader.StartsWith("basic ", StringComparison.InvariantCultureIgnoreCase))
{
string userNameAndPassword = Encoding.Default.GetString(
Convert.FromBase64String(authHeader.Substring(6)));
string[] parts = userNameAndPassword.Split(':');
if (authProvider.IsValidUser(parts[0], parts[1]))
{
//the authProvider object sometimes is null .Why?
return true;
}
}
}
return false;
}
#endregion
}
public class BasicAuthProvider : IAuthProvider
{
#region IAuthProvider Members
public string DomainName { get; set; }
public BasicAuthProvider(string sDmName)
{
DomainName = sDmName;
}
public bool IsValidUser(string userName, string password)
{
string sFullName = "LDAP://" + DomainName + ".com";
bool bLogin = ADHelper.IsAuthenticated(sFullName, DomainName + #"\" + userName, password);
return bLogin;
}
public bool IsRequestAllowed(HttpRequest request,string sName)
{
return sName == "joe.wang";
}
public void Dispose()
{
}
#endregion
}
Especially when multiple user get into the Website. the exception of NullReferenceException happened. and when I debug, I found sometimes Init method may not be called. Maybe that is the why the exception happened . Anybody could help me to check it ?Thanks
The problem is (as Aristos pointed out) that you have made the authProvider static.
That means that when several users are generating requests at the same time, there will be several instances of you HttpModule running simultaneously. But they will all share one authProvider.
So it's possible that User A starts a request, causing a new instance of you module to run it's Init method. Then the thread handling that request is put on hold and another request from User B starts, causing another a new intance of the module to run it's Init method. This will overwrite the instance in authProvider that was put there in User A's request . Then that thread is put on hold and the previous thread from User A is resumed and finishes processing the request, thereby Disposing the authProvider (set by User B's request) and setting it to null. After that the request from User B once again resumes and finds that authProvider is now null.
Based on the code you have provided, it seems like the simplest possible solution is to simply remove the static keyword from the line:
private static IAuthProvider authProvider=null;
Then each instance of the HttpModule will have it's own copy of the authProvider and one request will not affect the state of another.
you have set as static your main object authProvider, so you need to make synchronize when you make it and delete it.
private static IAuthProvider authProvider=null;
So you need to write it as:
public class MyHttpModuler : IHttpModule
{
//can not be shared with others request.
//private IAuthProvider authProvider = null;
//We do not need it now.
//private static readonly object _lockObj = new object();
#region IHttpModule members
/// <summary>
/// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
/// </summary>
public void Dispose()
{
//authProvider.Dispose();
//authProvider = null;
}
public void Init(HttpApplication application)
{
application.BeginRequest += new EventHandler(Application_BeginRequest);
}
private void Application_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpRequest request = app.Request;
HttpResponse response = app.Response;
TryAuthenticate(app);
}
#endregion
#region private method
/// <summary>
/// Tries to authenticate the user
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
private bool TryAuthenticate(HttpApplication context)
{
IAuthProvider authProvider = new BasicAuthProvider("achievo");
string authHeader = context.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authHeader))
{
if (authHeader.StartsWith("basic ", StringComparison.InvariantCultureIgnoreCase))
{
string userNameAndPassword = Encoding.Default.GetString(
Convert.FromBase64String(authHeader.Substring(6)));
string[] parts = userNameAndPassword.Split(':');
if (authProvider.IsValidUser(parts[0], parts[1]))
{
//the authProvider object sometimes is null .Why?
authProvider=null;
return true;
}
}
}
authProvider=null;
return false;
}
#endregion
}

Saving Entity Framework objects in ViewState

Given two tables, Make and Model, where a make can contain many models and resulting in the following EF generated entity types...
/// <KeyProperties>
/// ID
/// </KeyProperties>
[global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="CarsModel", Name="Make")]
[global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
[global::System.Serializable()]
public partial class Make : global::System.Data.Objects.DataClasses.EntityObject
{
/// <summary>
/// Create a new Make object.
/// </summary>
/// <param name="id">Initial value of ID.</param>
public static Make CreateMake(int id)
{
Make make = new Make();
make.ID = id;
return make;
}
/// <summary>
/// There are no comments for Property ID in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public int ID
{
get
{
return this._ID;
}
set
{
this.OnIDChanging(value);
this.ReportPropertyChanging("ID");
this._ID = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
this.ReportPropertyChanged("ID");
this.OnIDChanged();
}
}
private int _ID;
partial void OnIDChanging(int value);
partial void OnIDChanged();
/// <summary>
/// There are no comments for Property Name in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public string Name
{
get
{
return this._Name;
}
set
{
this.OnNameChanging(value);
this.ReportPropertyChanging("Name");
this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
this.ReportPropertyChanged("Name");
this.OnNameChanged();
}
}
private string _Name;
partial void OnNameChanging(string value);
partial void OnNameChanged();
/// <summary>
/// There are no comments for Models in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("CarsModel", "FK_Model_Make", "Model")]
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.Data.Objects.DataClasses.EntityCollection<Model> Models
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection<Model>("CarsModel.FK_Model_Make", "Model");
}
set
{
if ((value != null))
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection<Model>("CarsModel.FK_Model_Make", "Model", value);
}
}
}
}
/// <KeyProperties>
/// ID
/// </KeyProperties>
[global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="CarsModel", Name="Model")]
[global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
[global::System.Serializable()]
public partial class Model : global::System.Data.Objects.DataClasses.EntityObject
{
/// <summary>
/// Create a new Model object.
/// </summary>
/// <param name="id">Initial value of ID.</param>
public static Model CreateModel(int id)
{
Model model = new Model();
model.ID = id;
return model;
}
/// <summary>
/// There are no comments for Property ID in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public int ID
{
get
{
return this._ID;
}
set
{
this.OnIDChanging(value);
this.ReportPropertyChanging("ID");
this._ID = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
this.ReportPropertyChanged("ID");
this.OnIDChanged();
}
}
private int _ID;
partial void OnIDChanging(int value);
partial void OnIDChanged();
/// <summary>
/// There are no comments for Property Name in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public string Name
{
get
{
return this._Name;
}
set
{
this.OnNameChanging(value);
this.ReportPropertyChanging("Name");
this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
this.ReportPropertyChanged("Name");
this.OnNameChanged();
}
}
private string _Name;
partial void OnNameChanging(string value);
partial void OnNameChanged();
/// <summary>
/// There are no comments for Make in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("CarsModel", "FK_Model_Make", "Make")]
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public Make Make
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Make>("CarsModel.FK_Model_Make", "Make").Value;
}
set
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Make>("CarsModel.FK_Model_Make", "Make").Value = value;
}
}
/// <summary>
/// There are no comments for Make in the schema.
/// </summary>
[global::System.ComponentModel.BrowsableAttribute(false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.Data.Objects.DataClasses.EntityReference<Make> MakeReference
{
get
{
return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Make>("CarsModel.FK_Model_Make", "Make");
}
set
{
if ((value != null))
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference<Make>("CarsModel.FK_Model_Make", "Make", value);
}
}
}
I am trying to store an instance of the Make class into ASP.NET ViewState, along with the associated models as follows...
private Make Make {
get { return this.ViewState[#"EditContext"] as Make; }
set { this.ViewState[#"EditContext"] = value; }
}
and
this.Make = (from make in context.Makes.Include(#"Models")
where make.ID == 1
select make).FirstOrDefault();
But upon PostBack, this.Make.Models is always empty (depite definitely being populated when the entity was placed into the ViewState.
According to the MS Help,
Because entity types support binary
serialization, objects can be saved in
the view state of an ASP.NET
application during a postback
operation. When required, the object
and its related objects are retrieved
from the view state and attached to an
existing object context.
I would therefore expect what I am doing to work. Can anybody explain why this is not the case?
Thanks.
It seems that the problem was my own fault.
After adding the entity to the ViewState, I was manually detaching it from the object context. This was then clearing the links between the Make and the associated Model objects.
By simply adding the object to the ViewState without calling context.Detach(), the Models remain in the list, and I can still call context.Attach() to facilitate the manipulation of the object during the postback.

Resources