Custom Classes data annotations - data-annotations

I have a custom class as:
public class BasicInfo
{
[Required(ErrorMessage = "First Name is required.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is required.")]
public string LastName { get; set; }
}
public class ContactInfo
{
[Required(ErrorMessage = "Cell # is required.")]
public string CellNo { get; set; }
[Required(ErrorMessage = "Email is required.")]
public int Email { get; set; }
}
public class PErson
{
public BasicInfo bInfo { get; set; }
public ContactInfo cInfo { get; set; }
}
and using this code to validate - taken from: How does one do property validation of a C# class using Data Annotations in .NET Framework 3.5?
public static class Validator
{
// This could return a ValidationResult object etc
public static IEnumerable<string> Validate(object o)
{
Type type = o.GetType();
PropertyInfo[] properties = o.GetType().GetProperties();
foreach (var propertyInfo in properties)
{
object[] customAttributes = propertyInfo.GetCustomAttributes(typeof(ValidationAttribute), inherit: true);
foreach (var customAttribute in customAttributes)
{
var validationAttribute = (ValidationAttribute)customAttribute;
bool isValid = validationAttribute.IsValid(propertyInfo.GetValue(o, BindingFlags.GetProperty, null, null, null));
if (!isValid)
{
yield return validationAttribute.ErrorMessage;
}
}
}
}
}
This code works when my class is:
public class PErson
{
[Required(ErrorMessage = "First Name is required.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is required.")]
public string LastName { get; set; }
[Required(ErrorMessage = "Cell # is required.")]
public string CellNo { get; set; }
[Required(ErrorMessage = "Email is required.")]
public int Email { get; set; }
}

Related

How to email image from database in ASP.NET MVC using entinty framework

I am working on asp.net mvc project where where i have to send an email that display company logo. I would like to email a logo image stored in database through email body. I am able to to display this image from database in the view, but have no idea how to send it with email. here is how i displays it in the view :
#{
var logo = from e in _db.MyCompanies
where e.userId == rt
select e;
var logos = logo.ToList();
foreach (var y in logos)
{
if (y.Files.Any(f => f.FileType == InsertingMultipleFields.Models.FileType.Avatar))
{
<img class="img-responsive" src="~/File?id= #y.Files.First(f => f.FileType == InsertingMultipleFields.Models.FileType.Avatar).FileId" alt="avatar" />
}
}
}
Here is my model:
public class MyCompany
{
public int ID { get; set; }
public string userId { get; set; }
[RegularExpression(#"^[a-zA-Z ]+$", ErrorMessage = "Use letters only please")]
[StringLength(100, MinimumLength = 2)]
[Display(Name = "My Company")]
public string CompanyName { get; set; }
[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[RegularExpression(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$|^\+?\d{0,2}\-?\d{4,5}\-?\d{5,6}", ErrorMessage = "Please enter a valid email address ")]
public string Email { get; set; }
public string Contact { get; set; }
[Required(ErrorMessage = "Adress is required.")]
[StringLength(50, MinimumLength = 3)]
[Display(Name = "Address Line1")]
public string AddressLine1 { get; set; }
[Required(ErrorMessage = "Adress is required.")]
[StringLength(50, MinimumLength = 3)]
[Display(Name = "Address Line2")]
public string AddressLine2 { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
public virtual ICollection<Purchaseorder> Purchaseorders { get; set; }
public virtual ICollection<Invoice> Invoices { get; set; }
public virtual ICollection<File> Files { get; set; }
public virtual ICollection<FilePath> FilePaths { get; set; }
}
public class File
{
public int FileId { get; set; }
public string userId { get; set; }
[StringLength(255)]
public string FileName { get; set; }
[StringLength(100)]
public string ContentType { get; set; }
public byte[] Content { get; set; }
public FileType FileType { get; set; }
public int MyCompanyId { get; set; }
public virtual MyCompany MyCompany { get; set; }
}
public class FilePath
{
public int FilePathId { get; set; }
public string userId { get; set; }
[StringLength(255)]
public string FileName { get; set; }
public FileType FileType { get; set; }
public int MyCompanyID { get; set; }
public virtual MyCompany MyCompany { get; set; }
}
public enum FileType
{
Avatar = 1, Photo
}
My action method:
public ActionResult King()
{
using (var message = new MailMessage("my#gmail.com", "toemail#gmail.com"))
{
message.Subject = "Message Subject test";
message.Body = "Message test";
using (SmtpClient client = new SmtpClient
{
EnableSsl = true,
Host = "smtp.gmail.com",
Port = 587,
Credentials = new NetworkCredential("myemail#gmail.com", "235!it1978")
})
{
client.Send(message);
}
}
}
I have no idea how to send email with an image from database.
By default the email body is text to view html encode email you have to set IsBodyHtml property to true. Try this message.IsBodyHtml = true;
Sending Image with Email, Image must be located on online server
Copy URL of image that you want to send via Email
Example: http://xyz/content/Email/face.jpg
string Subject = "Send Image";
string sender_email = "xyx#gmail.com";
string passsword = "xyx";
string to = "xyx";
string path = "http://xyz/content/Email/face.jpg";
using (MailMessage mm = new MailMessage(sender_email, to))
{
mm.Subject = Subject;
mm.IsBodyHtml = true;
string img = "path";
string imagepath = Server.MapPath(img);
mm.Body = string.Format("<img src="+imagepath+"/><br/><h1>Find Above Image attachment</h1>");
using (SmtpClient smtp = new SmtpClient())
{
smtp.EnableSsl = true;
smtp.Host = "smtp.gmail.com";
smtp.Port = 25;
smtp.UseDefaultCredentials = false;
NetworkCredential NetworkCred = new NetworkCredential(sender_email, passsword);
smtp.Credentials = NetworkCred;
smtp.Send(mm);
}
}

A specified Include path is not valid on eager loading

I am using eager loading in entity framework. My Model class is like
public class EmployeeMaster : AbsCommonParameters
{
[Key]
public int Id { get; set; }
public string EmpId { get; set; }
[Required(ErrorMessage = "Employee name is required")]
public string Name { get; set; }
[Required(ErrorMessage = "Employee geography is required")]
public string Geography { get; set; }
public string EmailId { get; set; }
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[Column(TypeName = "Date")]
[Display(Name = "Date Of Joining")]
public Nullable<DateTime> DOJ { get; set; }
[Required(ErrorMessage = "Employee designation is required")]
public string Designation { get; set; }
[NotMapped]
public List<CenterMaster> lstCenters { get; set; }
[NotMapped]
public List<CostCodeMaster> lstCostCode { get; set; }
}
In Controller Index Action my Code is like this
public ActionResult Index()
{
var lstUser = db.ObjEmployeeMaster.Include(p => p.lstCenters).
Include(p => p.lstCostCode).Where(x => x.DeletedStatus == false).ToList();
return View(lstUser);
}
Also In DBContext Constructor I have used
this.Configuration.LazyLoadingEnabled = false;
After this I got error
A specified Include path is not valid
Please help where I am wrong.
Thanks in advance.

DropDownListFor selection not being saved

I am new to MVC. I am using a DropDownListFor to display a list of company names and, based on the selection made, filling in other Customer fields. The customer fields are being populated fine, but when I attempt to POST the record, I get a validation error "Company name is required", even though the company name has been selected in the DropDownListFor. Here is the ViewModel:
namespace CMSUsersAndRoles.Models
{
public class QuoteViewModel
{ [Key]
[Display(Name = "Quote Id")]
public int QuoteId { get; set; }
// Columns from Customer table
[Required(ErrorMessage = "Please select a company")]
[Display(Name = "Customer Id")]
public int? CustomerId { get; set; }
[Display(Name = "Sales Rep")]
public string SalesRep { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
public string Company { get; set; }
[Display(Name = "Address 1")]
public string Address1 { get; set; }
[Display(Name = "Address 2")]
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
[StringLength(10)]
[Display(Name = "Zip Code")]
[RegularExpression(#"^\d{5}(-\d{4})?$", ErrorMessage = "Invalid Zip Code")]
public string PostalCode { get; set; }
[Phone]
[Display(Name = "Work Phone")]
public string WorkPhone { get; set; }
[Phone]
[Display(Name = "Cell Phone")]
public string CellPhone { get; set; }
[EmailAddress]
public string Email { get; set; }
[Range(0, 100)]
public decimal? Discount { get; set; }
[Display(Name = "Payment Terms")]
public int? PaymentTerms { get; set; }
// Columns from QuoteDetail table
[Display(Name = "Quote Detail")]
public List<QuoteDetail> QuoteDetail { get; set; }
// Columns from Quote table
public decimal Subtotal { get; set; }
public decimal Tax { get; set; }
public decimal Total { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Quote Date")]
public DateTime? QuoteDate { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Good Until")]
public DateTime? GoodUntil { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Quote Sent")]
public DateTime? QuoteSent { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date Approved")]
public DateTime? DateApproved { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date Ordered")]
public DateTime? DateOrdered { get; set; }
}
}
Here is the code from the View:
#Html.DropDownListFor(model => model.CustomerId, new SelectList(ViewBag.Customers, "CustomerId", "Company"), "---Select one---", new { htmlAttributes = new { #class = "company" } });
#Html.HiddenFor(model => model.Company)
#Html.ValidationMessageFor(model => model.Company, "", new { #class = "text-danger" })
Here is the Get:
public ActionResult Create()
{
QuoteViewModel qvm = new QuoteViewModel();
var customers = db.Customers.ToList();
ViewBag.Customers = customers;
return View(qvm);
}
And here is the code for the POST:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(QuoteViewModel qvm)
{
if (ModelState.IsValid)
{
Quote quote1 = new Quote();
quote1.CustomerId = qvm.CustomerId;
...
customer.CustomerId = (int)qvm.CustomerId;
...
customer.Company = qvm.Company;
db.Entry(customer).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
var objContext = ((IObjectContextAdapter)db).ObjectContext;
// Get failed entry
var entry = ex.Entries.Single();
// Now call refresh on ObjectContext
objContext.Refresh(RefreshMode.ClientWins, entry.Entity);
}
return RedirectToAction("Index");
}
var customers = db.Customers.ToList();
ViewBag.Customers = customers;
return View(qvm);
}
What am I missing? Any help will be much appreciated.
I was not setting the value of the HiddenFor below. Thanks, #StephenMuecke.
#Html.HiddenFor(model => model.Company)

EF5 Migrations throwing error on simplemembership seed

Error:
No mapping exists from object type eTrail.Models.Global.Address to a known managed provider native type.
The code that is throwing the error:
if (!WebSecurity.UserExists("me"))
{
WebSecurity.CreateUserAndAccount(
"me",
"password", new
{
FirstName = "Firstname",
LastName = "Lastname",
Email = "me#me.com",
Address = new Address
{
Street = "123 Stree",
Street2 = "",
City = "CityVille",
State = "UT",
Zip = "99999",
Country = "USA",
PhoneCell = "111.111.1111"
},
CreatedDate = DateTime.Now,
ModifiedDate = DateTime.Now,
ImageName = ""
});
}
My User.cs Model:
public class User : IAuditInfo
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public Address UserAddress { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public ICollection<Role> Roles { get; set; }
public string ImageName { get; set; }
public User()
{
UserAddress = new Address();
Roles = new List<Role>();
}
}
The Address Model:
public class Address
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Street { get; set; }
public string Street2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
public string PhoneHome { get; set; }
public string PhoneCell { get; set; }
public string PhoneOther { get; set; }
public string FaxNumber { get; set; }
}
Any idea why I am getting this error? Both Model classes are in my DbContext class as DbSet and DbSet.
You used the wrong property name when you created the new user account. You used Address instead of UserAddress. Make the following change under the comment I added to the code.
if (!WebSecurity.UserExists("me"))
{
WebSecurity.CreateUserAndAccount(
"me",
"password", new
{
FirstName = "Firstname",
LastName = "Lastname",
Email = "me#me.com",
//Changed Address to UserAddress
UserAddress = new Address
{
Street = "123 Stree",
Street2 = "",
City = "CityVille",
State = "UT",
Zip = "99999",
Country = "USA",
PhoneCell = "111.111.1111"
},
CreatedDate = DateTime.Now,
ModifiedDate = DateTime.Now,
ImageName = ""
});
}

IValidatableObject not triggered

I'm trying to make use of the IValidatableObject as described here http://davidhayden.com/blog/dave/archive/2010/12/31/ASPNETMVC3ValidationIValidatableObject.aspx.
But it just wont fire when I'm trying to validate, the ModelState.IsValid is always true.
Here is my model code:
[MetadataType(typeof(RegistrationMetaData))]
public partial class Registration : DefaultModel
{
[Editable(false)]
[Display(Name = "Property one")]
public int PropertyOne { get; set; }
}
public class RegistrationMetaData :IValidatableObject
{
[Required(ErrorMessage = "Customer no. is required.")]
[Display(Name = "Customer no.")]
public string CustomerNo { get; set; }
[Display(Name = "Comments")]
public string Comments { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (new AccountModel().GetProfile(CustomerNo) == null)
yield return new ValidationResult("Customer no. is not valid.", new[] { "CustomerNo" });
}
}
I extend a LINQ to SQL table called Registration, my first guess was that this is not possible to do on a Meta class, but I'm not sure?
I do not get any errors, and it builds just fine, but the Validate method will not fire. What have I missed?
That's because it is the Registration model that should implement IValidatableObject and not RegistrationMetaData:
[MetadataType(typeof(RegistrationMetaData))]
public partial class Registration : IValidatableObject
{
[Editable(false)]
[Display(Name = "Property one")]
public int PropertyOne { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (new AccountModel().GetProfile(CustomerNo) == null)
yield return new ValidationResult("Customer no. is not valid.", new[] { "CustomerNo" });
}
}
public class RegistrationMetaData
{
[Required(ErrorMessage = "Customer no. is required.")]
[Display(Name = "Customer no.")]
public string CustomerNo { get; set; }
[Display(Name = "Comments")]
public string Comments { get; set; }
}

Resources