using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.Text;
namespace PartyInvites.Models
{
public class GuestResponse : IDataErrorInfo
{
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public bool? WillAttend { get; set; }
public string Error { get { return null; } }
public string this[string propName]
{
get
{
if ((propName == "Name") && string.IsNullOrEmpty(Name))
return "Please enter your name";
if ((propName == "Email") && string.IsNullOrEmpty(Email)) // Need to cover them leaving field blank
return "Please enter a valid email address";
if ((propName == "Email") && !Regex.IsMatch(Email, ".+\\@.+\\..+")) // Need to cover input != name@example.com
return "Please enter a valid email address";
if ((propName == "Phone") && string.IsNullOrEmpty(Phone))
return "Please enter your phone number";
if ((propName == "WillAttend") && !WillAttend.HasValue) // Does the drop down have a value?
return "Please specify whether you'll attend";
return null;
}
}
public void Submit()
{
EnsureCurrentlyValid();
// Send via email
var message = new StringBuilder();
message.AppendFormat("Date: {0:yyyy-MM-dd hh:mm}\n", DateTime.Now);
message.AppendFormat("Email: {0}\n", Email);
message.AppendFormat("Phone: {0}\n", Phone);
message.AppendFormat("Can come: {0}\n", WillAttend.Value? "Yes" : "No");
SmtpClient smtpClient = new SmtpClient("smtp.example.com");
smtpClient.Send(new MailMessage(
"rsvps@example.com", // From
"person@example.com", // To
Name + (WillAttend.Value? " will attend" : " won't attend"), // Subject
message.ToString() // Body
));
}
private void EnsureCurrentlyValid()
{
// I'm valid if IDataErrorInfo.this[] returns null for every property
var propsToValidate = new[] { "Name", "Email", "Phone", "WillAttend" };
bool isValid = propsToValidate.All(x => this[x] == null); // This is a lambda expression
if (!isValid)
throw new InvalidOperationException("Can't submit invalid GuestResponse");
}
}
}