Asp.net MVC maxlength not working using data annotation - asp.net-mvc-3

I am using asp.net mvc 4 i am using [maxlength(2)] in my model but it is not working on client side validation i am new to asp.net mvc .here is my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace RestrauntsMVC.Models
{
public class Restraunts
{
public int id { get; set; }
[Required]
public string name { get; set; }
[Required]
[MaxLength(2),MinLength(1)]
public int rating { get; set; }
[Required]
public string location { get; set; }
}
}

Answering myself to help future readers.I found out Maxlength and Minlength is for String not for integer.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace RestrauntsMVC.Models
{
public class Restraunts
{
public int id { get; set; }
[Required]
public string name { get; set; }
[Required]
[Range(1,10,ErrorMessage="Rating must between 1 to 10")]
public int rating { get; set; }
[Required]
public string location { get; set; }
}
}

Like other mention is only for string so how about writing your own ValidationAttribute ?
using System.ComponentModel.DataAnnotations;
internal class MaxDigitsAttribute : ValidationAttribute
{
private int Max,
Min;
public MaxDigitsAttribute(int max, int min = 0)
{
Max = max;
Min = min;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (!IsValid(value))
{
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
public override bool IsValid(object value)
{
// you could do any custom validation you like
if (value is int)
{
var stringValue = "" + (int)value;
var length = stringValue.Length;
if (length >= Min && length <= Max)
return true;
}
return false;
}
}

Related

Cant use system.web.security and HttpContext.Current.User.Identity.Name in dot net core 6

I'm trying to migrate from ASP.NET MVC on .NET 4.5 to ASP.NET Core 6,
I can't use System.Web.Security any more.
I also can't use HttpContext.Current.User.Identity.Name. Please suggest an alternative to implement the same functionality:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using Ibq.Wages.ManagementSystem.Models;
using Microsoft.AspNetCore.Http;
namespace Ibq.Wages.ManagementSystem.AppStart
{
public class CustomRoleProvider : RoleProvider
{
public int UserCompanyId { get; set; }
public string PayerQid { get; set; }
public string PayerEid { get; set; }
public bool OTPCompleted { get; set; }
public int? AuthorizationLevels { get; set; }
private PIBQWS_prodContext context = new PIBQWS_prodContext();
public override string ApplicationName { get; set; }
public CustomRoleProvider()
{
if(String.IsNullOrEmpty(HttpContext.Current.User.Identity.Name) == false)
UserCompany(HttpContext.Current.User.Identity.Name);
}
}
}

IQueryable<Patron> does not contain a definition for FirstName and no extension method First Name

I'm starting to learn ASP.NET Core and I stuck in one error and don't understand what is problem.
It says:
IQueryable<Patron> does not contain a definition for FirstName and no extension method FirstName accepting a first argument of type IQueryable<Patron> could be found (are you missing a using directive or an assembly reference?"
So my code so far:
Patron.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace LibaryData.Models
{
public class Patron
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public DateTime DateOfBirth { get; set; }
public string TelephoneNumber { get; set; }
public virtual LibaryCard LibaryCard { get; set; }
public virtual LibaryBranch HomeLibaryBranch { get; set; }
}
}
CheckoutServices.cs
using LibaryData;
using LibaryData.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LibaryData.Models;
namespace LibaryServices
{
public class ChekoutService : ICheckout
{
private LibaryContext _context;
public ChekoutService(LibaryContext context)
{
_context = context;
}
public string GetCurrentCheckoutPatron(int assetId)
{
var checkout = GetCheckoutByAssetId(assetId);
if(checkout == null)
{
return "";
}
var cardId = checkout.LibaryCard.Id;
var patron = _context.Patrons
.Include(p => p.LibaryCard)
.Where(p => p.LibaryCard.Id == cardId);
return patron.FirstName + " " + patron.LastName;
}
private Checkout GetCheckoutByAssetId(int assetId)
{
return _context.Checkouts
.Include(co => co.LibaryAsset)
.Include(co => co.LibaryCard)
.Where(co => co.LibaryAsset.Id == assetId)
.FirstOrDefault(co => co.LibaryAsset.Id ==assetId);
}
}
}
So in my class CheckoutServices in method GetCurrentCheckoutPatron I can not call a object patron.FirstName and patron.LastName
As you can see all classes are public, references is already there.
Any suggestion?
Replace .Where with .First to get a Patron and not a IQueryable<Patron>
Edit
Note that if you use .First, an exception can be raised if there's no match.
However, if you use .FirstOrDefault and there's no match, it will return null, so you'll get a NullReferenceException when trying to access patron.FirstName.
Be carefull to check for nulls
In your method GetCurrentCheckoutPatron the variable patron is an IQueryable. If you are expecting only single result from the query, you might want to call FirstOrDefault.

Post {FromBody] from data model to execute a procedure

I think I am on the right track here, but cannot quite get this over the line. Very new to WebAPI and c# my background in SQL I could really use a hint. So thank you very much for any feedback.
using VirtualAssistant.Models;
using VirtualAssistant.DataModel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Web.Http.Description;
using System.Collections;
using System.Data.Entity.Core.Objects;
namespace VirtualAssistant.Controllers
{
public class CreateController : ApiController
{
// POST: ChatAi/CreateCase
[Route("CreateCase")]
public IHttpActionResult Post([FromBody]usp_CreateCase_Submit createCase_Submit )
{
usp_CreateCase_Result results = new CreateCaseEntities().usp_CreateCase(createCase_Submit).FirstOrDefault();
if (results.caseId == null)
{
return NotFound();
}
return Ok(results);
}
}
}
I am using these data Models to help support Post[FromBody]
namespace VirtualAssistant.DataModel
{
using System;
public partial class usp_CreateCase_Result
{
public string referenceId { get; set; }
public Nullable<int> caseId { get; set; }
public string slaPriorityName { get; set; }
public string helpDeskName { get; set; }
public string helpDeskPhoneNumber { get; set; }
public string providerCompanyName { get; set; }
public string providerDivisionName { get; set; }
public string serviceDetailName { get; set; }
public string serviceTypeName { get; set; }
public string serviceStreamName { get; set; }
public Nullable<System.DateTime> slaAllocateBy { get; set; }
public Nullable<System.DateTime> slaAttendBy { get; set; }
public Nullable<System.DateTime> slaCompleteBy { get; set; }
public string caseStage { get; set; }
public string statusCode { get; set; }
public string statusMessage { get; set; }
}
public partial class usp_CreateCase_Submit
{
public Nullable<int> personId { get; set; }
public Nullable<int> locationId { get; set; }
public Nullable<int> serviceDetailId { get; set; }
public Nullable<int> linkedCaseId { get; set; }
public string contactFullName { get; set; }
public string contactPhoneNumber { get; set; }
public string contactMobileNumber { get; set; }
public string contactEmailAddres { get; set; }
public string problemNote { get; set; }
public string costCode { get; set; }
public string authoriserEmailAddress { get; set; }
public bool isDraft { get; set; }
public bool isOnlineEmergencyConfirmed { get; set; }
}
}
The error I am left dealing with is:
Severity Code Description Project File Line Suppression State
Error CS7036 There is no argument given that corresponds to the
required formal parameter 'locationId' of
'CreateCaseEntities.usp_CreateCase(int?, int?, int?, int?, string,
string, string, string, string, string, string, bool?,
bool?)' LloydsVirtualAssistant C:\Users\Noel.Purdie2\OneDrive -
Mitie\MITIE Solutions Delivery
Team\ChatAI\LloydsVirtualAssistant\LloydsVirtualAssistant\Controllers\CreateController.cs 28 Active
I understand that using json I can only have a single imput in the from. The team I am working with insist on [FromBody] no use of URI. Every example i can find out there doesn't include using database objects.
I am using a data model to import the functions
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace VirtualAssistant.DataModel
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.Objects;
using System.Linq;
public partial class CreateCaseEntities : DbContext
{
public CreateCaseEntities()
: base("name=CreateCaseEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual ObjectResult<usp_CreateCase_Result> usp_CreateCase(Nullable<int> personId, Nullable<int> locationId, Nullable<int> serviceDetailId, Nullable<int> linkedCaseId, string contactFullName, string contactPhoneNumber, string contactMobileNumber, string contactEmailAddress, string problemNote, string costCode, string authoriserEmailAddress, Nullable<bool> isDraft, Nullable<bool> isOnlineEmergencyConfirmed)
{
var personIdParameter = personId.HasValue ?
new ObjectParameter("PersonId", personId) :
new ObjectParameter("PersonId", typeof(int));
var locationIdParameter = locationId.HasValue ?
new ObjectParameter("LocationId", locationId) :
new ObjectParameter("LocationId", typeof(int));
var serviceDetailIdParameter = serviceDetailId.HasValue ?
new ObjectParameter("ServiceDetailId", serviceDetailId) :
new ObjectParameter("ServiceDetailId", typeof(int));
var linkedCaseIdParameter = linkedCaseId.HasValue ?
new ObjectParameter("LinkedCaseId", linkedCaseId) :
new ObjectParameter("LinkedCaseId", typeof(int));
var contactFullNameParameter = contactFullName != null ?
new ObjectParameter("ContactFullName", contactFullName) :
new ObjectParameter("ContactFullName", typeof(string));
var contactPhoneNumberParameter = contactPhoneNumber != null ?
new ObjectParameter("ContactPhoneNumber", contactPhoneNumber) :
new ObjectParameter("ContactPhoneNumber", typeof(string));
var contactMobileNumberParameter = contactMobileNumber != null ?
new ObjectParameter("ContactMobileNumber", contactMobileNumber) :
new ObjectParameter("ContactMobileNumber", typeof(string));
var contactEmailAddressParameter = contactEmailAddress != null ?
new ObjectParameter("ContactEmailAddress", contactEmailAddress) :
new ObjectParameter("ContactEmailAddress", typeof(string));
var problemNoteParameter = problemNote != null ?
new ObjectParameter("ProblemNote", problemNote) :
new ObjectParameter("ProblemNote", typeof(string));
var costCodeParameter = costCode != null ?
new ObjectParameter("CostCode", costCode) :
new ObjectParameter("CostCode", typeof(string));
var authoriserEmailAddressParameter = authoriserEmailAddress != null ?
new ObjectParameter("AuthoriserEmailAddress", authoriserEmailAddress) :
new ObjectParameter("AuthoriserEmailAddress", typeof(string));
var isDraftParameter = isDraft.HasValue ?
new ObjectParameter("IsDraft", isDraft) :
new ObjectParameter("IsDraft", typeof(bool));
var isOnlineEmergencyConfirmedParameter = isOnlineEmergencyConfirmed.HasValue ?
new ObjectParameter("IsOnlineEmergencyConfirmed", isOnlineEmergencyConfirmed) :
new ObjectParameter("IsOnlineEmergencyConfirmed", typeof(bool));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<usp_CreateCase_Result>("usp_CreateCase", personIdParameter, locationIdParameter, serviceDetailIdParameter, linkedCaseIdParameter, contactFullNameParameter, contactPhoneNumberParameter, contactMobileNumberParameter, contactEmailAddressParameter, problemNoteParameter, costCodeParameter, authoriserEmailAddressParameter, isDraftParameter, isOnlineEmergencyConfirmedParameter);
}
}
}
You are passing data to usp_CreateCase method in a wrong way, You need to update usp_CreateCase parameters to take one object of type usp_CreateCase_Submit
usp_CreateCase(usp_CreateCase_Submit createCase_Submit)
{
var personIdParameter = createCase_Submit.personId.HasValue ?
new ObjectParameter("PersonId", createCase_Submit.personId) :
new ObjectParameter("PersonId", typeof(int));
}

Why can't I use the Column data annotation with Entity Framework 5?

I want to use the Column data annotation as shown in the sample code below but the compiler (and also IntelliSense) do not seem to know that particular data annotation. I'm using EF 5 in Visual Studio 2010. I installed EF 5 using NuGet. The Required and MaxLength annotations are working.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Model
{
public class Destination
{
public int DestinationId { get; set; }
[Required]
public string Name { get; set; }
public string Country { get; set; }
[MaxLength(500)]
public string Description { get; set; }
[Column(TypeName="image")]
public byte[] Photo { get; set; }
public List<Lodging> Lodgings { get; set; }
}
}
What am I missing?
Column is in:
using System.ComponentModel.DataAnnotations.Schema;
the following code:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace ConsoleApplication2
{
public class MyContext : DbContext
{
public IDbSet<Entity> Entities { get; set; }
}
public class Entity
{
public int Id { get; set; }
[Column(TypeName = "image")]
public byte[] Photo { get; set; }
}
}
produces:

How to make the entity key value user-assigned

I'm retrieving data from another database that has already created unique IDs for each "beer" entity. However, when I assign the unique key value from the remote database to a new "beer" object, it gets replaced as soon as the object is inserted into the database.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using BeerRecommender.Models.ViewModels;
namespace BeerRecommender.Models
{
public class Beer
{
public Beer()
{
Created = DateTime.Now;
Updated = DateTime.Now;
}
[Key]
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Brewery Brewery { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public ICollection<City> Cities { get; set; }
public ICollection<Tag> Tags { get; set; }
public Style Style { get; set; }
}
}
I'm using the UnitOfWork pattern.
UnitOfWork.BeerRepository.Insert(beer);
UnitOfWork.Save();
As you already discovered, EF will generate values for int primary keys. To fine tune this behavior you need to mark your key with the DatabaseGenerated attribute (or you can also configure this with the the fluent api's HasDatabaseGeneratedOption method):
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; }

Resources