Get error message on isUnique attribute MVC - unique-constraint

I have a model property like below,
[Index("CourseCodeIndex", IsUnique = true)]
[MaxLength(15)]
public string Name { get; set; }
and if I use invalid data it works well but returns no error message. Is there any way to show a message on (view, like other required like messages)
#Html.ValidationMessageFor(model => model.Name)

if you want to show the error message, you need to declare it like:
[Required(ErrorMessage = "Compiletime error required")]
Also, try this.
[Unique(ErrorMessage = "This already exist !!")]

Make an instance of your context file
private datbaseContext db = new databaseContext();
add the code below to your controller action method
db.table.Add(model);
var user = db.table.Where(u => u.Name == model.Name).FirstOrDefault();
if (user != null)
{
ModelState.AddModelError("", model.Name + " Already Exists");
}
else
{
db.SaveChanges();
return RedirectToAction("Index", "model");
}
And the #Html.ValidationSummary(true) from your view will attach the error message

Related

StateHasChanged() does not reload page

Issue:
As mentioned in Title, StateHasChanged does not re-render the page
Objective:
I want to Refresh the page when a button is clicked
Current Code
<button #onclick="CreatePlayer">Create User</button>
#functions {
string username;
[CascadingParameter]
Task<AuthenticationState> authenticationStateTask { get; set; }
async Task CreatePlayer()
{
var authState = await authenticationStateTask;
var user = authState.User;
var player = await PlayerData.GetByEmail(user.Identity.Name);
if (player == null)
{
player = new Player()
{
Email = user.Identity.Name,
UserName = username
};
await PlayerData.Create(player);
}
await Task.Delay(50);
StateHasChanged();
}
}
Just for the record, I add my comment in an answer :
StateHasChanged just inform the component that something changes in is state, that doesn't rerender it. The component choose by itself if it has to rerender or not. You can override ShouldRender to force the component to rerender on state changed.
#code {
bool _forceRerender;
async Task CreatePlayer()
{
var authState = await authenticationStateTask;
var user = authState.User;
var player = await PlayerData.GetByEmail(user.Identity.Name);
if (player == null)
{
player = new Player()
{
Email = user.Identity.Name,
UserName = username
};
await PlayerData.Create(player);
}
_forceRerender = true;
StateHasChanged();
}
protected override bool ShouldRender()
{
if (_forceRerender)
{
_forceRerender = false;
return true;
}
return base.ShouldRender();
}
}
On the one hand, you tell the compiler that she should create an event handler for the click event, named CreatePlayer: #onclick="CreatePlayer . This attribute compiler directive, behind the scenes, creates an EventCallback<Task> handler for you, the implication of which is that you do not need to use StateHasChanged in your code at all, as this method ( StateHasChanged ) is automatically called after UI events take place.
On the other hand, you tell the compiler that the type of the button should be set to "submit". This is wrong of course... You can't have it both. Setting the type attribute to "submit", normally submit form data to the server, but In Blazor it is prevented to work that way by code in the JavaScript portion of Blazor. Do you want to submit a form data to the server ? Always recall Blazor is an SPA Application. No submit ?
Your code should be:
<button #onclick="CreatePlayer" >Create User</button>
Just for the records, ordinarily you should inject the AuthenticationStateProvider object into your components, like this:
#inject AuthenticationStateProvider AuthenticationStateProvider
and then retrieve the AuthenticationState object. This is how your code may be rewritten:
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;

Vaadin RegexpValidator multiple error message

Is it possible to return conditional error message for a vaadin validator?
TextField textField = new TextField();
String regex = "?:(foo|bar)";
textField.addValidator(new RegexpValidator(regex, true, getErrorMessage()));
I want to have a different error message depending on what the user write in the textField.
I found the solution. One should just override the getErrorMessage of the validator
textField.addValidator(new RegexpValidator(regex, true, "") {
#Override
public String getErrorMessage() {
return setMessage();
}
});

How can i write unit test for this actionfilter

public MyContext _db;
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (_db == null || !_db.ChangeTracker.HasChanges())
{
return;
}
try
{
_db.SaveChanges();
}
catch
{
}
}
This is my action filter for my wep api project. _db context object injected to this filter by per request. My point is here to call SaveChanges() method once after all processing done in service layers. My problem is how can test this filter? How can i mimic exception case that can happen in any controler or service layer and when exception throws saveChanges() never called? How can i setup the case that exception occurred in any place inside application?
I have been doing the same, last week, for my WebAPI 2 action filter.
I have an action filter that validates my ModelState and in case of any error it throws an error list with 200 HTTPcode.
The action looks like this:
public class ModelValidationActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var modelState = actionContext.ModelState;
if (!modelState.IsValid)
{
actionContext.Response = ...
}
}
}
UNIT TEST
var httpControllerContext = new HttpControllerContext
{
Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/someUri")
{
Content = new ObjectContent(typeof(MyModel),
new MyModel(), new JsonMediaTypeFormatter())
},
RequestContext = new HttpRequestContext()
};
httpControllerContext.Request = new HttpRequestMessage();
httpControllerContext.Request.SetConfiguration(new HttpConfiguration());
var httpActionContext = new HttpActionContext { ControllerContext = httpControllerContext };
var filter = new ModelValidationActionFilterAttribute();
httpActionContext.ModelState.AddModelError("*", "Invalid model state");
// act
filter.OnActionExecuting(httpActionContext);
// assert
httpActionContext.Response.ShouldNotBe(null);
httpActionContext.Response.ShouldBeOfType(typeof (HttpResponseMessage));
var result = httpActionContext.Response.Content.ReadAsStringAsync().Result;
BaseServiceResponse<object> resultResponse =
JsonConvert.DeserializeObject<BaseServiceResponse<object>>(result);
resultResponse.Data.ShouldBe(null);
resultResponse.Messages.Count.ShouldBe(1);
resultResponse.Messages.First().Description.ShouldBe("Invalid model state");
In your case you need to Mock DB context using IDbContext interface - see here: http://aikmeng.com/post/62817541825/how-to-mock-dbcontext-and-dbset-with-moq-for-unit
If an unhandled exception occurs while executing the request then the Exception property on actionExecutedContext will contain the exception. This is part of the framework, and not something you need to test. In your tests you can simple set the Exception property manually and assert that the attribute takes the correct action.
[Fact]
public void Saves_data_on_failure()
{
var mockDbContext = new Mock<IDbContext>();
var myAttribute = new MyAttribute(mockDbContext.Object);
var executionContext = new HttpActionExecutedContext
{
Exception = new Exception("Request failed.")
};
myAttribute.OnActionExecuted(executionContext);
mockDbContext.Verify(d => d.SaveChanges());
}
You might also want to consider whether or not you want to save data for all types of exception. The data might be in an invalid/unknown state.

Nhibernate and SQLite Exception "Cannot write to a Closed TextWriter"

I'm trying to use NHibernate with SQLite for Unit Testing. But I'm keep getting error
ADOException was unhandled by user code
While preparing INSERT INTO User (First_Name, Last_Name, UserName, Password, Email, Active, Default_Clinic_Identification_Number, Login_Icon, Created_Date, Created_By, Modified_Date, Modified_By) VALUES (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8, #p9, #p10, #p11); select last_insert_rowid() an error occurred
Inner Exception: {"Cannot write to a closed TextWriter."}
I don't know what i'm doing wrong. Here is my code
public class InMemoryDatabaseTest : IDisposable
{
private static Configuration Configuration;
private static ISessionFactory SessionFactory;
protected ISession session;
public InMemoryDatabaseTest()
{
if (Configuration == null)
{
Assembly a = Assembly.Load("Astute.Framework.Data");
Configuration = new Configuration()
.SetProperty(Environment.ReleaseConnections, "on_close")
.SetProperty(Environment.Dialect, typeof(SQLiteDialect).AssemblyQualifiedName)
.SetProperty(Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName)
.SetProperty(Environment.ConnectionString, "data source=:memory:")
.SetProperty(Environment.ProxyFactoryFactoryClass, typeof(ProxyFactoryFactory).AssemblyQualifiedName)
.AddAssembly(a);
SessionFactory = Configuration.BuildSessionFactory();
}
session = SessionFactory.OpenSession();
new SchemaExport(Configuration).Execute(true, true, false, session.Connection, Console.Out);
}
public void Dispose()
{
session.Dispose();
}
}
[TestClass]
public class Test : InMemoryDatabaseTest
{
[TestMethod]
public void CanSaveUser()
{
object id;
using (var tx = session.BeginTransaction())
{
id = session.Save(new User
{
FirstName = "Imran",
LastName = "Ashraf",
UserName = "imran",
Password = "Test",
Email = "Test#test.com",
IsActive = true,
DefaultClinicIdentifcationNumber = "",
LoginIcon = "",
CreatedBy = 1000000,
CreatedDate = DateTime.Today,
ModifiedBy = 1000000,
ModifiedDate = DateTime.Today
});
tx.Commit();
}
session.Clear();
}
}
I'm getting error on this line id = session.Save. I got this example from http://ayende.com/Blog/archive/2009/04/28/nhibernate-unit-testing.aspx
Any idea?
Thanks in advance.
The error message "Inner Exception: {"Cannot write to a closed TextWriter."}" is given when you are trying to write into the Console.Out.
I created a new TextWriter and used it:
TextWriter writer = null;
new SchemaExport(Configuration).Execute(true, true, false, session.Connection, writer);
That fixed that exception.
I can't see the problem. I use this as connection string:
Data Source=:memory:;Version=3;New=True;
You may try it to see if it solves the problem. The New=True; part looks promising.
In my case I noticed that I used two instances of InMemoryDatabaseTest. I deleted one instance from the test.

Quick Rhinomocks Help

Can someone take a look at this code and tell me if there's any obvious reason it shouldn't be working? When service.getResponse is called within my code the mocking framework only returns null, not the object I specified.
[Test]
public void Get_All_Milestones()
{
var mockRepo = new MockRepository();
var service = mockRepo.DynamicMock<IRestfulService>();
var request = new RestRequestObject
{
Password = "testpw!",
UserName = "user",
SecureMode = true,
Url = "www.updatelog.com/",
Command = String.Format("projects/{0}/milestones/list", 123456),
Method = "POST"
};
var response = new RestResponseObject
{
StatusCode = 200,
ErrorsExist = false,
Response =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<milestones type=\"array\">\n <milestone>\n <completed type=\"boolean\">false</completed>\n <created-on type=\"datetime\">2008-10-02T17:37:51Z</created-on>\n <creator-id type=\"integer\">3028235</creator-id>\n <deadline type=\"date\">2008-10-20</deadline>\n <id type=\"integer\">7553836</id>\n <project-id type=\"integer\">123456</project-id>\n <responsible-party-id type=\"integer\">3028295</responsible-party-id>\n <responsible-party-type>Person</responsible-party-type>\n <title>Atb2 Editor Substantially Done</title>\n <wants-notification type=\"boolean\">true</wants-notification>\n </milestone>\n</milestones>\n"
};
using(mockRepo.Record())
{
Expect
.Call(service.GetResponse(request))
.Return(response);
}
using(mockRepo.Playback())
{
var dal = new DataAccess(service);
var result = dal.GetMilestones(123456);
Assert.IsNotNull(result, "The result should not be null.");
Assert.AreNotEqual(0, result.Count, "There should be exactly one item in this list.");
Assert.AreEqual(123456, result[0].ProjectId, "The project ids don't match.");
Assert.AreEqual(7553836, result[0].Id, "The ids don't match.");
}
mockRepo.VerifyAll();
}
A dynamic mock will return null if the input data does not match the expected, so my guess would be that your code is calling service.GetResponse() with different values for the RestRequestObject or that equality for the RestRequestObject does not work as you expect it to.
I think I would try replacing the dynamic mock with a strict mock and look at the error Rhino Mocks returns.