Open farzinmonsef opened 4 years ago
using System; using System.Collections.Generic;
using System.Data.SqlClient;
using Common.SendEmail.Model;
namespace Common.SendEmail.DataAccess
{
public class AppSettingData : BaseFactory
{
public List
List<SqlParameter> parmList = new List<SqlParameter>();
SqlParameter p = new SqlParameter("@toolid", toolId);
parmList.Add(p);
result = GetList<AppSetting>("EQMUser.AppSettingList", parmList);
return result;
}
public string GetByKey(string key, int toolId)
{
string targetValue = string.Empty;
List<AppSetting> result = new List<AppSetting>();
List<SqlParameter> parmList = new List<SqlParameter>();
SqlParameter p = new SqlParameter("@key", key);
parmList.Add(p);
SqlParameter p2 = new SqlParameter("@toolId", toolId);
parmList.Add(p2);
result = GetList<AppSetting>("EQMUser.AppSettingByKey", parmList);
foreach (AppSetting item in result)
{
targetValue = item.Value;
}
return targetValue;
}
public string GetByKey(string key)
{
string targetValue = string.Empty;
int defaultToolId = 164;
List<AppSetting> result = new List<AppSetting>();
List<SqlParameter> parmList = new List<SqlParameter>();
SqlParameter p = new SqlParameter("@key", key);
parmList.Add(p);
SqlParameter p2 = new SqlParameter("@toolId", defaultToolId);
parmList.Add(p2);
result = GetList<AppSetting>("EQMUser.AppSettingByKey", parmList);
foreach (AppSetting item in result)
{
targetValue = item.Value;
}
return targetValue;
}
}
}
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks;
using Common.SendEmail.Model;
namespace Common.SendEmail.DataAccess
{
public class AuditData : BaseFactory
{
public void Log(AuditItem item)
{
IEnumerable
this.ExecuteNonQuery("EQMUser.AuditInsertUpdate", System.Data.CommandType.StoredProcedure, parmList.ToArray());
}
}
}
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Reflection;
using Common;
//using Halos.Configuration;
namespace Common.SendEmail.DataAccess { public class BaseFactory : IDisposable { public const bool IgnoreCase = true; public const bool RegardCase = false; public const bool AsStoredProc = true; public const bool AsQueryText = false;
private string _connectionName = "";
public string ConnectionName
{
get { return _connectionName; }
set { _connectionName = value; }
}
private ConnectionStringSettings GetCString(string cStringName)
{
return ConfigurationManager.ConnectionStrings[ //DynamicConfigurationManager.AppSettings["DatabaseToUse"]];
"EQM" //ConfigurationManager.AppSettings["DatabaseToUse"]
];
}
public BaseFactory()
{
ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings[ //DynamicConfigurationManager.AppSettings["DatabaseToUse"]];
"EQM" //ConfigurationManager.AppSettings["DatabaseToUse"]
];
_connectionName = (connectionString == null? "EQM":(connectionString.Name == null ? "EQM": connectionString.Name)); // "DEV_POA_DB";
}
public BaseFactory(string connectionName)
{
if (connectionName.ToLower().Contains("touse"))
{
ConnectionStringSettings connectionString = GetCString(connectionName);
_connectionName = connectionString.Name;
}
else
_connectionName = connectionName;
}
public SqlConnection CreateOpenConnection()
{
return CreateOpenConnection(_connectionName);
}
private SqlConnection connection;
public SqlConnection Connection
{
get
{
if (connection == null || connection.State != ConnectionState.Open)
{
connection = CreateOpenConnection();
}
return connection;
}
}
public SqlConnection CreateOpenConnection(string cStringName)
{
connection = CreateConnection(cStringName);
try
{
connection.Open();
}
catch (Exception ex)
{
var s = ex.ToString();
connection.Dispose();
throw new Exception("Connection failed to Open: " + s);
}
return connection;
}
public string CString { get; set; }
//public SqlConnection CreateConnection()
//{
// return CreateConnection("POA");
//}
public SqlConnection CreateConnection(string cStringName)
{
if (string.IsNullOrWhiteSpace(CString) || CString != cStringName)
{
ConnectionStringSettings connectionString;
if (cStringName.ToLower().Contains("touse"))
{
connectionString = ConfigurationManager.ConnectionStrings[
//DynamicConfigurationManager.AppSettings[cStringName]];
"EQM" //ConfigurationManager.AppSettings["DatabaseToUse"]
];
ConnectionName = connectionString.Name;
}
else
connectionString = ConfigurationManager.ConnectionStrings[cStringName]; //DynamicConfigurationManager.AppSettings["DatabaseToUse"]];
if (connectionString == null) //|| connectionString.ConnectionString == null)
throw new Exception("No db connection string available");
CString = connectionString.ConnectionString;
}
var connection = new SqlConnection(CString);
if (connection == null)
throw new Exception("No db connection available");
return connection;
}
/// <summary>
///
/// </summary>
/// <param name="parms"></param>
/// <param name="sqlComm"></param>
/// <returns></returns>
private SqlCommand AttachParameters(IEnumerable<SqlParameter> parms, SqlCommand sqlComm)
{
var sqlParameters = parms as SqlParameter[] ?? parms.ToArray();
if (sqlParameters.Any())
sqlComm.Parameters.AddRange(sqlParameters.ToArray());
return sqlComm;
}
public SqlCommand CreateSqlCommand(string cmdText, string cStringName, CommandType cmdType, IEnumerable<SqlParameter> parms)
{
SqlCommand cmd = new SqlCommand(cmdText, CreateOpenConnection(cStringName));
cmd = AttachParameters(parms, cmd);
return cmd;
}
public IEnumerable<SqlParameter> StripChangeDates(IEnumerable<SqlParameter> parmList)
{
IEnumerable<SqlParameter> pList = from SqlParameter p in parmList.Select(i => i.ParameterName.ToLower() != "@modifiedon" &&
i.ParameterName.ToLower() != "@createedon")
select p;
return pList;
}
public IEnumerable<SqlParameter> CreateShortParms<T>(object from, bool isInsert = false, string paramNames = "")
{
List<SqlParameter> toList = new List<SqlParameter>();
Type t = from.GetType();
PropertyInfo[] properties = t.GetProperties();
foreach (PropertyInfo property in properties)
{
SqlParameter to = new SqlParameter();
to.ParameterName = "@" + property.Name;
//if (isInsert && property.Name.ToLower().Contains("modified"))
// continue; // don't need properties named modified on insert
if (property.Name.ToLower().Contains("errors"))
continue;
if (!string.IsNullOrEmpty(paramNames) && (!paramNames.ToLower().Contains("@" + property.Name.ToLower())))
continue;
var v = property.GetValue(from);
if (v != null)
{
DateTime dt = new DateTime();
if (v.ToString().Equals(dt.ToString()))
{
continue; // don't want an empty date value
}
to.Value = property.GetValue(from);
}
toList.Add(to);
}
return toList;
}
public IEnumerable<SqlParameter> CreateParms<T>(object from, bool isInsert = false) where T : class, new()
{
return CreateShortParms<T>(from, isInsert, "");
}
public SqlDataReader GetDataAsReader(SqlCommand cmd)
{
SqlDataReader reader = cmd.ExecuteReader();
return reader;
}
public IEnumerable<T> GetDataAsList<T>(IDataReader reader, Func<IDataRecord, T> BuildObject)
{
try
{
while (reader.Read())
{
yield return BuildObject(reader);
}
}
finally
{
reader.Dispose();
}
}
public IEnumerable<T> GetList<T>(string cmdText, bool asProc = false, int timeout = 60) where T : class, new()
{
int recordCount;
List<SqlParameter> parms = new List<SqlParameter>();
return GetList<T>(cmdText, parms, out recordCount, true, asProc, timeout);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cmdText"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public IEnumerable<T> GetList<T>(string cmdText, int timeout = 60) where T : class, new()
{
return GetList<T>(cmdText, new List<SqlParameter>());
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cmdText"></param>
/// <param name="parms"></param>
/// <param name="ignoreCase"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public List<T> GetList<T>(string cmdText, IEnumerable<SqlParameter> parms, bool ignoreCase = true, int timeout = 60)
where T : class, new()
{
int recordCount;
return GetList<T>(cmdText, parms, out recordCount, ignoreCase, timeout);
}
public List<T> GetListByInt<T>(string cmdText, int key, string keyParmName, bool asProc = true, int timeout = 60) where T : class, new()
{
int count = 0;
return GetListByInt<T>(cmdText, key, keyParmName, out count, asProc, timeout);
}
public List<T> GetListByInt<T>(string cmdText, int key, string keyParmName, out int recordCount, bool asProc = true, int timeout = 60) where T : class, new()
{
var sqlComm = new SqlCommand(cmdText)
{
CommandType = asProc ? CommandType.StoredProcedure : CommandType.Text,
CommandTimeout = timeout,
};
SqlParameter p = new SqlParameter(keyParmName, key);
List<SqlParameter> parms = new List<SqlParameter>();
parms.Add(p);
return GetList<T>(AttachParameters(parms, sqlComm), out recordCount, timeout, true);
}
public List<T> GetList<T>(string cmdText,
IEnumerable<SqlParameter> parms,
out int recordCount,
bool ignoreCase = true,
bool asProc = true,
int timeout = 60) where T : class, new()
{
var sqlComm = new SqlCommand(cmdText)
{
CommandType = asProc ? CommandType.StoredProcedure : CommandType.Text,
CommandTimeout = timeout,
};
return GetList<T>(AttachParameters(parms, sqlComm), out recordCount, timeout, ignoreCase);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cmdText"></param>
/// <param name="parms"></param>
/// <param name="recordCount"></param>
/// <param name="ignoreCase"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public List<T> GetList<T>(string cmdText,
IEnumerable<SqlParameter> parms,
out int recordCount,
bool ignoreCase = true,
int timeout = 60) where T : class, new()
{
return GetList<T>(cmdText, parms, out recordCount, ignoreCase, true, timeout);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="command"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public List<T> GetList<T>(SqlCommand command, int timeout = 30) where T : class, new()
{
int recordCount;
return GetList<T>(command, out recordCount, timeout);
}
public List<T> GetList<T>(SqlCommand command, bool ignoreCase = true, int timeout = 60) where T : class, new()
{
int recordCount;
return GetList<T>(command, out recordCount, timeout, ignoreCase);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="command"></param>
/// <param name="recordCount"></param>
/// <param name="timeout"></param>
/// <param name="ignoreCase"></param>
/// <returns></returns>
public List<T> GetList<T>(SqlCommand command, out int recordCount, int timeout = 60, bool ignoreCase = true)
where T : class, new()
{
const string totalColumnName = "Total";
var ds = GetDataSet(command, timeout);
var resultList = ds.Tables[0].DataTableToList<T>(ignoreCase);
recordCount = 0;
if (ds.Tables.Count > 1)
{
recordCount = ds.Tables[1].Rows[0].Field<Int32>(totalColumnName);
}
return resultList ?? new List<T>();
}
//public T GetFromXml<T>(string cmdText, CommandType cmdType, IEnumerable<SqlParameter> parms, int timeout = 60)
//{
// var result = default(T);
// using (SqlConnection con = CreateOpenConnection())
// {
// using (
// var command = new SqlCommand
// {
// Connection = con,
// CommandText = cmdText,
// CommandType = cmdType,
// CommandTimeout = timeout
// })
// {
// command.Parameters.AddRange(parms.ToArray());
// var oResult = command.ExecuteXmlReader();
// XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
// result = (T)xmlSerializer.Deserialize(oResult);
// }
// }
// return result;
//}
/// <summary>
/// Calls db ExecuteScaler
/// </summary>
/// <typeparam name="T">T can be any simple type (int, string, date, datetime)</typeparam>
/// <param name="cmdText"></param>
/// <param name="cmdType"></param>
/// <param name="parms"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public T ExecuteScalar<T>(string cmdText, CommandType cmdType, IEnumerable<SqlParameter> parms, int timeout = 60)
{
var result = default(T);
using (SqlConnection con = CreateOpenConnection())
{
using (
var command = new SqlCommand
{
Connection = con,
CommandText = cmdText,
CommandType = cmdType,
CommandTimeout = timeout
})
{
if (cmdType == CommandType.StoredProcedure && parms != null) command.Parameters.AddRange(parms.ToArray());
var oResult = command.ExecuteScalar();
if (oResult != null)
result = (T)oResult;
}
}
return result;
}
/// <summary>
///
/// </summary>
/// <param name="cmdText"></param>
/// <param name="parms"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public DataSet GetDataSet(string cmdText, IEnumerable<SqlParameter> parms, int timeout = 60)
{
using (var cmd = new SqlCommand
{
CommandText = cmdText,
CommandTimeout = timeout,
CommandType = CommandType.StoredProcedure
})
{
cmd.Parameters.AddRange(parms.ToArray());
return GetDataSet(cmd, timeout);
}
}
/// <summary>
///
/// </summary>
/// <param name="command"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public DataSet GetDataSet(SqlCommand command, int timeout = 60)
{
var ds = new DataSet();
using (var con = command.Connection == null || command.Connection.State != ConnectionState.Open ? CreateConnection(_connectionName) : command.Connection)
{
if (con.State != ConnectionState.Open) con.Open();
using (var t = con.BeginTransaction(IsolationLevel.ReadUncommitted))
{
try
{
using (command)
{
command.Connection = con;
command.Transaction = t;
var adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
}
t.Commit();
}
catch (Exception ex)
{
t.Rollback();
throw ex;
}
}
}
//if the ds adapter fill has no data and to prevent an object reference issues, adding a new table when count is 0
if (ds.Tables.Count == 0)
{
ds.Tables.Add(new DataTable("Empty"));
}
return ds;
}
/// <summary>
///
/// </summary>
/// <param name="commandText"></param>
/// <param name="commandType"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public int ExecuteNonQuery(string commandText, CommandType commandType, params SqlParameter[] parameters)
{
int returnValue;
return ExecuteNonQuery(commandText, commandType, parameters, out returnValue);
}
public int ExecuteNonQuery(string commandText, CommandType commandType, IEnumerable<SqlParameter> parameters,
out int returnValue)
{
var parms = parameters.ToList();
parms.Add(new SqlParameter { ParameterName = "RetVal", Direction = ParameterDirection.ReturnValue });
var result = 0;
var cmd = new SqlCommand(commandText)
{
CommandType = commandType,
CommandTimeout = 30
};
cmd.Parameters.AddRange(parms.ToArray());
SqlParameterCollection outParameters = ExecuteNonQuery(cmd, out returnValue);
foreach (SqlParameter p in outParameters)
{
if (returnValue == 0)
{
if (p.ParameterName == "RetVal")
returnValue = (int)p.Value;
}
if (p.ParameterName == "result")
result = (int)p.Value;
}
return result;
}
public SqlParameterCollection ExecuteNonQuery(SqlCommand command)
{
int returnValue;
return ExecuteNonQuery(command, out returnValue);
}
public SqlParameterCollection ExecuteNonQuery(SqlCommand command, out int returnValue)
{
int result;
using (var con = CreateOpenConnection())
{
command.Connection = con;
result = command.ExecuteNonQuery();
returnValue = command.Parameters.Contains("RetVal") ?
command.Parameters["RetVal"].Value is int ? (int)command.Parameters["RetVal"].Value : 0 : 0;
}
var parms = command.Parameters;
parms.Add(new SqlParameter("result", result));
return parms;
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
if (connection != null)
if (connection.State != ConnectionState.Closed) connection.Close();
}
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~BaseFactory() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
}
using System.ComponentModel.DataAnnotations;
namespace Common.SendEmail.Model { public class AppPortalTool { [Key] public int Id { get; set; } public string Tool { get; set; } public bool IsVisible { get; set; }
//public virtual AppSetting AppSetting { get; set; }
}
}
using System; using System.ComponentModel.DataAnnotations;
namespace Common.SendEmail.Model { public class AppSetting : IAppSetting { [Key] public int Id { get; set; } public int ToolId { get; set; } public string Key { get; set; } public string Value { get; set; } public string Description { get; set; } public string TypeOf { get; set; } public bool IsUnique { get; set; } public string LastNote { get; set; } public DateTime? LastModifiedDate { get; set; } public string LastModifiedBy { get; set; }
// [ForeignKey("ToolId")] public virtual AppPortalTool AppPortalTool { get; set; } } }
using System; using System.ComponentModel.DataAnnotations;
namespace Common.SendEmail.Model { public class AppSettingModel { public int Id { get; set; }
[Display(Name = "ToolId")]
public int ToolId { get; set; }
[Display(Name = "Key")]
[Required(ErrorMessage = "Key is required")]
public string Key { get; set; }
[Display(Name = "Value")]
[Required(ErrorMessage = "Value is required")]
public string Value { get; set; }
[Display(Name = "Description")]
public string Description { get; set; }
[Display(Name = "IsUnique")]
public bool IsUnique { get; set; }
[Display(Name = "LastNote")]
[Required(ErrorMessage = "Note is required")]
public string LastNote { get; set; }
[Display(Name = "LastModifiedDate")]
public DateTime? LastModifiedDate { get; set; }
[Display(Name = "LastModifiedBy")]
public string LastModifiedBy { get; set; }
public string UserName { get; set; }
}
}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace Common.SendEmail.Model { public class AuditItem { public int? AuditId { get; set; } public string ItemKey { get; set; }
public string Summary { get; set; }
public string Detail { get; set; }
public DateTime AuditDateTime { get; set; }
}
}
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace Common.SendEmail.Model { public class EmailMessage : IEmailMessage { public string To { get; set; } public string Cc { get; set; } public string Key { get; set; } public string Body { get; set; } public string Subject { get; set; } public int? ItemId { get; set; } public string RequestBusinessId { get; set; } public string Error { get; set; }
public Stream ContentStream { get; set; }
public string AttachmentFileName { get; set; }
public string MediaTypeName { get; set; }
}
}
using System;
namespace Common.SendEmail.Model { public interface IAppSetting { AppPortalTool AppPortalTool { get; set; } string Description { get; set; } int Id { get; set; } bool IsUnique { get; set; } string Key { get; set; } string LastModifiedBy { get; set; } DateTime? LastModifiedDate { get; set; } string LastNote { get; set; } int ToolId { get; set; } string TypeOf { get; set; } string Value { get; set; } } }
using System.Collections.Generic;
namespace Common.SendEmail.Model
{
public interface IAppSettingBLL
{
//IEnumerable
IEnumerable<AppSetting> GetAppSettingsDataByToolId(int toolId);
string GetAppSettingByKey(string key, int toolId);
string GetAppSettingByKey(string key);
//AppSetting GetAppSetting(string Key);
//AppSetting GetAppSettingById(int id);
//void AddAppSetting(AppSetting appSetting);
//void UpdateAppSetting(AppSetting appSetting);
//void DeleteAppSetting(AppSetting appSetting);
}
}
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace Common.SendEmail.Model { public interface IEmailMessage { string Body { get; set; } string Key { get; set; } string Cc { get; set; } string Error { get; set; } string Subject { get; set; } int? ItemId { get; set; } string RequestBusinessId { get; set; } string To { get; set; } Stream ContentStream { get; set; } string AttachmentFileName { get; set; } string MediaTypeName { get; set; } } }
using System; using System.Collections.Generic; using System.Configuration; using Common.SendEmail.Model;
namespace Common.SendEmail { public class AppSettingBLL : IAppSettingBLL { public AppSettingBLL() { //ConfigurationManager.RefreshSection("appSettings"); }
//public AppSetting GetAppSetting(string Key)
//{
// return _appSettingRepo.GetAppSetting(Key);
//}
//public IEnumerable<AppSetting> GetAppSettingsData()
//{
// return _appSettingRepo.GetAppSettingsData();
//}
//public void AddAppSetting(AppSetting appSetting)
//{
// _appSettingRepo.AddAppSetting(appSetting);
// _unitOfWork.Commit();
//}
//public void UpdateAppSetting(AppSetting appSetting)
//{
// _appSettingRepo.UpdateAppSetting(appSetting);
// _unitOfWork.Commit();
//}
//public void DeleteAppSetting(AppSetting appSetting)
//{
// _appSettingRepo.DeleteAppSetting(appSetting);
// _unitOfWork.Commit();
//}
//public AppSetting GetAppSettingById(int id)
//{
// return _appSettingRepo.GetAppSettingById(id);
//}
public string GetAppSettingByKey(string key)
{
using (Common.SendEmail.DataAccess.AppSettingData ctx = new DataAccess.AppSettingData())
{
return ctx.GetByKey(key);
}
}
public string GetAppSettingByKey(string key, int toolId)
{
using (Common.SendEmail.DataAccess.AppSettingData ctx = new DataAccess.AppSettingData())
{
return ctx.GetByKey(key, toolId);
}
}
public IEnumerable<AppSetting> GetAppSettingsDataByToolId(int toolId)
{
using (Common.SendEmail.DataAccess.AppSettingData ctx = new DataAccess.AppSettingData())
{
return ctx.GetByToolId(toolId);
}
}
}
}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
using Common.SendEmail.Model; using Common.SendEmail.DataAccess;
namespace Common.SendEmail {
public class AuditBLL
{
public void Log(string Summary, string Detail)
{
Log(string.Empty, Summary, Detail);
}
public void Log(string key, string Summary, string Detail)
{
AuditItem a = new AuditItem();
a.ItemKey = string.IsNullOrEmpty(key) ? "EQMEMAIL" : key;
a.Summary = Summary;
a.Detail = Detail;
Log(a);
}
public void Log(AuditItem item)
{
using (AuditData ctx = new AuditData())
{
ctx.Log(item);
}
}
}
}
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Mail; using System.Text.RegularExpressions;
using Common.SendEmail.Model;
namespace Common.SendEmail { public class Email : IEmail { private readonly IAppSettingBLL _oAppSettingDomain;
public string SmtpServerName, SmtpPortNumber, Username, Password;
public string ToEmail, CcEmail, BccEmail, FromEmail, Subject, HtmlBody, PendReqBccEmail, PendReqFromEmail, PendReqSubject;
public string ApplicationUrl, ContactEmail, ErrorMessage = null;
public string ImageUrl, BaseUrl;
public string SimpleUrl;
public Email()
{
_oAppSettingDomain = new Common.SendEmail.AppSettingBLL();
InitializeAppSetting();
}
public Email(appPortalTool toolID)
{
_oAppSettingDomain = new Common.SendEmail.AppSettingBLL();
InitializeAppSetting(toolID);
}
public Email(Dictionary<string, string> settings)
{
_oAppSettingDomain = new Common.SendEmail.AppSettingBLL();
InitializeAppSetting();
BaseUrl = settings.Count() > 0 ? settings["baseUrl"] : string.Empty;
string[] parts = BaseUrl.Split(':');
SimpleUrl = parts[0] + ":" + parts[1];
ImageUrl = settings.Count() > 1 ? settings["imageUrl"] : string.Empty;
}
private void InitializeAppSetting()
{
InitializeAppSetting(appPortalTool.EQMEmail);
}
private void InitializeAppSetting(appPortalTool toolID)
{
AppSettingModel model = new AppSettingModel();
var appSettingEmailData = _oAppSettingDomain.GetAppSettingsDataByToolId(Convert.ToInt32(appPortalTool.SMTPSettings));
var settingEmailData = appSettingEmailData as IList<AppSetting> ?? appSettingEmailData.ToList();
if (appSettingEmailData != null && settingEmailData.Count > 0)
{
SmtpServerName = settingEmailData.FirstOrDefault(x => x.Key == "smtpServer")?.Value;
SmtpPortNumber = settingEmailData.FirstOrDefault(x => x.Key == "smtpPort")?.Value;
Username = settingEmailData.FirstOrDefault(x => x.Key == "SmtpUsername")?.Value;
Password = settingEmailData.FirstOrDefault(x => x.Key == "SmtpPassword")?.Value;
}
appSettingEmailData = _oAppSettingDomain.GetAppSettingsDataByToolId(Convert.ToInt32(toolID));
settingEmailData = appSettingEmailData as IList<AppSetting> ?? appSettingEmailData.ToList();
if (appSettingEmailData != null && settingEmailData.Count > 0)
{
ToEmail = settingEmailData.FirstOrDefault(x => x.Key == "TO")?.Value;
CcEmail = settingEmailData.FirstOrDefault(x => x.Key == "CC")?.Value;
BccEmail = settingEmailData.FirstOrDefault(x => x.Key == "BCC")?.Value;
FromEmail = settingEmailData.FirstOrDefault(x => x.Key == "FROM")?.Value;
Subject = settingEmailData.FirstOrDefault(x => x.Key == "SUBJECT")?.Value;
HtmlBody = settingEmailData.FirstOrDefault(x => x.Key == "cosecreviewemail")?.Value;
ApplicationUrl = settingEmailData.FirstOrDefault(x => x.Key == "ApplicationURL")?.Value;
ContactEmail = settingEmailData.FirstOrDefault(x => x.Key == "ContactEmail")?.Value;
}
}
public IEmailMessage GetSettings()
{
IEmailMessage item = new EmailMessage();
item.Body = HtmlBody;
item.Cc = CcEmail;
item.Subject = Subject;
item.To = ToEmail;
return item;
}
public void SendEmail(string to, string cc, string emailKey, int? itemId = null, string requestBusinessId = null)
{
string emailBody = string.Format(_oAppSettingDomain.GetAppSettingByKey(emailKey), itemId.Value.ToString(), BaseUrl, requestBusinessId);
//SendEmailBody(to, cc, emailBody, string.Format(Subject + ": {0}", itemId));
SendEmailBody(to, cc, emailBody, string.Format(Subject + ": {0}", requestBusinessId) );
}
//public bool SendEmailNew(EmailDetail emailDetail)
//{
// MailMessage message = new MailMessage();
// try
// {
// SmtpClient smtp = new SmtpClient();
// message = CreateMailMessage(emailDetail, EmailType.FinraSurvey);
// List<MemoryStream> msList = new List<MemoryStream>();
// foreach (var attachment in survey.SurveyAttachment)
// {
// byte[] file = File.ReadAllBytes("C:\\ICON1.png");
// MemoryStream ms = new MemoryStream(file);// attachment.FileData);
// message.Attachments.Add(new Attachment(ms, attachment.FileName, MediaTypeNames.Application.Octet));
// msList.Add(ms);
// }
// smtp.Host = _appSettings.GetValue("SmtpClientHost");
// smtp.Port = Convert.ToInt32(_appSettings.GetValue("SmtpClientPort"));
// smtp.Send(message);
// message.Dispose();
// return true;
// }
// catch (Exception e)
// {
// LogFailedEmail(e, message);
// return false;
// }
//}
public IEmailMessage Send(IEmailMessage item)
{
AuditBLL auditLogic = new Common.SendEmail.AuditBLL();
IEmailMessage response = new EmailMessage();
if (item == null)
throw new Exception("this makes no sense");
response = item;
if (!string.IsNullOrWhiteSpace(item.Key))
{
try
{
string subject = string.Empty;
//if (item != null && item.Subject != null && item.Subject.Contains('{'))
// subject = string.Format(item.Subject, item.ItemId.Value);
//else
//Farz if (item != null && item.Subject != null && item.Subject.Contains('{'))
//Farz subject = string.Format(item.Subject, item.RequestBusinessId);
//Farz else
//Farz subject = string.Format(Subject + ": {0}", item.RequestBusinessId);
// send using key
string emailBody = "";
//string.Format(_oAppSettingDomain.GetAppSettingByKey(response.Key), item.ItemId.Value.ToString(), BaseUrl);
//Farz string emailBody = string.Format(_oAppSettingDomain.GetAppSettingByKey(response.Key), item.ItemId.Value.ToString(), BaseUrl, item.RequestBusinessId);
//auditLogic.Log("Email Line 96 - Body: ", emailBody);
FileStream fs = new FileStream(item.AttachmentFileName, FileMode.Open, FileAccess.Read);
Byte[] imgByte = new byte[fs.Length];
fs.Read(imgByte, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
item.ContentStream = new MemoryStream();
item.ContentStream.Write(imgByte, 0, imgByte.Length);
item.ContentStream.Position = 0;
if (item.ContentStream != null && item.ContentStream.Length > 0)
{
//auditLogic.Log("Email Line 96 - Body: ", emailBody);
SendEmailBody(response.To, response.Cc, response.Body, response.Subject
//SendEmailBody(response.To, response.Cc, emailBody, subject,
, item.ContentStream, item.AttachmentFileName, item.MediaTypeName);
}
else
{
//SendEmailBody(response.To, response.Cc, emailBody, string.Format(Subject + ": {0}", item.ItemId.Value));
SendEmailBody(response.To, response.Cc, emailBody, Subject
//,item.ContentStream, item.AttachmentFileName, item.MediaTypeName
);
}
}
catch (Exception keyEx)
{
item.Error = keyEx.ToString();
}
}
else
{
try
{
//Send using body
SendEmailBody(response.To, response.Cc, response.Body, response.Subject);
}
catch (Exception bodyEx)
{
item.Error = bodyEx.ToString();
}
}
return item;
}
public void SendEmailBody(string to, string cc, string emailBody, string msgSubject)
{
SendEmailBody(to, cc, emailBody, msgSubject, null, string.Empty, string.Empty);
}
public void SendEmailBody(string to, string cc, string emailBody, string msgSubject,
System.IO.Stream attachContent, string fileName, string mediaType)
{
AuditBLL audit = new AuditBLL();
string regEx = "^[EFBH]|^01hw*";
bool islocalDev = Regex.IsMatch(Environment.MachineName, regEx);
if (string.IsNullOrWhiteSpace(SmtpServerName))
{
throw new Exception("SMTP Server Name not provided.");
}
SmtpClient smtp = new SmtpClient(SmtpServerName);
if (!string.IsNullOrWhiteSpace(SmtpPortNumber))
{
var portNumber = -1;
if (int.TryParse(SmtpPortNumber, out portNumber))
smtp.Port = portNumber;
}
if (!string.IsNullOrWhiteSpace(Username) & !string.IsNullOrWhiteSpace(Password))
smtp.Credentials = new NetworkCredential(Username, Password);
MailMessage msg = new MailMessage();
// need to create a component to handle is lowerlane logic
if (!string.IsNullOrWhiteSpace(to)) msg.To.Add(to.ToLower());
//if (Environment.MachineName.ToLower().Equals("wsdne07aleot"))
// msg.CC.Add("don.kirby@bankofamerica.com");
//else
//{
// if (cc.ToLower() == "donotcc")
// {
// cc = string.Empty;
// }
// else
if (!string.IsNullOrWhiteSpace(cc))
{
msg.CC.Add(cc.ToLower().EndsWith(";") ? cc.Substring(0, cc.Length - 1).ToLower() : cc.ToLower());
}
//}
//if (!string.IsNullOrWhiteSpace(BccEmail)) msg.Bcc.Add(BccEmail.ToLower());
if (!string.IsNullOrWhiteSpace(BccEmail))
{
var bccAddresses = BccEmail.Split(';'); // now allowing multiple bcc email addresses in AppSettings by separating with a semi-colon
foreach (var bccAddress in bccAddresses)
{
msg.Bcc.Add(bccAddress.ToLower().Trim());
}
}
if (!string.IsNullOrWhiteSpace(FromEmail)) msg.From = new MailAddress(FromEmail.ToLower());
if (!string.IsNullOrWhiteSpace(msgSubject)) msg.Subject = msgSubject;
msg.Body = emailBody;
//audit.Log("line 180", emailBody);
if (attachContent != null && attachContent.Length > 0)
{
//audit.Log("line 184", "Add attachment");
Attachment att = new Attachment(attachContent, fileName, mediaType);
msg.Attachments.Add(att);
//audit.Log("line 187", "Added attachment");
}
msg.IsBodyHtml = msg.Body.ToLower().Contains("<html>");
//audit.Log("line 191", string.Format("Is html content {0}", msg.IsBodyHtml));
msg.Priority = MailPriority.Normal;
if (!islocalDev)
{
try
{
audit.Log("email sending", "sending");
audit.Log("to:", to);
audit.Log("cc:", cc);
audit.Log("subject", msgSubject);
audit.Log("msg body", msg.Body);
smtp.Send(msg);
audit.Log("email sent", "sent");
}
catch (Exception ex)
{
string errorData = ex.ToString() + " From " + msg.From.ToString() + " To " + msg.To.ToString() + " " + msg.Subject + " " + msg.Headers.ToString() + " " + smtp.Port + " " + smtp.Host + " " + smtp.Credentials + " BCC " + msg.Bcc + " CC " + msg.CC;
audit.Log("emailerror", "email send error", errorData);
throw;
}
}
else
{
DateTime now = DateTime.Now;
string sDate = now.ToShortDateString();
Guid g = Guid.NewGuid();
System.IO.File.WriteAllText(string.Format(@"c:\temp\splat{0}.txt", g.ToString()),
string.Format("TO: {0}" + Environment.NewLine + "CC: {1}" + Environment.NewLine + "Body: {2}",
msg.To, msg.CC, msg.Body));
}
}
}
}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace Common.SendEmail { public enum MessageSeverity { None, Info, Success, Warning, Danger }
public enum appPortalTool
{
EqmApp = 1,
MERGE = 2,
EQMEmail = 3,
EQMExportPath = 4,
EQMRequestExport = 5,
EQMPendingReport = 6,
SMTPSettings = 7
}
public enum appSetting
{
CORSPath = 1,
ServerPath,
FolderExpirationDays,
LegalUserHierarchyCode,
AdminADGroup,
ContactSupport,
FAQ
}
}
using Common.SendEmail.Model; namespace Common.SendEmail { public interface IEmail { void SendEmail(string to, string cc, string emailKey, int? itemId, string requestBusinessId); void SendEmailBody(string to, string cc, string emailBody, string msgSubject); void SendEmailBody(string to, string cc, string emailBody, string msgSubject, System.IO.Stream attachContent, string fileName, string mediaType); IEmailMessage GetSettings(); IEmailMessage Send(IEmailMessage item); } }
Common.SendEmail