Problem returning data from Search Query in ASP.Net - asp.net-core

I'm learning ASP.NET Core MVC development. I'm trying to create a search query that returns the book if author name or the book title matches from a dummy database.
This is my BookRepository (data source):
public class BookRepository
{
public List<BookModel> SearchBook(string title, string authorName)
{
return DataSource().Where(x => x.Title.Contains(title) || x.Author.Contains(authorName)).ToList();
}
private List<BookModel> DataSource()
{
return new List<BookModel>
{
new BookModel(){Id=1, Author="Einstein", Title="The Grand Design"},
new BookModel(){Id=2, Author="Author", Title="ASP.Net"},
new BookModel(){Id=3, Author="Author1", Title="Visual Studio"}
};
}
}
My BookController class is:
using Book_Store.Repository;
namespace Book_Store.Controllers
{
public class BookController : Controller
{
private readonly BookRepository bookRepository = null;
public BookController()
{
bookRepository = new BookRepository();
}
public List<BookModel> SearchBook(string bookName, string authorName)
{
return bookRepository.SearchBook(bookName, authorName);
}
}
}
The problem is this query is returning a null array every time. I'm executing the command like this:
Can someone please identify the problem in this rather simple program?
Thanks!

Related

The repeated fields in a protobuf message is empty in a POST api in ASP.NET Core

As the title said, when I try to post a message (which is generated by protobuf message) from a react application to ASP.NET Core, the backend cannot receive the repeated fields (empty).
The following is the payload of a post action from the browser:
{ "strs": [ "test1", "test2" ] }
enter image description here
But in the POST API of ASP.NET Core, the body is just empty:
enter image description here
The protobuf message is very simple:
message TestArray {
repeated string strs = 1;
}
Any advice will be appreciated. Thank you in advance.
Part of the generated TestArray class in C#:
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
// ...
public sealed partial class TestArray : pb::IMessage<TestArray>
// ...
private readonly pbc::RepeatedField<string> strs_ = new pbc::RepeatedField<string>();
// ...
public pbc::RepeatedField<string> Strs {
get { return strs_; }
}
I followed this document and created the model as below:
public class TestArray
{
public RepeatedField<string> Strs { get; set; }
}
Tested with postman:
It seems binded successfully,so I asked you for the details of TestArray class to check what's wrong
I think you could create a DTO and add the necessary data to the instance of TestArray class
public sealed partial class TestArray
{
private readonly RepeatedField<string> strs_ = new RepeatedField<string>();
public RepeatedField<string> Strs
{
get { return strs_; }
}
}
public class SomeDto
{
public string[] Strs { get; set; }
}
In controller:
[HttpPost]
public IActionResult Post(SomeDto dto)
{
var testarr = new TestArray();
testarr.Strs.Add(dto.Strs);
return Ok();
}
Result:

How can I validate different types within a collection using FluentValidation?

I have a class with a collection that needs validation. The generic on the collection takes an interface and different types can be added to the collection.
What is the cleanest path forward to creating a FluentValidation validator that supports polymorphism?
public interface IWizardStep {}
public class WizardOne : IWizardStep
{
public string Model { get; set; }
}
public class WizardTwo : IWizardStep
{
public string FirstName { get; set; }
}
public class Wizard
{
public Wizard()
{
var w1 = new WizardOne();
var w2 = new WizardTwo();
Steps = new List<IWizardStep>
{
w1,
w2
};
}
public IList<IWizardStep> Steps { get; set; }
}
public class WizardValidator : AbstractValidator<Wizard>
{
public WizardValidator()
{
RuleFor(x => x.Steps)
// Steps First where is WizardOne
// Model.NotEmpty()
// Steps First where is WizardTwo
// FirstName.NotEmpty()
}
FluentValidation doesn't support polymorphism for child collections like this out of the box, but you can add this behaviour by using a custom property validator, or by using OfType in your rule definitions.
I've written about both approaches before here:
Step 1: Create a validator for each implementor
Start by creating a validator for WizardOne and WizardTwo:
public class WizardOneValidator : AbstractValidator<WizardOne> {
public WizardOneValidator() {
RuleFor(x => x.Model).NotEmpty();
}
}
public class WizardTwoValidator : AbstractValidator<WizardTwo> {
public WizardTwoValidator() {
RuleFor(x => x.FirstName).NotEmpty();
}
}
Step 2: Create the parent validator
You have two options for defining the parent validator. The simplest approach is to use OfType, but this is less performant. The more complex option is to use a custom property validator.
Option 1: Using OfType
public WizardValidator : AbstractValidator<Wizard> {
public WizardValidator() {
RuleForEach(x => x.Steps.OfType<WizardOne>()).SetValidator(new WizardOneValidator());
RuleForEach(x => x.Steps.OfType<WizardTwo>()).SetValidator(new WizardTwoValidator());
}
}
This is the simplest approach, but calling OfType inside the call RuleFor will end up bypassing FluentValidation's expression cache, which is a potential performance hit. It also iterates the collection multiple. This may or may not be an issue for you - you'll need to decide if this has any real-world impact on your application.
Option 2: Using a custom PropertyValidator.
This uses a custom custom validator which can differentiate the underlying type at runtime:
public WizardValidator : AbstractValidator<Wizard> {
public WizardValidator() {
RuleForEach(x => x.Steps).SetValidator(new PolymorphicValidator<Wizard, IWizardStep>()
.Add<WizardOne>(new WizardOneValidator())
.Add<WizardTwo>(new WizardTwoValidator())
);
}
}
Syntactically, this isn't quite as nice, but doesn't bypass the expression cache and doesn't iterate the collection multiple times. This is the code for the PolymorphicValidator:
public class PolymorphicValidator<T, TInterface> : ChildValidatorAdaptor<T, TInterface> {
readonly Dictionary<Type, IValidator> _derivedValidators = new Dictionary<Type, IValidator>();
// Need the base constructor call, even though we're just passing null.
public PolymorphicValidator() : base((IValidator<TInterface>)null, typeof(IValidator<TInterface>)) {
}
public PolymorphicValidator<T, TInterface> Add<TDerived>(IValidator<TDerived> derivedValidator) where TDerived : TInterface {
_derivedValidators[typeof(TDerived)] = derivedValidator;
return this;
}
public override IValidator<TInterface> GetValidator(PropertyValidatorContext context) {
// bail out if the current item is null
if (context.PropertyValue == null) return null;
if (_derivedValidators.TryGetValue(context.PropertyValue.GetType(), out var derivedValidator)) {
return new ValidatorWrapper(derivedValidator);
}
return null;
}
private class ValidatorWrapper : AbstractValidator<TInterface> {
private IValidator _innerValidator;
public ValidatorWrapper(IValidator innerValidator) {
_innerValidator = innerValidator;
}
public override ValidationResult Validate(ValidationContext<TInterface> context) {
return _innerValidator.Validate(context);
}
public override Task<ValidationResult> ValidateAsync(ValidationContext<TInterface> context, CancellationToken cancellation = new CancellationToken()) {
return _innerValidator.ValidateAsync(context, cancellation);
}
public override IValidatorDescriptor CreateDescriptor() {
return _innerValidator.CreateDescriptor();
}
}
}
This will probably be implemented in the library as a first class feature at some point in the future - you can track its development here if you're interested.

GWTP: Troubles to display a CellTable

Hi I'm new to GWT and so, to GWTP too.
I try to play with CellTables and I decided to begin by building a simple one following GWT documentation at developers.google.com/web-toolkit/doc/2.4/DevGuideUiCellWidgets#celltable
I adapted few things to match GWTP MVP design.
First, I created my Celltable on my View.ui.xml file:
xmlns:c="urn:import:com.google.gwt.user.cellview.client">
<g:HTMLPanel>
<c:CellTable pageSize='15' ui:field='cellTable' />
</g:HTMLPanel>
Then, I created a class Contact:
public class Contact {
private final String address;
private final String name;
public Contact(String name, String address) {
this.name = name;
this.address = address;
}
public String getAddress() {
return address;
}
public String getName() {
return name;
}
}
in my View.java file:
#UiField(provided=true) CellTable<Contact> cellTable = new CellTable<Contact>();
public CellTable<Contact> getCellTable() {
return cellTable;
}
Finally in my Presenter.java file:
public interface MyView extends View {
CellTable<Contact> getCellTable();
}
#Override
protected void onReset() {
super.onReset();
// Create name column.
TextColumn<Contact> nameColumn = new TextColumn<Contact>() {
#Override
public String getValue(Contact contact) {
return contact.getName();
}
};
// Create address column.
TextColumn<Contact> addressColumn = new TextColumn<Contact>() {
#Override
public String getValue(Contact contact) {
return contact.getAddress();
}
};
// Add the columns.
getView().getCellTable().addColumn(nameColumn, "Name");
getView().getCellTable().addColumn(addressColumn, "Address");
// Set the total row count.
getView().getCellTable().setRowCount(CONTACTS.size(), true);
// Push the data into the widget.
getView().getCellTable().setRowData(0, CONTACTS);
}
Everything seems good to me but there is no CellTable displayed when I try this code...And I get no errors...
Thanks in advance for your Help!
It looks like you do not use/have DataProvider registered for your CellTable. GWT CellWidgets are based on DataProvider/DIsplay pattern. So CellTable is just a Display for your DataProvider. One DataProvider could have multiple displays.
You do not need to write:
// Set the total row count.
getView().getCellTable().setRowCount(CONTACTS.size(), true);
// Push the data into the widget.
getView().getCellTable().setRowData(0, CONTACTS);
You need to register your CellTable as a Display for your DataProvider (eg ListDataProvider) and than call refresh method when you update DataProvider with new data.

Returning Dataset to controller in asp.net MVC

In Data access layer I have method to retrieve all the table values. How can I return it into the controller in asp.net MVC. can anyone help me?
Thanks in advance.
public static Dataset GetMembers()
{
//sql steps to retrieve records and fill it in dataset
}
Controller code:
{
var members = class.GetMembers()
return View(members);
}
You'll need to modify your GetMembers method (or implement another one that returns IEnumerable<YourType>. In this example (since you don't provide any additional data), I'll return a list of MyType, which I'll assume looks like:
public class MyType
{
public int ID { get; set; }
public string Name { get; set; }
}
And then populate a List<MyType> inside GetMembers
public static IEnumerable<MyType> GetMembers()
{
List<MyType> list = new List<MyType>();
using(SqlConnection db = new SqlConnection(connectionString))
{
DataSet ds = new DataSet();
// get a DataSet as normal
foreach (DataRow dr in ds.Tables[0].Rows)
{
list.Add(new MyType()
{
ID = Convert.ToInt32(dr["ID"].ToString()),
Name = dr["Name"].ToString())
});
}
}
return list;
}
This is a basic example of how you could return IEnumerable (of which List<T> implements) from your method.

Context variables in Ninject 2

I found this article on Context Variables in an earlier version of Ninject. My question is two-fold. First, how can I get this behavior with Ninject 2? Secondly, do context variables carry through down the request chain? For example, let's say I wanted to replace these calls:
var a = new A(new B(new C())));
var specialA = new A(new B(new SpecialC()));
... with this:
var a = kernel.Get<A>();
var specialA = kernel.Get<A>(With.Parameters.ContextVariable("special", "true"));
Is it possible to set up a binding like this, where the context remembers that it is in a "special" context when it comes time to construct a C?
Here's some stuff that I use against V2, with ~0 effort to clean it up for you - let me know if you can't disentagle it.
As you surmised, there doesn't seem to be a really explicit API that surfaces the "context parameter, even for nested resolutions" stuff in v2 as-is (it's presence is buried as the 3rd parameter on an overload of the Parameter ctor).
public static class ContextParameter
{
public static Parameter Create<T>( T value )
{
return new Parameter( value.GetType().FullName, value, true );
}
}
public static class ContextParameterFacts
{
public class ProductId
{
public ProductId( string productId2 )
{
Value = productId2;
}
public string Value { get; set; }
}
public class Repository
{
public Repository( ProductId productId )
{
ProductId = productId;
}
public ProductId ProductId { get; set; }
}
public class Outer
{
public Outer( Repository repository )
{
Repository = repository;
}
public Repository Repository { get; set; }
}
public class Module : NinjectModule
{
public override void Load()
{
Bind<ProductId>().ToContextParameter();
}
}
//[ Fact ]
public static void TwoDeepShouldResolve()
{
var k = new StandardKernel( new Module() );
var o = k.Get<Outer>( ContextParameter.Create( new ProductId( "a" ) ) );
Debug.Assert( "a" == o.Repository.ProductId.Value );
}
}
And here's some code [that'll confuse the matter] which demonstrates how I apply it in my context:-
public class ServicesNinjectModule : NinjectModule
{
public override void Load()
{
Bind<ProductId>().ToContextParameter();
Bind<Func<ProductId, ResourceAllocator>>().ToConstant( ( productId ) => Kernel.Get<ResourceAllocator>(
ContextParameter.Create( productId ) ) );
}
}
public static class NinjectContextParameterExtensions
{
public static IBindingWhenInNamedWithOrOnSyntax<T> ToContextParameter<T>( this IBindingToSyntax<T> bindingToSyntax )
{
return bindingToSyntax.ToMethod( context => (T)context.Parameters.Single( parameter => parameter.Name == typeof( T ).FullName ).GetValue( context ) );
}
}
As usual, you should go look a the source and the tests - they'll provide you with a far more detailed and relevant answer than I can.