public static Return SaveToCache(string url, string html) { try { //return new Return(); var fileInfo = GetFileInfoFromUrl(url); if (!fileInfo.Directory.Exists) { var directoryInfo = Directory.CreateDirectory(fileInfo.Directory.FullName); } else { /*if ((CacheDurationInSeconds != null) && (DateTime.Now < fileInfo.LastWriteTime.AddSeconds((double)CacheDurationInSeconds))) * { * return new Return() { Error = ErrorHelper.CreateError("Cache hasn't expired yet") }; * }*/ //File.Delete(fileInfo.FullName); } File.WriteAllText(fileInfo.FullName, html); //ContextHelper.SetToCache(url, html); return(new Return()); } catch (Exception ex) { var error = ErrorHelper.CreateError($"Error Creating FileSystem Cache: '{url}", ex.Message); ErrorHelper.LogException(error.Exception); return(new Return(ex, error)); } }
public static Return RestoreDatabase(string backUpFilePath) { Return returnObj = BaseMapper.GenerateReturn(); if (!string.IsNullOrEmpty(backUpFilePath) && File.Exists(backUpFilePath)) { var databaseName = BaseMapper.GetDataModel().Database.Connection.Database; var sqlCommand = $@"ALTER DATABASE {databaseName} SET Single_User WITH Rollback Immediate; USE master; RESTORE DATABASE {databaseName} FROM DISK = '{backUpFilePath}'; ALTER DATABASE {databaseName} SET Multi_User"; try { var result = BaseMapper.GetDataModel(true).Database.ExecuteSqlCommand(transactionalBehavior: System.Data.Entity.TransactionalBehavior.DoNotEnsureTransaction, sql: sqlCommand); returnObj.SetRawData(result); return(returnObj); } catch (Exception ex) { ErrorHelper.LogException(ex); returnObj.Error = ErrorHelper.CreateError(ex); return(returnObj); } } return(returnObj); }
public static Return GetFromCache(string url) { var returnObj = new Return(); try { //var inContext = (string)ContextHelper.GetFromCache(url); //if (inContext != null && inContext != "") //{ // returnObj.SetRawData(inContext); // return returnObj; //} var fileInfo = GetFileInfoFromUrl(url); if (fileInfo.Exists) { //if (BaseMapper.CanConnectToDB != null && BaseMapper.CanConnectToDB == true) //{ // if ((CacheDurationInSeconds != null) && (DateTime.Now > fileInfo.LastWriteTime.AddSeconds((double)CacheDurationInSeconds))) // { // File.Delete(fileInfo.FullName); // returnObj.Error = new Elmah.Error(new Exception("Cache has expired")); // return returnObj; // } //} using (FileStream fs = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (StreamReader sr = new StreamReader(fs)) { var data = sr.ReadToEnd(); returnObj.SetRawData(data); return(returnObj); } } } else { returnObj.Error = new Elmah.Error(new Exception("Cache does not exist")); return(returnObj); } } catch (Exception ex) { ErrorHelper.LogException(ex); returnObj.Error = new Elmah.Error(ex); return(returnObj); } }
public static string RunOrCompileRazorCode(string tag, string code, object obj, bool compileRazor) { //Only UnComment to debug Razor code, make sure to comment it again because it slows down rendering if (FrameworkSettings.CurrentUser != null && FrameworkSettings.CurrentUser.IsInRole(RoleEnum.Developer)) { var config = new TemplateServiceConfiguration(); config.Debug = true; config.EncodedStringFactory = new RawStringFactory(); var service = RazorEngineService.Create(config); Engine.Razor = service; } if (!string.IsNullOrEmpty(code) && (code.Contains("@{") || code.Contains("@using") || code.Contains("@for") || code.Contains("@Model") || code.Contains("@Raw")) && compileRazor) { code = "@using FrameworkLibrary\n@using WebApplication\n@using System\n@using System.Linq\n@using System.Web\n" + code; var key = "templateKey:" + code; try { if (Engine.Razor.IsTemplateCached(key, null)) { var returnVal = Engine.Razor.Run(key, null, obj); return(returnVal); } var result = Engine.Razor.RunCompile(code, key, null, obj); return(result); } catch (RazorEngine.Templating.TemplateCompilationException ex) { if (tag.StartsWith("{")) { code = tag; } else { code = ""; } var error = ErrorHelper.CreateError(string.Join("\n", ex.CompilerErrors.Select(i => i.ErrorText)), code); ErrorHelper.LogException(error.Exception); throw new Exception(tag + "\r\n\r\n" + error.Exception.Message + "\r\n\r\n" + error.Exception.InnerException); } } else { return(code); } }
public Return CreateAndSendCampaign(string listId, string fromName, string fromEmailAddress, string subject, string title, string htmlMessage) { var returnObj = BaseMapper.GenerateReturn(); var campaign = new Campaign { Type = CampaignType.Regular, Recipients = new Recipient { ListId = listId }, Settings = new Setting { SubjectLine = subject, Title = title, FromName = fromName, ReplyTo = fromEmailAddress }, Tracking = new Tracking { Opens = true, HtmlClicks = true, TextClicks = true }, ReportSummary = new ReportSummary(), DeliveryStatus = new DeliveryStatus(), }; try { var mailChimpCampaign = MailChimpManager.Campaigns.AddOrUpdateAsync(campaign).Result; var ContentRequest = new ContentRequest { Html = htmlMessage }; var content = MailChimpManager.Content.AddOrUpdateAsync(mailChimpCampaign.Id, ContentRequest).Result; MailChimpManager.Campaigns.SendAsync(mailChimpCampaign.Id); return(returnObj); } catch (Exception ex) { ErrorHelper.LogException(ex); returnObj.Error = ErrorHelper.CreateError(ex); return(returnObj); } }
public static string GetFromCache(string url) { try { url = url.ToLower(); IDatabase cache = Connection.GetDatabase(); return(cache.StringGet(url)); } catch (Exception ex) { ErrorHelper.LogException(ex); return(""); } }
public static void SetValue(object obj, string propertyName, object value) { if (propertyName.Contains("{")) { propertyName.Replace("{", ""); } if (propertyName.Contains("}")) { propertyName.Replace("}", ""); } var nestedProperties = StringHelper.SplitByString(propertyName, "."); if (nestedProperties.Length > 0) { object tempNestedProperty = obj; foreach (var nestedProperty in nestedProperties) { var tempPropertyInfo = tempNestedProperty.GetType().GetProperty(nestedProperty); if (tempPropertyInfo != null) { var val = tempPropertyInfo.GetValue(tempNestedProperty, null); if (val is string || val is bool || val is long || val == null) { if (System.ComponentModel.TypeDescriptor.GetConverter(tempPropertyInfo.PropertyType).CanConvertFrom(value.GetType())) { if (value != "") { try { tempPropertyInfo.SetValue(tempNestedProperty, Convert.ChangeType(value, tempPropertyInfo.PropertyType), null); } catch (Exception ex) { ErrorHelper.LogException(new Exception($"Error setting value for property '{tempPropertyInfo.Name}' with value '{value}' for control with ID '{((System.Web.UI.Control)obj).ClientID}'", ex)); } } } } else { tempNestedProperty = val; } } } } }
public static void CopyFrom <T>(this T to, object from, IEnumerable <string> omitPoperties = null) where T : class { if (from == null) { return; } if (omitPoperties == null) { omitPoperties = new List <string>(); } var properties = from.GetType().GetProperties(); var updatedProperties = new Dictionary <PropertyInfo, object>(); foreach (var property in properties) { if (omitPoperties.Contains(property.Name)) { continue; } if (ommitValuesBySegment.Any(ommitValueBySegment => property.ToString().Contains(ommitValueBySegment))) { continue; } var toProperty = to.GetType().GetProperty(property.Name); if (toProperty == null) { continue; } try { var value = property.GetValue(from, null); updatedProperties.Add(toProperty, value); UpdateProperty(toProperty, value, to, from); } catch (Exception ex) { ErrorHelper.LogException(ex); } } }
public dynamic GetTweetsByScreenName(string screenName, int count = 2, bool returnRawResults = false) { var key = "HomeTweets"; var rawResultsKey = "RawResultHomeTweets"; var homeTweets = (List <LinqToTwitter.Status>)ContextHelper.GetFromCache(key); var rawResults = (string)ContextHelper.GetFromCache(rawResultsKey); if ((returnRawResults) && (!string.IsNullOrEmpty(rawResults))) { return(rawResults); } if (homeTweets != null) { return(homeTweets); } try { var twitterContext = new TwitterContext(GetOAuthToken()); var queryResults = (from tweet in twitterContext.Status where tweet.Type == StatusType.User && tweet.ScreenName == screenName && tweet.Count == count && tweet.IncludeRetweets == true select tweet); var queryResultsList = queryResults.ToList(); ContextHelper.SaveToCache(key, queryResultsList, DateTime.Now.AddMinutes(10)); ContextHelper.SaveToCache(rawResultsKey, twitterContext.RawResult, DateTime.Now.AddMinutes(10)); if (returnRawResults) { return(twitterContext.RawResult); } else { return(queryResultsList); } } catch (Exception ex) { ErrorHelper.LogException(ex); ContextHelper.RemoveFromCache(key); } return(homeTweets); }
public static Return SaveToCache(string url, string html) { try { url = url.ToLower(); IDatabase cache = Connection.GetDatabase(); var returnVal = cache.StringSet(url, html, TimeSpan.FromSeconds(SettingsMapper.GetSettings().OutputCacheDurationInSeconds)); return(new Return()); } catch (Exception ex) { ErrorHelper.LogException(ex); return(new Return(ex, ErrorHelper.CreateError(ex))); } }
/// <summary> /// Attempts to update the DB with all the changes made to the current DataContext /// </summary> /// <param name="logError"></param> /// <returns>An instance of the Return class</returns> public static Return SaveDataModel(bool logError = true) { var returnObj = new Return(); try { var returnVal = GetDataModel().SaveChanges(); returnObj.SetRawData(returnVal); if (returnVal == 0) { throw new Exception("No changes made", new Exception("The transaction was successfull but no changes were made")); } } catch (DbEntityValidationException ex) { returnObj.Error = ErrorHelper.CreateError(ex); var message = ""; foreach (var validationError in ex.EntityValidationErrors) { foreach (var error in validationError.ValidationErrors) { message += error.ErrorMessage + "<br />\r\n"; } } returnObj.Error.Message += "<br>\r\n" + message; if (logError) { ErrorHelper.LogException(ex); } } catch (Exception ex) { returnObj.Error = ErrorHelper.CreateError(ex); if (logError) { ErrorHelper.LogException(ex); } } return(returnObj); }
public static void ResizeImage(string OriginalFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider) { if (OriginalFile.StartsWith(".")) { return; } try { FileInfo OrigFileInfo = new FileInfo(OriginalFile); System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile); // Prevent using images internal thumbnail FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); if (OnlyResizeIfWider) { if (FullsizeImage.Width <= NewWidth) { NewWidth = FullsizeImage.Width; } } int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width; if (NewHeight > MaxHeight) { // Resize with height instead NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height; NewHeight = MaxHeight; } System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero); // Clear handle to original file so that we can overwrite it if necessary FullsizeImage.Dispose(); // Save resized picture NewImage.Save(OrigFileInfo.DirectoryName + "/resized/" + OrigFileInfo.Name); } catch (Exception ex) { ErrorHelper.LogException(ex); } }
public static Return ClearAllCache() { if (string.IsNullOrEmpty(baseDir)) { return(new Return()); } //FileCacheHelper.DeleteGenerateNav(); //FileCacheHelper.DeleteSettings(); //FileCacheHelper.DeleteHTMLCache(); var directoryInfo = new DirectoryInfo(URIHelper.ConvertToAbsPath(baseDir)); var subDirectories = directoryInfo.GetDirectories(); var allFiles = directoryInfo.GetFiles(); foreach (var file in allFiles) { try { File.Delete(file.FullName); } catch (Exception ex) { ErrorHelper.LogException(ex); } } foreach (var directory in subDirectories) { try { Directory.Delete(directory.FullName, true); } catch (Exception ex) { ErrorHelper.LogException(ex); } } ContextHelper.ClearAllMemoryCache(); return(new Return()); }
public static Return ClearAllCache() { try { var endpoints = Connection.GetEndPoints(true); foreach (var endpoint in endpoints) { var server = Connection.GetServer(endpoint); server.FlushAllDatabases(); } return(new Return()); } catch (Exception ex) { ErrorHelper.LogException(ex); return(new Return(ex, ErrorHelper.CreateError(ex))); } }
public static Return AddObjectToContext <T>(T obj) where T : class, IMustContainID { var returnObj = new Return(); try { if (GetObjectFromContext(obj) == null) { GetDataModel().Set <T>().Add(obj); } } catch (Exception ex) { ErrorHelper.LogException(ex); returnObj.Error = ErrorHelper.CreateError(ex); } return(returnObj); }
public static bool CanConnectToDBUsingEntities(Entities context) { if (CanConnectToDB != null) { return((bool)CanConnectToDB); } try { context.Database.Connection.Open(); CanConnectToDB = true; return(true); } catch (Exception ex) { CanConnectToDB = false; ErrorHelper.LogException(ex); return(false); } }
public static Return RemoveFromCache(string url) { try { url = url.ToLower(); IDatabase cache = Connection.GetDatabase(); if (cache != null && cache.KeyExists(url)) { cache.KeyDelete(url); } return(new Return()); } catch (Exception ex) { ErrorHelper.LogException(ex); return(new Return(ex, ErrorHelper.CreateError(ex))); } }
/// <summary> /// Attempts to delete an object from the current DataContext /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns>An instance of the Return class</returns> public static Return DeleteObjectFromContext <T>(T obj) where T : class, IMustContainID { var returnObj = new Return(); try { obj = GetObjectFromContext(obj); if (obj != null) { GetDataModel().Set <T>().Remove(obj); } } catch (Exception ex) { returnObj.Error = ErrorHelper.CreateError(ex); ErrorHelper.LogException(ex); } return(returnObj); }
public static Return DeleteCacheDir(string url) { try { url = url + "/"; var fileInfo = GetFileInfoFromUrl(url); if (fileInfo.Directory.Exists) { Directory.Delete(fileInfo.Directory.FullName, true); ContextHelper.ClearAllMemoryCache(); } return(new Return()); } catch (Exception ex) { ErrorHelper.LogException(ex); return(new Return(ex, ErrorHelper.CreateError(ex))); } }
public static Return RemoveFromCache(string url) { try { var fileInfo = GetFileInfoFromUrl(url); if (fileInfo.Exists) { File.Delete(fileInfo.FullName); ContextHelper.RemoveFromCache(url); fileInfo.Directory.Delete(true); } return(new Return()); } catch (Exception ex) { ErrorHelper.LogException(ex); return(new Return(ex, ErrorHelper.CreateError(ex))); } }
public static IEnumerable <RssItem> GetRssItems(string rssFeed, int count = 5) { try { if (!rssFeed.Contains("<")) { return(new List <RssItem>()); } var rssItems = new List <RssItem>(); var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(rssFeed); var items = xmlDoc.GetElementsByTagName("item"); int index = 0; foreach (XmlNode item in items) { if (index >= count) { break; } rssItems.Add(GetRssItem(item)); index++; } return(rssItems); } catch (Exception ex) { ErrorHelper.LogException(ex); return(new List <RssItem>()); } }
public static string ParseData(string data, object obj, bool compileRazor = true) { //return data; if (obj == null) { return(""); } data = data.Trim(); if (data.StartsWith("@") && data.EndsWith("}")) { data = RunOrCompileRazorCode(data, data, obj, compileRazor); } var matches = Regex.Matches(data, openToken + "[a-zA-Z0-9-.&=<>/\\;(\n|\r|\r\n)\"#?']+" + closeToken); foreach (var item in matches) { var tag = item.ToString(); var tagValue = ""; var propertyName = tag.Replace("{", "").Replace("}", ""); var queryStringParams = ""; if (propertyName.Contains("?")) { var segments = propertyName.Split('?').ToList(); propertyName = segments[0]; segments.RemoveAt(0); queryStringParams = string.Join("", segments); } var nestedProperties = StringHelper.SplitByString(propertyName, "."); if (nestedProperties.Length > 0) { if (obj == null) { continue; } object tempNestedProperty = obj; var propertyloopIndex = 0; foreach (var nestedProperty in nestedProperties) { PropertyInfo tempPropertyInfo = null; MethodInfo tempMethodInfo = null; var matchParams = Regex.Matches(nestedProperty, "([a-zA-Z0-9-_]+)"); var methodParamsMatches = new List <string>(); for (int i = 0; i < matchParams.Count; i++) { var val = matchParams[i].ToString(); if (val != "quot") { methodParamsMatches.Add(val); } } if (nestedProperty.Contains("(") && !nestedProperty.Contains(".")) { try { tempMethodInfo = tempNestedProperty.GetType().GetMethod(methodParamsMatches[0]); } catch (Exception ex) { ErrorHelper.LogException(ex); } } else { var prop = nestedProperty; var queryParamsSplit = nestedProperty.Split('?'); if (queryParamsSplit.Count() > 1) { prop = queryParamsSplit.ElementAt(0); } if (tempNestedProperty is JObject) { var val = (tempNestedProperty as JObject).GetValue(prop); if (val is JArray) { tempNestedProperty = String.Join(",", val as JArray); } else { if (val != null) { tempNestedProperty = val.ToString(); } } } else { tempPropertyInfo = tempNestedProperty.GetType().GetProperty(prop); } } if (tempPropertyInfo != null || tempMethodInfo != null) { if (tempPropertyInfo != null) { tempNestedProperty = tempPropertyInfo.GetValue(tempNestedProperty, null); } else if (tempMethodInfo != null) { var objParams = new object[methodParamsMatches.Count - 1]; var parametersInfo = tempMethodInfo.GetParameters(); for (var i = 0; i < methodParamsMatches.Count - 1; i++) { if (parametersInfo.Count() > i) { objParams[i] = Convert.ChangeType(methodParamsMatches[i + 1], parametersInfo[i].ParameterType); } } tempNestedProperty = tempMethodInfo.Invoke(tempNestedProperty, objParams.Where(i => i != null)?.ToArray()); } if (tempNestedProperty != null) { var hasEnumerable = tempNestedProperty.GetType().ToString().Contains("Enumerable") || tempNestedProperty.GetType().ToString().Contains("Collection"); long tmpIndex = 0; if (nestedProperties.Count() > propertyloopIndex + 1) { if (hasEnumerable) { if (long.TryParse(nestedProperties[propertyloopIndex + 1], out tmpIndex)) { var count = 0; foreach (var nestedItem in tempNestedProperty as IEnumerable <object> ) { if (count == tmpIndex) { tempNestedProperty = nestedItem; break; } count++; } continue; } else { var count = 0; var returnValue = ""; var tempPropertiesString = ""; var tmp = nestedProperties.ToList(); tmp.RemoveAt(propertyloopIndex); var newPropertyString = string.Join(".", tmp); foreach (var nestedItem in (dynamic)tempNestedProperty) { var tmpReturn = ParseData("{" + newPropertyString + "}", nestedItem); returnValue += ParseData(tmpReturn, nestedItem); /*var tmpReturn = ParseData("{" + nestedProperties[propertyloopIndex + 1] + "}", nestedItem); * returnValue += ParseData(tmpReturn, nestedItem); * count++;*/ } tagValue = returnValue; } } } else { if (nestedProperties.Length < propertyloopIndex + 1) { return(ParseData("{" + nestedProperties[propertyloopIndex + 1] + "}", tempNestedProperty)); } else if (tempNestedProperty is string) { if (tempMethodInfo != null) { tagValue = tempNestedProperty.ToString(); } //return ParseData("{" + nestedProperties[propertyloopIndex + 1] + "}", tempNestedProperty); } } } } else { var splitEq = nestedProperty.ToString().Split('='); if (splitEq.Count() > 1) { tempPropertyInfo = tempNestedProperty.GetType().GetProperty(splitEq[0]); if (tempPropertyInfo != null) { var returnVal = tempPropertyInfo.GetValue(tempNestedProperty, null); if (splitEq[1].Replace("\"", "") == returnVal.ToString()) { var tmp = nestedProperties.ToList(); tmp.RemoveAt(propertyloopIndex); var newPropertyString = string.Join(".", tmp); tempNestedProperty = ParseData("{" + newPropertyString + "}", tempNestedProperty); } else { tempNestedProperty = ""; } } } } propertyloopIndex++; } if (tempNestedProperty is DateTime) { tagValue = data.Replace(item.ToString(), StringHelper.FormatOnlyDate((DateTime)tempNestedProperty)); } if (tempNestedProperty is string || tempNestedProperty is bool || tempNestedProperty is long) { var val = tempNestedProperty.ToString(); var queryStringSplit = item.ToString().Replace(OpenToken, "").Replace(CloseToken, "").Split('?'); if (queryStringSplit.Count() > 1) { var nv = HttpUtility.ParseQueryString(queryStringSplit.ElementAt(1)); foreach (string key in nv) { var value = nv[key]; val = val.Replace(OpenToken + key + CloseToken, value); } } tagValue = data.Replace(item.ToString(), val); } } if (tagValue.StartsWith("~/")) { tagValue = URIHelper.ConvertToAbsUrl(tagValue); } if (!string.IsNullOrEmpty(tagValue)) { data = RunOrCompileRazorCode(tag, tagValue, obj, compileRazor); } } data = RunOrCompileRazorCode(data, data, obj, compileRazor); return(data); }
public string MakeWebRequest(string urlString, ICredentials credentialCache = null, RequestMethod method = RequestMethod.GET, string queryString = "") { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; var storageItem = WebserviceRequestsMapper.GetByUrl(urlString); var data = ""; if ((storageItem != null) && (EnableCaching) && !storageItem.Response.Contains("unavailable") && storageItem.DateLastModified.AddSeconds(CacheDurationInSeconds) > DateTime.Now) { return(storageItem.Response); } WebserviceRequest request = null; if (storageItem == null) { request = new WebserviceRequest(); } else { request = storageItem; } request.Url = urlString; request.QueryString = queryString; request.Response = ""; request.Method = method.ToString(); request.UrlReferrer = ""; if (System.Web.HttpContext.Current.Request.UrlReferrer != null) { request.UrlReferrer = System.Web.HttpContext.Current.Request.UrlReferrer.AbsoluteUri; } WebRequest webRequest = WebRequest.Create(urlString); if (credentialCache != null) { webRequest.Credentials = credentialCache; webRequest.PreAuthenticate = true; } webRequest.Method = method.ToString(); try { if (method == RequestMethod.POST) { var encoding = new ASCIIEncoding(); byte[] bytes = encoding.GetBytes(queryString); webRequest.ContentLength = bytes.Length; webRequest.ContentType = "application/x-www-form-urlencoded"; using (var webRequestStream = webRequest.GetRequestStream()) { webRequestStream.Write(bytes, 0, bytes.Length); webRequestStream.Flush(); webRequestStream.Close(); } } using (WebResponse webResponse = webRequest.GetResponse()) { Stream dataStream = webResponse.GetResponseStream(); using (StreamReader streamReader = new StreamReader(dataStream)) { data = streamReader.ReadToEnd(); } } } catch (WebException ex) { ErrorHelper.LogException(ex); data = ex.Message; if (ex.Response != null) { // can use ex.Response.Status, .StatusDescription if (ex.Response.ContentLength != 0) { using (var stream = ex.Response.GetResponseStream()) { using (var reader = new StreamReader(stream)) { data = reader.ReadToEnd(); } } } } } if (request != null) { request.Response = data; var ommit = false; foreach (var item in OmmitList) { if (request.Url.ToLower().Contains(item)) { ommit = true; break; } } if (EnableCaching) { if (request.ID == 0) { WebserviceRequestsMapper.Insert(request); } else { request = BaseMapper.GetObjectFromContext(request); WebserviceRequestsMapper.Update(request); } } } return(data); }
public static Return Send(string fromEmailAddress, IEnumerable <MailAddress> emailAddresses, string subject, string body, EmailMode emailMode = EmailMode.Both, bool bcc = true) { Return returnObj = new Return(); var emailLog = new EmailLog(); if (emailMode == EmailMode.Both || emailMode == EmailMode.Smtp) { try { MailMessage message = new MailMessage(); foreach (MailAddress address in emailAddresses) { if (bcc) { message.Bcc.Add(address); } else { message.To.Add(address); } } message.Sender = new MailAddress(fromEmailAddress); message.IsBodyHtml = true; message.Subject = subject; message.Body = body; emailLog = GetEmailLogFromMailMessage(message); System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(); client.Send(message); emailLog.ServerMessage = "Successfully sent email"; EmailsMapper.Insert(emailLog); return(returnObj); } catch (Exception ex) { ErrorHelper.LogException(ex); returnObj.Error = ErrorHelper.CreateError(ex); emailLog.ServerMessage = returnObj.Error.Message; EmailsMapper.Insert(emailLog); if (emailMode == EmailMode.Both) { var directSentReturn = SendDirectMessage(fromEmailAddress, emailAddresses, subject, body, bcc); if (directSentReturn.IsError) { return(directSentReturn); } else { returnObj = BaseMapper.GenerateReturn(); } } return(returnObj); } } else { return(SendDirectMessage(fromEmailAddress, emailAddresses, subject, body)); } }
private static Return SendDirectMessage(string fromEmailAddress, IEnumerable <MailAddress> emailAddresses, string subject, string body, bool bcc = true) { var returnObj = new Return(); var emailLog = new EmailLog(); Message message = new Message(); message.Subject = subject; message.From = new Address(fromEmailAddress); foreach (var mailAddress in emailAddresses) { if (bcc) { message.Bcc.Add(mailAddress.Address); } else { message.To.Add(mailAddress.Address); } } message.IsHtml = true; message.BodyHtml.Text = body; message.BodyText.Text = body; emailLog.FromEmailAddress = message.From.Email; emailLog.SenderName = message.Sender.Name; emailLog.SenderEmailAddress = message.Sender.Email; emailLog.Subject = message.Subject; emailLog.ToEmailAddresses = ""; emailLog.VisitorIP = ""; emailLog.RequestUrl = ""; emailLog.ServerMessage = ""; emailLog.Message = body; try { var mailMessage = new MailMessage(); mailMessage.CopyFrom(message); var returnStr = ActiveUp.Net.Mail.SmtpClient.DirectSend(message); if (!string.IsNullOrEmpty(returnStr)) { emailLog.ServerMessage = returnObj?.Error?.Message; if (emailLog.ServerMessage == null) { emailLog.ServerMessage = ""; } EmailsMapper.Insert(emailLog); } return(returnObj); } catch (Exception ex) { ErrorHelper.LogException(ex); returnObj.Error = ErrorHelper.CreateError(ex); emailLog.ServerMessage = returnObj?.Error?.Message; if (emailLog.ServerMessage == null) { emailLog.ServerMessage = ""; } EmailsMapper.Insert(emailLog); return(returnObj); } }
public static Return BackupDatabase() { Return returnObj = BaseMapper.GenerateReturn(); var databaseName = BaseMapper.GetDataModel().Database.Connection.Database; var sqlCommand = $@"BACKUP DATABASE {databaseName} TO DISK = '{DbBackupPath}{DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss-tt")}-{databaseName}.bak'"; try { var result = BaseMapper.GetDataModel(true).Database.ExecuteSqlCommand(transactionalBehavior: System.Data.Entity.TransactionalBehavior.DoNotEnsureTransaction, sql: sqlCommand); returnObj.SetRawData(result); return(returnObj); } catch (Exception ex) { ErrorHelper.LogException(ex); returnObj.Error = ErrorHelper.CreateError(ex); return(returnObj); } /*SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString); * string dbName = builder.InitialCatalog; * string backUpPath = URIHelper.BasePath + "App_Data/DBBackups/" + DateTime.Now.ToString("yyyy'-'MM'-'dd-HH'-'mm'-'ss'Z'") + "-" + dbName + ".bak"; * * using (SqlConnection cnn = new SqlConnection(connectionString)) * { * cnn.Open(); * dbName = cnn.Database.ToString(); * * ServerConnection sc = new ServerConnection(cnn); * Server sv = new Server(sc); * * // Create backup device item for the backup * BackupDeviceItem bdi = new BackupDeviceItem(backUpPath, DeviceType.File); * * // Create the backup informaton * Microsoft.SqlServer.Management.Smo.Backup bk = new Backup(); * * //bk.PercentComplete += new PercentCompleteEventHandler(percentComplete); * bk.Devices.Add(bdi); * bk.Action = BackupActionType.Database; * bk.PercentCompleteNotification = 1; * bk.BackupSetDescription = dbName; * bk.BackupSetName = dbName; * bk.Database = dbName; * * //bk.ExpirationDate = DateTime.Now.AddSeconds(10); * bk.LogTruncation = BackupTruncateLogType.Truncate; * bk.FormatMedia = false; * bk.Initialize = true; * bk.Checksum = true; * bk.ContinueAfterError = true; * bk.Incremental = false; * * try * { * // Run the backup * bk.SqlBackup(sv);//Exception * return returnObj; * } * catch (Exception ex) * { * ErrorHelper.LogException(ex); * * returnObj.Error = ErrorHelper.CreateError(ex); * * return returnObj; * } * }*/ }