Bind ICommand to enter pressed - mvvm-light

So i have a windows 8 application with a basic view:
Example:
<TextBox Text="{Binding UserName}"/>
<PasswordBox Text="{Binding Password}"/>
<Button Content="Sign In" Command="{Binding Login}"/>
And a View Model with the ICommand implemented.
public class LoginViewModel : ViewModelBase
{
public ICommand Login { get; set; }
//Other properties
public LoginViewModel()
{
Login = ExecuteLogin;
}
public void ExecuteLogin()
{
//Logic
}
}
It all works fine. But now I want to trigger the ICommand when the user presses enter in the password box, just for a better User Experience. Anybody has any idea how to do it?

Yes, what you need is this class:
namespace SL
{
public sealed class EnterKeyDown
{
#region Properties
#region Command
/// <summary>
/// GetCommand
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static ICommand GetCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(CommandProperty);
}
/// <summary>
/// SetCommand
/// </summary>
/// <param name="obj"></param>
/// <param name="value"></param>
public static void SetCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(CommandProperty, value);
}
/// <summary>
/// DependencyProperty CommandProperty
/// </summary>
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(EnterKeyDown), new PropertyMetadata(null, OnCommandChanged));
#endregion Command
#region CommandParameter
/// <summary>
/// GetCommandParameter
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static object GetCommandParameter(DependencyObject obj)
{
return (object)obj.GetValue(CommandParameterProperty);
}
/// <summary>
/// SetCommandParameter
/// </summary>
/// <param name="obj"></param>
/// <param name="value"></param>
public static void SetCommandParameter(DependencyObject obj, object value)
{
obj.SetValue(CommandParameterProperty, value);
}
/// <summary>
/// DependencyProperty CommandParameterProperty
/// </summary>
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.RegisterAttached("CommandParameter", typeof(object), typeof(EnterKeyDown), new PropertyMetadata(null, OnCommandParameterChanged));
#endregion CommandParameter
#region HasCommandParameter
private static bool GetHasCommandParameter(DependencyObject obj)
{
return (bool)obj.GetValue(HasCommandParameterProperty);
}
private static void SetHasCommandParameter(DependencyObject obj, bool value)
{
obj.SetValue(HasCommandParameterProperty, value);
}
private static readonly DependencyProperty HasCommandParameterProperty =
DependencyProperty.RegisterAttached("HasCommandParameter", typeof(bool), typeof(EnterKeyDown), new PropertyMetadata(false));
#endregion HasCommandParameter
#endregion Propreties
#region Event Handling
private static void OnCommandParameterChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
SetHasCommandParameter(o, true);
}
private static void OnCommandChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = o as FrameworkElement;
if (element != null)
{
if (e.NewValue == null)
{
element.KeyUp -= FrameworkElementKeyUp;
}
else if (e.OldValue == null)
{
element.KeyUp += FrameworkElementKeyUp;
}
}
}
private static void FrameworkElementKeyUp(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Enter)
{
var o = sender as DependencyObject;
var command = GetCommand(sender as DependencyObject);
var element = e.OriginalSource as FrameworkElement;
if (element != null)
{
// If the command argument has been explicitly set (even to NULL)
if (GetHasCommandParameter(o))
{
var commandParameter = GetCommandParameter(o);
// Execute the command
if (command.CanExecute(commandParameter))
{
command.Execute(commandParameter);
}
}
else if (command.CanExecute(element.DataContext))
{
command.Execute(element.DataContext);
}
}
}
}
#endregion
}
}
XAML namespace:
xmlns:sl="clr-namespace:SL;"
XAML code:
<TextBox sl:EnterKeyDown.Command="{Binding SearchClickCommand}"
Text="{Binding Input, Mode=TwoWay,
NotifyOnValidationError=True, ValidatesOnDataErrors=True,
ValidatesOnExceptions=True, ValidatesOnNotifyDataErrors=True}" />
<Button Content="Search"
Command="{Binding SearchClickCommand}" />

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.

How to return a BadRequest from a Controller?

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);

Ninject Dependency Injection works for only for one controller

I had originally set up DI with ninject for an asp.net web api 2 service with a single controller and everything was working correctly. Upon adding a second controller, ninject does not work for the new one. I'm getting the following error:
"An error occurred when trying to create a controller of type 'VstsController'. Make sure that the controller has a parameterless public constructor."
First controller (for which ninject works):
public class RepositoryController : ApiController
{
private GitHubClient _client;
public RepositoryController(IGitHubClientAuthenticated gitHubClientAuthenticated)
{
_client = gitHubClientAuthenticated.Client;
_client.Credentials = gitHubClientAuthenticated.Credentials;
}
Second controller:
public class VstsController : ApiController
{
private VssConnection _connection;
public VstsController(IVssConnectionAuthenticated vssConnectionAuthenticated)
{
_connection = vssConnectionAuthenticated.VssConnection;
}
Ninject config file:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IVssConnectionAuthenticated>().To<VssConnectionAuthenticated>();
kernel.Bind<IGitHubClientAuthenticated>().To<GitHubClientAuthenticated>();
kernel.Bind<IAuthenticationHelper>().To<AuthenticationHelper>();
}
Do I need to tweak anything if I want to keep adding controllers? Couldn't find any documentation on this. Thanks in advance
EDIT: Including ninject set up code as well as VssAuthenticated + IvssAuthenticated:
namespace Dashboard.WebAPI.Models
{
public interface IVssConnectionAuthenticated
{
VssConnection VssConnection { get; }
Uri Uri { get; }
}
}
namespace Dashboard.WebAPI.Models
{
public class VssConnectionAuthenticated: IVssConnectionAuthenticated
{
public VssConnection VssConnection { get; private set; }
public Uri Uri { get; private set; }
VssConnectionAuthenticated()
{
Uri = new Uri("uri");
string vstsSecretUri = "vstssecreturi";
GetKeyVaultSecret keyVaultSecretGetter = new GetKeyVaultSecret(new AuthenticationHelper(), vstsSecretUri);
string keyVaultSecret = keyVaultSecretGetter.KeyVaultSecret;
VssBasicCredential vssBasicCredential = new VssBasicCredential(string.Empty, keyVaultSecret);
VssConnection = new VssConnection(Uri, vssBasicCredential);
}
Full Ninject Config File:
namespace Dashboard.WebAPI.App_Start
{
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
using System.Web.Http;
using Dashboard.WebAPI.Models;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage the application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
/// <summary>
/// Load modules and register services
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IVssConnectionAuthenticated>().To<VssConnectionAuthenticated>();
kernel.Bind<IGitHubClientAuthenticated>().To<GitHubClientAuthenticated>();
kernel.Bind<IAuthenticationHelper>().To<AuthenticationHelper>();
}
}
}
Registering Ninject as Dependency Resolver:
namespace Dashboard.WebAPI.App_Start
{
public class NinjectDependencyScope : IDependencyScope
{
IResolutionRoot resolver;
public NinjectDependencyScope(IResolutionRoot resolver)
{
this.resolver = resolver;
}
public object GetService(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has been disposed");
return resolver.TryGet(serviceType);
}
public System.Collections.Generic.IEnumerable<object> GetServices(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has been disposed");
return resolver.GetAll(serviceType);
}
public void Dispose()
{
IDisposable disposable = resolver as IDisposable;
if (disposable != null)
disposable.Dispose();
resolver = null;
}
}
public class NinjectDependencyResolver: NinjectDependencyScope, IDependencyResolver
{
IKernel kernel;
public NinjectDependencyResolver(IKernel kernel) : base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel.BeginBlock());
}
}
}
In case anyone else runs into this problem- The problem was in VssConnectionAuthenticated: The constructor needs to be public.

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