void RegUserAction(string url) { string tsql = @" INSERT INTO [CMSStatsUserDownloads] ([UserRegisterID] ,[UserEmail] ,[DownloadDate] ,[URL] ,[PageType] ,[Category] ,[SubCategory] ,[Title]) SELECT TOP 1 UserRegisterID ,@Email ,GETDATE() ,@URL ,@PageType ,@Category ,@SubCategory ,@Title FROM [CMSUserRegister] WHERE Email = @Email ORDER BY [UserRegisterID] DESC ;"; SqlParameter[] parameters = { new SqlParameter { ParameterName = "Email", DbType = DbType.AnsiString, Size = 50, Value = userEmail } , new SqlParameter{ ParameterName = "URL", DbType = DbType.AnsiString, Size = 400, Value = url } , new SqlParameter{ ParameterName = "PageType", DbType = DbType.AnsiString, Size = 60, Value = "RECURSO" } , new SqlParameter{ ParameterName = "Category", DbType = DbType.AnsiString, Size = 60, Value = PageCategory } , new SqlParameter{ ParameterName = "SubCategory", DbType = DbType.AnsiString, Size = 60, Value = PageSubCategory } , new SqlParameter{ ParameterName = "Title", DbType = DbType.AnsiString, Size = 60, Value = PageTitle } }; try { Dalayer.DAL.SqlApiSqlClient.ExecuteSqlString(tsql, parameters, Global.Configuration.DB.GetConnectionStringDBMain(), 30); } catch (Exception ex) { Global.LogError(this.Context, Global.EnumLogCategories.DATABASE, ex.Message); } }
private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e) { // Get the unique identifier for this asynchronous operation. string token = (string)e.UserState; //string token = e.UserState.ToString(); if (e.Cancelled) { // Console.WriteLine( "[{0}] Send canceled.", token ); } if (e.Error != null) { // Console.WriteLine( "[{0}] {1}", token, e.Error.ToString() ); Global.LogError(HttpContext.Current, EnumLogCategories.EMAIL, "Error sending email: " + token + " " + e.Error); } else { // Console.WriteLine( "Message sent." ); Global.LogDebug(HttpContext.Current, EnumLogCategories.EMAIL, "Email Send " + token); } // mailSent = true; }
// http://stackoverflow.com/questions/7276375/what-are-best-practices-for-using-smtpclient-sendasync-and-dispose-under-net-4/7276819#7276819 /// <summary> /// Call using: /// using System.Threading.Tasks; /// var t = Task.Run( () => Global.Utils.Emails.SendEmailAsync( "*****@*****.**", asunto, "enviado desde helpdesk", false ) ); /// t.Wait(); /// </summary> /// <param name="toEmailAddress"></param> /// <param name="emailSubject"></param> /// <param name="emailMessage"></param> /// <param name="isBodyHtml"></param> /// <returns></returns> public static async Task SendEmailAsync(string[] to, string from, string[] CC, string[] BCC, string emailSubject, string emailMessage, bool isBodyHtml) { var message = new MailMessage(); //message.To.Add( toEmailAddress ); // from? message.From = new MailAddress(from); // to? if (to != null) { foreach (string s in to) { if (s != null) { message.To.Add(s); } } } // CC? if (CC != null) { foreach (string s in CC) { if (s != null) { message.To.Add(s); } } } // BCC? if (BCC != null) { foreach (string s in BCC) { if (s != null) { message.To.Add(s); } } } message.Subject = emailSubject; message.Body = emailMessage; message.IsBodyHtml = isBodyHtml; message.From = new MailAddress(Configuration.Mail.GetMailServerLogin()); //Proper Authentication Details need to be passed when sending email from gmail NetworkCredential mailAuthentication = new NetworkCredential(Configuration.Mail.GetMailServerLogin(), Configuration.Mail.GetMailServerPassword()); using (var smtpClient = new SmtpClient()) { // server smtpClient.Host = Configuration.Mail.GetMailServer(); smtpClient.Port = Configuration.Mail.GetMailServerPort(); smtpClient.EnableSsl = Configuration.Mail.GetMailServerIsEnableSSL(); smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = mailAuthentication; if (Global.Configuration.Development.GetIsEnabledDeveloperMode()) { smtpClient.Timeout = 5000; } else { smtpClient.Timeout = 180000; //An Int32 that specifies the time-out value in milliseconds. The default value is 100,000 (100 seconds). } // Set the method that is called back when the send operation ends. // smtpClient.SendCompleted += new SendCompletedEventHandler( SendCompletedCallback ); // The userState can be any object that allows your callback // method to identify this send operation. // For this example, the userToken is a string constant. string userState = emailSubject.Replace(" ", "") + "_" + DateTime.Now.Ticks.ToString(); // send try { await smtpClient.SendMailAsync(message); // smtpClient.Send( message ); // only works with this... // smtpClient.SendAsync( message, userState ); } catch (Exception e) { Global.LogError(HttpContext.Current, EnumLogCategories.EMAIL, e.Message + Environment.NewLine + e.InnerException); } } }
protected void BootstrapButtonSend_Click(object sender, EventArgs e) { Page.Validate(); if (!Page.IsValid) { return; } if (string.IsNullOrEmpty(recaptcha.Value)) { Msg.Visible = true; Msg.InnerHtml = "Error en los datos de seguridad, vuelva a recargar la página."; return; } var Recaptchav3 = new RecaptchaVerificationHelper(); // If your site is behind CloudFlare, be sure you're suing the CF-Connecting-IP header value instead: // https://support.cloudflare.com/hc/en-us/articles/200170986-How-does-Cloudflare-handle-HTTP-Request-headers RecaptchaVerificationResult recaptchaResult = Recaptchav3.VerifyRecaptchav3Response( Global.Configuration.Security.Google.Recaptcha.v3.GetGoogleRecaptchaSecretKey() , Global.Configuration.Security.Google.Recaptcha.v3.GetGoogleRecaptchaWebsiteKey() , Request.UserHostAddress , recaptcha.Value ); if (recaptchaResult == RecaptchaVerificationResult.Success) { //divMessage.InnerHtml = "Score: " + Recaptchav3.Score; decimal?minScore = new decimal(0.6); if (Recaptchav3.Score < minScore) { Response.Redirect("~/Captcha.aspx", true); } // // format msg... // // IMPORANT: Your smtp login email MUST be same as your FROM address. string[] to = { Global.Configuration.Mail.GetEmailContacto() }; string from = Global.Configuration.Mail.GetMailServerLogin(); //string[] CC; //string[] BCC; string domainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority); string emailSubject = "Formulario de Contacto Sitio Web " + domainName; bool isBodyHtml = false; string emailMessage = @" ---------------------------------------- - FORMULARIO PROBLEMAS AL PESAR ---------------------------------------- Nombre: " + Names.Text + Environment.NewLine + @" Apellido: " + LastName.Text + Environment.NewLine + @" Movil: " + Mobile.Text + Environment.NewLine + @" Email: " + Email.Text + Environment.NewLine + @" Cargo: " + Position.Text + Environment.NewLine + @" Empresa: " + Business.Text + Environment.NewLine + @" Ciudad: " + City.Text + Environment.NewLine + @" Telefono: " + Telephone.Text + Environment.NewLine + @" Inconveniente: " + Incident.SelectedItem.Value + Environment.NewLine + @" Balanza: " + Balanza.Text + Environment.NewLine + @" Capacidad: " + Capacidad.Text + Environment.NewLine + @" Mensaje: " + Environment.NewLine + Notes.Text + Environment.NewLine + @" -------------------------------------- "; //var t = Task.Run( () => Global.Emails.SendEmailAsync(to, from, null, null, emailSubject, emailMessage, isBodyHtml) ); //t.Wait(); System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage() { From = new MailAddress(from, from, System.Text.Encoding.UTF8), Subject = emailSubject, SubjectEncoding = System.Text.Encoding.UTF8, Body = emailMessage, BodyEncoding = System.Text.Encoding.UTF8, IsBodyHtml = isBodyHtml, Priority = MailPriority.Normal }; mail.To.Add(to[0]); string msg; SmtpClient client = new SmtpClient { Credentials = new System.Net.NetworkCredential(Global.Configuration.Mail.GetMailServerLogin(), Global.Configuration.Mail.GetMailServerPassword()), Port = Global.Configuration.Mail.GetMailServerPort(), Host = Global.Configuration.Mail.GetMailServer(), EnableSsl = Global.Configuration.Mail.GetMailServerIsEnableSSL() }; try { client.Send(mail); msg = "Gracias, mensaje enviado..."; ClientScript.RegisterStartupScript(this.GetType(), "UserMsg", "alert('" + msg + "');", true); Msg.Visible = true; Msg.InnerHtml = msg; } catch (Exception ex) { Global.LogError(this.Context, Global.EnumLogCategories.EMAIL, ex.Message); msg = "Lo sentimos, su mensaje no pudo ser enviado, intente mas tarde..."; ClientScript.RegisterStartupScript(this.GetType(), "UserMsg", "alert('" + msg + "');", true); Msg.Visible = true; Msg.InnerHtml = msg; } } else { Msg.Visible = true; Msg.InnerHtml = "Existe un problema para validar la seguridad, intente mas tarde o por favor contacte a soporte técnico."; return; } }
private void Application_Error(object sender, EventArgs e) { //https://msdn.microsoft.com/en-us/library/24395wz3.aspx HttpServerUtility server = HttpContext.Current.Server; Exception exception = server.GetLastError(); string currentPageRequest = HttpContext.Current.Request.FilePath; if (Configuration.Development.GetIsEnabledDebugDeveloperModeShowGlobalPageError()) { if (exception.GetType() == typeof(HttpException)) { Server.Transfer("~/ErrorPageHttp.aspx"); } else { Response.Write("<h2>Global Page Error</h2>\n"); Response.Write( "<p>" + exception.Message + "</p>\n"); Response.Write("Return to the <a href='/Default.aspx'>" + "Default Page</a>\n"); if (Context.Request.IsLocal) { Response.Write("<p>" + exception.Source + "</p>\n"); Response.Write("<p>" + exception.InnerException + "</p>\n"); Response.Write("<p>" + exception.StackTrace + "</p>\n"); } } if (!_previousPageError.Equals(currentPageRequest)) { ExceptionUtility.LogException(exception, currentPageRequest); ExceptionUtility.NotifySystemOps(exception); } } // if not in DEV MODE, write error to .txt if (!Configuration.Development.GetIsEnabledDeveloperMode()) { // devexpress callback error // Use HttpContext.Current to get a Web request processing helper // is http? if (exception is HttpUnhandledException) { HttpException ex = (HttpException)Server.GetLastError(); //Exception innerexception = exception.InnerException; // Log an exception // TODO, send email to admin. if (!_previousPageError.Equals(currentPageRequest)) { ExceptionUtility.LogException(exception, currentPageRequest); ExceptionUtility.NotifySystemOps(exception); // log to logger if (HttpContext.Current != null && HttpContext.Current.Request != null) { Global.LogError(Context, Global.EnumLogCategories.GENERAL, "HTTP " + ex.GetHttpCode() + ": " + Request.RawUrl.ToString(), ex); } } // options to show info to user: // 1. show a blank page: //Server.ClearError(); // 2. redirect to a page // Response.Redirect("~/Errors/ErrorPageHttp.aspx"); // 3. do nothing, go to customErrors configuration in web.config and/or show asp.net error } else { // other NO http errors ExceptionUtility.LogException(exception, currentPageRequest); ExceptionUtility.NotifySystemOps(exception); // log to logger if (HttpContext.Current != null && HttpContext.Current.Request != null) { Global.LogError(Context, Global.EnumLogCategories.GENERAL, "Error " + exception.HResult + ": " + Request.RawUrl.ToString(), exception); } } } else { ExceptionUtility.LogException(exception, currentPageRequest); ExceptionUtility.NotifySystemOps(exception); // log to logger, no works in callback mode /* * if (HttpContext.Current != null && HttpContext.Current.Request != null) * Global.LogError( Context, Global.EnumLogCategories.GENERAL, * "Error " + exception.HResult + ": " + Request.RawUrl.ToString(), * exception ); */ ExceptionUtility.LogException(exception, currentPageRequest); ExceptionUtility.NotifySystemOps(exception); } //_previousException = exception; _previousPageError = currentPageRequest; }