protected void btnSubmit_Click(object sender, EventArgs e) { if (!User.Identity.IsAuthenticated) { if (tbxCode.Text == Session["CaptchaImageText"].ToString()) { Response.Redirect("Newsletter.aspx?add=" + tbxEmail.Text); } else { Session["CaptchaImageText"] = CaptchaImage.GenerateRandomCode(random); CustomValidator1.IsValid = false; } } else { string[] sEmails = tbxAddEmails.Text.Split(';'); SmtpMail.SmtpServer = "relay-hosting.secureserver.net"; MailMessage mm; foreach (string s in sEmails) { try { DataLayer.AddNewsletterEmail(s.Replace(" ", "")); } catch { DataLayer.CloseConn(); } } Response.Write("<h3>Emails added successfully.</h3><a href=\"Default.aspx\">(Click here to continue.)</a>"); Response.Flush(); Response.Close(); } }
private async Task <CaptchaResponse> Solve(CaptchaService service, CaptchaType captchaType) { var proxy = MakeProxy(Proxy, ProxyType); switch (captchaType) { case CaptchaType.TextCaptcha: var textOptions = new TextCaptchaOptions() { CaptchaLanguageGroup = CaptchaLanguageGroup, CaptchaLanguage = CaptchaLanguage }; return(await service.SolveTextCaptchaAsync(Text, textOptions)); case CaptchaType.ImageCaptcha: if (CaptchaImage == null) { throw new ArgumentNullException("You must download an image first!"); } var imageOptions = new ImageCaptchaOptions() { IsPhrase = IsPhrase, CaseSensitive = CaseSensitive, CharacterSet = CharacterSet, RequiresCalculation = RequiresCalculation, MinLength = int.Parse(MinLength), MaxLength = int.Parse(MaxLength), CaptchaLanguageGroup = CaptchaLanguageGroup, CaptchaLanguage = CaptchaLanguage, TextInstructions = TextInstructions }; return(await service.SolveImageCaptchaAsync(CaptchaImage.ToBase64(ImageFormat.Jpeg), imageOptions)); case CaptchaType.ReCaptchaV2: return(await service.SolveRecaptchaV2Async(SiteKey, SiteUrl, SData, Enterprise, Invisible, proxy)); case CaptchaType.ReCaptchaV3: return(await service.SolveRecaptchaV3Async(SiteKey, SiteUrl, Action, float.Parse(MinScore, CultureInfo.InvariantCulture), Enterprise, proxy)); case CaptchaType.FunCaptcha: return(await service.SolveFuncaptchaAsync(PublicKey, ServiceUrl, SiteUrl, NoJS, proxy)); case CaptchaType.HCaptcha: return(await service.SolveHCaptchaAsync(SiteKey, SiteUrl, proxy)); case CaptchaType.KeyCaptcha: return(await service.SolveKeyCaptchaAsync(UserId, SessionId, WebServerSign1, WebServerSign2, SiteUrl, proxy)); case CaptchaType.GeeTest: return(await service.SolveGeeTestAsync(GT, Challenge, ApiServer, SiteUrl, proxy)); case CaptchaType.Capy: return(await service.SolveCapyAsync(SiteKey, SiteUrl, proxy)); } throw new NotSupportedException($"Captcha type {captchaType} is not supported by the tester yet!"); }
public ActionResult GetCaptchaImage() { LoginCacheItem loginCacheItem = GetCachedLoginAttempt(false); if (loginCacheItem == null) { return(StatusCode(400)); } CaptchaImage ci = new CaptchaImage(loginCacheItem.CaptchaText, 240, 60, "Century Schoolbook"); try { // Write the image to the response stream in JPEG format. using (MemoryStream ms = new MemoryStream()) { ci.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); return(File(ms.ToArray(), "image/png")); } } catch (Exception err) { if (!err.Message.Contains("Specified method is not supported.")) { throw; } } finally { ci.Dispose(); } return(null); }
/// <summary> /// Validates the captcha. /// </summary> /// <param name="collection">The collection.</param> /// <param name="modelState">State of the model.</param> /// <param name="captchaKey">The captcha key.</param> /// <param name="captchaValue">The captcha value.</param> private static void ValidateCaptcha(FormCollection collection, ModelStateDictionary modelState, String captchaKey, String captchaValue) { bool isValid = true; // get the guid from form collection String guid = collection[CaptchaImage.CaptchaImageGuidKey]; // check for the guid because it is required from the rest of the opperation if (String.IsNullOrEmpty(guid)) { isValid = false; } else { // get values CaptchaImage image = CaptchaImage.GetCachedCaptcha(guid); String expectedValue = image == null ? String.Empty : image.Text; // removes the captch from cache so it cannot be used again HttpContext.Current.Cache.Remove(guid); // validate the captch if (String.IsNullOrEmpty(captchaValue) || String.IsNullOrEmpty(expectedValue) || !String.Equals(captchaValue, expectedValue, StringComparison.OrdinalIgnoreCase)) { isValid = false; } } if (!isValid) { modelState.AddModelError(captchaKey, @"The code you typed does not match the code the image."); } }
public string Genrate() { //System.Drawing.FontFamily family = new System.Drawing.FontFamily("Arial"); //CaptchaImage img = new CaptchaImage(150, 50, family); //string text = img.CreateRandomText(4) + " " + img.CreateRandomText(3); //_session["Captcha"] = text; //img.SetText(text); //img.GenerateImage(); //MemoryStream ms = new MemoryStream(); //img.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); //HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); //result.Content = new ByteArrayContent(ms.ToArray()); //result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); //return result; var family = new System.Drawing.FontFamily("Arial"); var img = new CaptchaImage(150, 50, family); //string text = img.CreateRandomText(4) + " " + img.CreateRandomText(3); var text = img.CreateRandomText(4); _session.Store("Captcha", text); img.SetText(text); img.GenerateImage(); var ms = new MemoryStream(); img.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); return(Convert.ToBase64String(ms.ToArray())); }
/// <summary> /// Called when [action executed]. /// </summary> /// <param name="filterContext">The filter filterContext.</param> public override void OnActionExecuting(ActionExecutingContext filterContext) { // make sure no values are getting sent in from the outside if (filterContext.ActionParameters.ContainsKey("captchaValid")) { filterContext.ActionParameters["captchaValid"] = null; } // get the guid from the post back string guid = filterContext.HttpContext.Request.Form["captcha-guid"]; // check for the guid because it is required from the rest of the opperation if (String.IsNullOrEmpty(guid)) { filterContext.RouteData.Values.Add("captchaValid", false); return; } // get values CaptchaImage image = CaptchaImage.GetCachedCaptcha(guid); string actualValue = filterContext.HttpContext.Request.Form[Field]; string expectedValue = image == null ? String.Empty : image.Text; // removes the captch from cache so it cannot be used again filterContext.HttpContext.Cache.Remove(guid); // validate the captch filterContext.ActionParameters["captchaValid"] = !String.IsNullOrEmpty(actualValue) && !String.IsNullOrEmpty(expectedValue) && String.Equals(actualValue, expectedValue, StringComparison.OrdinalIgnoreCase); }
protected void Page_Load(object sender, EventArgs e) { DataLayer dl = new DataLayer(); if (User.Identity.IsAuthenticated) { loggedinpanels.Controls.Add(new LiteralControl("<div style=\"width:250px;\" class=\"contenttitle\">Featured Member</div><div class=\"contentpanel\">")); DataTable dtRandomMember = dl.GetRandomMember(); loggedinpanels.Controls.Add(new LiteralControl("<table style=\"width:100%;\"><tr><td style=\"font-size:13px;text-align:center;\"><a href=\"Profile.aspx?member=" + dtRandomMember.Rows[0].ItemArray[0].ToString() + "\"><img style=\"border-width:0px;\" src=\"MakeThumbnail.aspx?size=100&image=images/MemberAvatars/" + dtRandomMember.Rows[0].ItemArray[3].ToString() + "\" /></a><br /><a href=\"Profile.aspx?member=" + dtRandomMember.Rows[0].ItemArray[0].ToString() + "\">View Profile</a></td><td style=\"padding-left:5px;font-size:13px;width:100%;\"><b>Name:</b> " + dtRandomMember.Rows[0].ItemArray[2].ToString() + "<br /><br /><b>Location:</b> " + dtRandomMember.Rows[0].ItemArray[17].ToString() + "<br /><br /><b>Business:</b> " + dtRandomMember.Rows[0].ItemArray[8].ToString() + "<br /><br />")); if (dtRandomMember.Rows[0].ItemArray[6].ToString() != "") { loggedinpanels.Controls.Add(new LiteralControl("<center><a href=\"" + dtRandomMember.Rows[0].ItemArray[6].ToString() + "\">Visit Website</a></center>")); } loggedinpanels.Controls.Add(new LiteralControl("</td></tr></table></div>")); } DataTable dtMemberAd = dl.GetRandomAd(); loggedinpanels.Controls.Add(new LiteralControl("<div class=\"contenttitle\">Member Ad</div><div style=\"text-align:center;\" class=\"contentpanel\"><a href=\"" + dtMemberAd.Rows[0].ItemArray[2].ToString() + "\"><img style=\"width:230px; border-width:0px;\" src=\"" + dtMemberAd.Rows[0].ItemArray[1].ToString() + "\" /></a></div>")); if (!this.IsPostBack) { Session["CaptchaImageText"] = CaptchaImage.GenerateRandomCode(random); } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Session["CaptchaImageText"] = CaptchaImage.GenerateRandomCode(random); } }
/// <summary> /// Generates the captcha image. /// </summary> /// <param name="helper">The helper.</param> /// <param name="height">The height.</param> /// <param name="width">The width.</param> /// <returns> /// Returns the <see cref="Uri"/> for the generated <see cref="CaptchaImage"/>. /// </returns> public static String CaptchaImage(this HtmlHelper helper, int height, int width) { var image = new CaptchaImage { Height = height, Width = width, }; HttpRuntime.Cache.Add( image.UniqueId, image, null, DateTime.Now.AddSeconds(Captcha.CaptchaImage.CacheTimeOut), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null); var stringBuilder = new StringBuilder(256); stringBuilder.Append("<input type=\"hidden\" name=\"captcha-guid\" value=\""); stringBuilder.Append(image.UniqueId); stringBuilder.Append("\" />"); stringBuilder.AppendLine(); stringBuilder.Append("<img src=\""); stringBuilder.Append(ApplicationUtility.Path + "captcha.ashx?guid=" + image.UniqueId); stringBuilder.Append("\" alt=\"CAPTCHA\" width=\""); stringBuilder.Append(width); stringBuilder.Append("\" height=\""); stringBuilder.Append(height); stringBuilder.Append("\" />"); return(stringBuilder.ToString()); }
public void ProcessRequest(HttpContext context) { int width = 200; int height = 30; try { width = Convert.ToInt32(context.Request.QueryString["w"]); height = Convert.ToInt32(context.Request.QueryString["h"]); } catch (Exception) { // Nothing } // 从 Session 中读取验证码,并创建图片 CaptchaImage ci = new CaptchaImage(context.Session["CaptchaImageText"].ToString(), width, height, "Consolas"); // 输出图片 context.Response.Clear(); context.Response.ContentType = "image/jpeg"; ci.Image.Save(context.Response.OutputStream, ImageFormat.Jpeg); ci.Dispose(); }
protected void btnAddComment_Click(object sender, EventArgs e) { if (Session["CaptchaImageText"].ToString() == tbxCode.Text) { if (tbxAddComment.Text.Length > 0) { DataLayer.AddComment(iBlogID, tbxUsername.Text, tbxAddComment.Text.Replace("\r", "<br />").Replace("\n", ""), DateTime.Now, tbxWebsite.Text); DataTable dtBlog = DataLayer.GetBlogsBy_blogID(iBlogID); SmtpMail.SmtpServer = "relay-hosting.secureserver.net"; MailMessage mm = new MailMessage(); mm.BodyFormat = MailFormat.Html; mm.To = "*****@*****.**"; mm.From = "*****@*****.**"; mm.Subject = "New Blog Comment"; mm.Body = tbxUsername.Text + " posted a comment on your blog titled: " + dtBlog.Rows[0].ItemArray[1].ToString() + "<br />Here it is below:<br /><br />"; mm.Body += tbxAddComment.Text.Replace("\r", "<br />").Replace("\n", ""); try { SmtpMail.Send(mm); } catch { } Response.Redirect("http://www.fordscleaning.com/Blog.aspx?blog=" + iBlogID.ToString()); } } else { cvCode.IsValid = false; Session["CaptchaImageText"] = CaptchaImage.GenerateRandomCode(random); } }
public ActionResult GetCaptchaImage(string fgcolor, string bgcolor, string ncolor) { Color f = ColorTranslator.FromHtml(CaptchaImage.FGColorDef); Color b = ColorTranslator.FromHtml(CaptchaImage.BGColorDef); Color n = ColorTranslator.FromHtml(CaptchaImage.NColorDef); Bitmap bmpCaptcha = CaptchaImage.GetCaptchaImage(f, b, n); if (bmpCaptcha == null) { Response.StatusCode = 404; Response.StatusDescription = "Not Found"; byte[] bb = new byte[0]; return(File(bb, "image/png")); } using (MemoryStream imgStream = new MemoryStream()) { bmpCaptcha.Save(imgStream, ImageFormat.Png); bmpCaptcha.Dispose(); Response.StatusCode = 200; Response.StatusDescription = "OK"; return(File(imgStream.ToArray(), "image/png")); } }
protected void Page_Load(object sender, EventArgs e) { string color = "000"; string moduleID = ""; if (Request.QueryString.AllKeys.Contains("moduleid")) { moduleID = Request.QueryString["moduleid"]; } if (Request.QueryString.AllKeys.Contains("color")) { color = Request.QueryString["color"]; } string availableCharters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0987654321"; int captchaLenght = 6; string captcha = ""; Random rand = new Random(); for (int i = 1; i <= captchaLenght; i++) { captcha += availableCharters[rand.Next(0, availableCharters.Length)]; } CaptchaImage captchaImage = new CaptchaImage(captcha, 300, 75, color); Response.Clear(); Response.ContentType = "image/jpeg"; // Write the image to the response stream in JPEG format. captchaImage.Image.Save(Response.OutputStream, ImageFormat.Jpeg); // Dispose of the CAPTCHA image object. captchaImage.Dispose(); Session["captcha_code_" + moduleID] = captcha; }
protected void SubmitReviewButton_Click(object sender, EventArgs e) { if (Page.IsValid) { //VALIDATE CAPTCHA if (ProductReviewHelper.ImageVerificationRequired(AbleContext.Current.User)) { if (CaptchaImage.Authenticate(CaptchaInput.Text)) { HandleSubmitedReview(); ReviewsRepeater.DataBind(); } else { CustomValidator invalidInput = new CustomValidator(); invalidInput.ID = Guid.NewGuid().ToString(); invalidInput.Text = "*"; invalidInput.ErrorMessage = "You did not input the number correctly."; invalidInput.IsValid = false; invalidInput.ValidationGroup = "ProductReviewForm"; phCaptchaValidators.Controls.Add(invalidInput); RefreshCaptcha(); } CaptchaInput.Text = string.Empty; } else { HandleSubmitedReview(); ReviewsRepeater.DataBind(); } } }
public static void NewCode(string vctype) { CaptchaImage validate = new CaptchaImage(12, 50); validate.strFont = "宋体"; validate.nFontSize = 13; MemoryStream stream = validate.GetCode(1, 4, 58, 22); Guid id; lock (CodeCache) { id = Guid.NewGuid(); CodeCache[id] = new CodeInf { Code = validate.strValidate, Time = DateTime.Now }; } var Response = System.Web.HttpContext.Current.Response; Response.Cookies.Add(new HttpCookie("vc_" + vctype, id.ToString()) { HttpOnly = true }); Response.ContentType = "image/jpeg"; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Clear(); Response.BinaryWrite(stream.ToArray()); Response.Flush(); Response.End(); }
protected void Submit_Click(object sender, EventArgs e) { if (EnableCaptcha) { if (CaptchaImage.Authenticate(CaptchaInput.Text)) { SubmitComment(); CaptchaInput.Text = ""; RefreshCaptcha(); } else { //CAPTCHA IS VISIBLE AND DID NOT AUTHENTICATE CustomValidator invalidInput = new CustomValidator(); invalidInput.Text = "*"; invalidInput.ErrorMessage = "You did not input the verification number correctly."; invalidInput.IsValid = false; phCaptchaValidators.Controls.Add(invalidInput); CaptchaInput.Text = ""; RefreshCaptcha(); } } else if (!EnableCaptcha) { SubmitComment(); } }
protected void Page_Load(object sender, EventArgs e) { string captcha = QueryHelper.GetString("captcha", ""); int width = QueryHelper.GetInteger("width", 80); if (width > MAXSIDESIZE) { width = MAXSIDESIZE; } int height = QueryHelper.GetInteger("height", 20); if (height > MAXSIDESIZE) { height = MAXSIDESIZE; } if (WindowHelper.GetItem("CaptchaImageText" + captcha) != null) { bool useWarp = QueryHelper.GetBoolean("useWarp", true); // Create a CAPTCHA image using the text stored in the Session object. CaptchaImage ci = new CaptchaImage(WindowHelper.GetItem("CaptchaImageText" + captcha).ToString(), width, height, null, useWarp); // Change the response headers to output a JPEG image. Response.Clear(); Response.ContentType = "image/jpeg"; Response.Cache.SetCacheability(HttpCacheability.NoCache); // Write the image to the response stream in JPEG format. ci.Image.Save(Response.OutputStream, ImageFormat.Jpeg); // Dispose of the CAPTCHA image object. ci.Dispose(); RequestHelper.EndResponse(); } }
public FileResult Captcha() { int Width = 200; int Height = 50; if (Request["w"] != null) { if (!int.TryParse(Request["w"], out Width)) { Width = 200; } } if (Request["h"] != null) { if (!int.TryParse(Request["h"], out Height)) { Height = 50; } } CaptchaImage ci = new CaptchaImage(Width, Height); ImageConverter converter = new ImageConverter(); var data = (byte[])converter.ConvertTo(ci.Image, typeof(byte[])); ci.Dispose(); return(File(data, "image/jpeg", "Captcha.jpeg")); }
public ActionResult GetCaptchaImage(string fgcolor, string bgcolor, string ncolor) { var context = System.Web.HttpContext.Current; context.Response.Cache.VaryByParams["fgcolor"] = true; context.Response.Cache.VaryByParams["bgcolor"] = true; context.Response.Cache.VaryByParams["ncolor"] = true; DoCacheMagic(context, 3); Color f = ColorTranslator.FromHtml(CaptchaImage.FGColorDef); Color b = ColorTranslator.FromHtml(CaptchaImage.BGColorDef); Color n = ColorTranslator.FromHtml(CaptchaImage.NColorDef); Bitmap bmpCaptcha = CaptchaImage.GetCaptchaImage(f, b, n); if (bmpCaptcha == null) { Response.StatusCode = 404; Response.StatusDescription = "Not Found"; byte[] bb = new byte[0]; return(File(bb, "image/png")); } bmpCaptcha.Save(stream, ImageFormat.Png); bmpCaptcha.Dispose(); return(File(stream.ToArray(), "image/png")); }
/// <summary> /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface. /// </summary> /// <param name="filterContext">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param> public void ProcessRequest(HttpContext context) { // get the unique GUID of the captcha; this must be passed in via the querystring string guid = context.Request.QueryString["guid"]; CaptchaImage ci = CaptchaImage.GetCachedCaptcha(guid); if (String.IsNullOrEmpty(guid) || ci == null) { context.Response.StatusCode = 404; context.Response.StatusDescription = "Not Found"; context.Response.End(); return; } // write the image to the HTTP output stream as an array of bytes using (Bitmap b = ci.RenderImage()) { b.Save(context.Response.OutputStream, ImageFormat.Gif); } context.Response.ContentType = "image/gif"; context.Response.StatusCode = 200; context.Response.StatusDescription = "OK"; context.Response.End(); }
/// <summary> /// The get response captcha. /// </summary> /// <param name="context"> /// The context. /// </param> public void GetResponseCaptcha([NotNull] HttpContext context) { #if (!DEBUG) try { #endif var captchaImage = new CaptchaImage( CaptchaHelper.GetCaptchaText(new HttpSessionStateWrapper(context.Session), context.Cache, true), 250, 50, "Century Schoolbook"); context.Response.Clear(); context.Response.ContentType = "image/jpeg"; captchaImage.Image.Save(context.Response.OutputStream, ImageFormat.Jpeg); #if (!DEBUG) } catch (Exception x) { this.Get <ILogger>().Log(this.Get <IUserDisplayName>().GetName(BoardContext.Current.CurrentUser), this, x); context.Response.Write( "Error: Resource has been moved or is unavailable. Please contact the forum admin."); } #endif }
private async void LoadCaptcha() { CaptchaImage.LoadText(text); await Task.Delay(200); CaptchaImage.LoadText(text); }
// GET: Captcha public ActionResult GetCaptcha() { var captcha = new CaptchaImage(); captcha.NoiseCount = 200; return(this.Captcha(captcha)); }
protected void SendEmailButton_Click(object sender, EventArgs e) { if (Page.IsValid) { if ((!trCaptchaImage.Visible) || CaptchaImage.Authenticate(CaptchaInput.Text)) { int productId = AbleCommerce.Code.PageHelper.GetProductId(); Product product = ProductDataSource.Load(productId); if (product != null) { int categoryId = AbleCommerce.Code.PageHelper.GetCategoryId(); Category category = CategoryDataSource.Load(categoryId); EmailTemplate template = EmailTemplateDataSource.Load(AbleContext.Current.Store.Settings.ProductTellAFriendEmailTemplateId); if (template != null) { //STRIP HTML Name.Text = StringHelper.StripHtml(Name.Text); FromEmail.Text = StringHelper.StripHtml(FromEmail.Text); FriendEmail.Text = StringHelper.StripHtml(FriendEmail.Text); // ADD PARAMETERS template.Parameters["store"] = AbleContext.Current.Store; template.Parameters["product"] = product; template.Parameters["category"] = category; template.Parameters["fromEmail"] = FromEmail.Text; template.Parameters["fromName"] = Name.Text; template.FromAddress = FromEmail.Text; template.ToAddress = FriendEmail.Text; template.Send(); FriendEmail.Text = string.Empty; SentMessage.Visible = true; CaptchaInput.Text = ""; CaptchaImage.ChallengeText = StringHelper.RandomNumber(6); } else { FailureMessage.Text = "Email template could not be loaded."; FailureMessage.Visible = true; } } else { FailureMessage.Text = "Product could not be identified."; FailureMessage.Visible = true; } } else { //CAPTCHA IS VISIBLE AND DID NOT AUTHENTICATE CustomValidator invalidInput = new CustomValidator(); invalidInput.ValidationGroup = "TellAFriend"; invalidInput.Text = "*"; invalidInput.ErrorMessage = "You did not input the verification number correctly."; invalidInput.IsValid = false; phCaptchaValidators.Controls.Add(invalidInput); CaptchaInput.Text = ""; CaptchaImage.ChallengeText = StringHelper.RandomNumber(6); } } }
public static void Main() { for (int i = 0; i < 1000; ++i) { var img = new CaptchaImage(); img.RenderImage().Save(".\\images\\" + img.Text + ".bmp"); } }
/// <summary> /// Enables processing of the result of an action method by a custom type that inherits from <see cref="T:System.Web.Mvc.ActionResult"/>. /// </summary> /// <param name="context">The context within which the result is executed.</param> public override void ExecuteResult(ControllerContext context) { CaptchaImage captchaImage = new CaptchaImage(_characters, Color.White, 175, 50); context.HttpContext.Response.ContentType = @"image/jpg"; context.HttpContext.Response.Expires = 0; captchaImage.Image.Save(context.HttpContext.Response.OutputStream, ImageFormat.Jpeg); }
public FileContentResult GetCaptcha() { string code = new Random(DateTime.Now.Millisecond).Next(1111, 9999).ToString(); Session["code"] = code; CaptchaImage captcha = new CaptchaImage(code, 110, 50); return(File(ToByteArray(captcha.Image, ImageFormat.Jpeg), "Jpeg")); }
public ActionResult Captcha() { var ci = new CaptchaImage(UserSettingsService.CaptchaText, 200, 50); var image = new MemoryStream(); ci.Image.Save(image, ImageFormat.Png); ci.Dispose(); image.Seek(0, SeekOrigin.Begin); return(File(image, @"image/png")); }
public IActionResult GetCaptchaImage() { var code = CaptchaImage.RandomString(4); var x = new CaptchaImage(code, 250, 100); HttpContext.Session.SetString("LoginCaptcha", code); var y = ImageToByte2(x.Image); return(File(y, "image/png")); }
public void ProcessRequest(HttpContext context) { string word = context.Request["l"]; CaptchaImage captchaImage = new CaptchaImage(word, Color.White, 175, 50); context.Response.ContentType = @"image/jpg"; context.Response.Expires = 0; captchaImage.Image.Save(context.Response.OutputStream, ImageFormat.Jpeg); }
public IActionResult ewcaptcha() { NoCache(); Session["CAPTCHA"] = Random(6); using (var captcha = new CaptchaImage(Session.GetString("CAPTCHA"), 200, 50, "Century Schoolbook")) { var ms = new System.IO.MemoryStream(); captcha.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); ms.Seek(0, System.IO.SeekOrigin.Begin); return(File(ms, "image/jpeg")); } }
protected void Page_Load(object sender, EventArgs e) { string _capchaCode = CaptchaImage.GenerateRandomCode(CaptchaType.AlphaNumeric, 4); Session["capcha"] = _capchaCode; var c = new CaptchaImage(_capchaCode, 100, 40, "Tahoma", Color.White, Color.Red); Response.ClearContent(); Response.ContentType = "image/jpeg"; var ms = new MemoryStream(); c.Image.Save(ms, ImageFormat.Jpeg); Response.OutputStream.Write(ms.ToArray(), 0, Convert.ToInt32(ms.Length)); ms.Close(); Response.End(); }
private void Page_Load(object sender, System.EventArgs e) { // Create a CAPTCHA image using the text stored in the Session object. CaptchaImage ci = new CaptchaImage(this.Session["CaptchaImageText"].ToString(), 100, 28, "Lê Bùi Sùng"); // Change the response headers to output a JPEG image. this.Response.Clear(); this.Response.ContentType = "image/jpeg"; // Write the image to the response stream in JPEG format. ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg); // Dispose of the CAPTCHA image object. ci.Dispose(); }
//В сессии создаем случайное число от 1111 до 9999. //Создаем в ci объект CatchaImage //Очищаем поток вывода //Задаем header для mime-типа этого http-ответа будет "image/jpeg" т.е. картинка формата jpeg. //Сохраняем bitmap в выходной поток с форматом ImageFormat.Jpeg //Освобождаем ресурсы Bitmap //Возвращаем null, так как основная информация уже передана в поток вывод public ActionResult Captcha() { Session[CaptchaImage.CaptchaValueKey] = new Random(DateTime.Now.Millisecond).Next(1111, 9999).ToString(CultureInfo.InvariantCulture); var ci = new CaptchaImage(Session[CaptchaImage.CaptchaValueKey].ToString(), 211, 50, "Helvetica"); // Change the response headers to output a JPEG image. this.Response.Clear(); this.Response.ContentType = "image/jpeg"; // Write the image to the response stream in JPEG format. ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg); // Dispose of the CAPTCHA image object. ci.Dispose(); return null; }
public void ProcessRequest(HttpContext context) { HttpApplication App = context.ApplicationInstance; HttpContext.Current.Session["CaptchaImageText"] = GenerateRandomCode(); CaptchaImage ci = new CaptchaImage(HttpContext.Current.Session["CaptchaImageText"].ToString(), 200, 50, "Century Schoolbook"); // Change the response headers to output a JPEG image. App.Context.Response.Clear(); App.Context.Response.ContentType = "image/jpeg"; // Write the image to the response stream in JPEG format. ci.Image.Save(App.Context.Response.OutputStream, ImageFormat.Jpeg); // Dispose of the CAPTCHA image object. ci.Dispose(); App.Response.StatusCode = 200; context.ApplicationInstance.CompleteRequest(); }
private void Page_Load(object sender, System.EventArgs e) { general = General.Instance; // Create a CAPTCHA image using the text stored in the Session object. CaptchaImage ci = new CaptchaImage(HttpContext.Current.Session["CaptchaImageText"].ToString(), 200, 50, "Century Schoolbook"); // CaptchaImage ci = new CaptchaImage(general.CaptchaImageText, 200, 50, "Century Schoolbook"); // Change the response headers to output a JPEG image. Response.Clear(); Response.ContentType = "image/jpeg"; // Write the image to the response stream in JPEG format. ci.Image.Save(Response.OutputStream, ImageFormat.Jpeg); // Dispose of the CAPTCHA image object. ci.Dispose(); }
protected void Button1_Click(object sender, EventArgs e) { if (CaptchaCode == txt_ccode.Text) { SmtpClient smtpClient = new SmtpClient(); MailMessage message = new MailMessage(); try { MailAddress fromAddress = new MailAddress(txtKontakt.Text, txtImePrezime.Text); smtpClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "sokac237"); smtpClient.Port = 587; smtpClient.Host = "smtp.gmail.com"; smtpClient.EnableSsl = true; // You can specify the host name or ipaddress of your server // Default in IIS will be localhost //From address will be given as a MailAddress Object message.From = fromAddress; // To address collection of MailAddress message.To.Add("*****@*****.**"); message.Subject = txtNaslov.Text; //Body can be Html or text format //Specify true if it is html message message.IsBodyHtml = false; // Message body content message.Body = txtTekst.Text + Environment.NewLine + "Kontakt: " + txtKontakt.Text; // Send SMTP mail smtpClient.Send(message); lblStatus.Text = "Poruka je uspješno poslana!"; if (lblStatus.Text == "Poruka je uspješno poslana!") { txtImePrezime.Text = ""; txt_ccode.Text = ""; txtKontakt.Text = ""; txtNaslov.Text = ""; txtTekst.Text = ""; txtImePrezime.Focus(); } } catch (Exception) { lblStatus.Text = "Dogodila se greška. Poruka nije poslan.<br>Neispravna forma e-mail adrese!"; } } else { ClientScript.RegisterClientScriptBlock(typeof(Page), "ValidateMsg", "<script>alert('Upisali ste netočne znakove!');</script>"); CaptchaImage cImage = new CaptchaImage(CaptchaImage.generateRandomCode(), 160, 50); cImage.Image.Save(Server.MapPath("~\\CaptchaImages\\" + Convert.ToString(Session["CaptchaCode"]) + ".jpg"), ImageFormat.Jpeg); CaptachaImage.ImageUrl = "~\\CaptchaImages\\" + Convert.ToString(Session["CaptchaCode"]) + ".jpg"; cImage.Dispose(); txt_ccode.Text = ""; txt_ccode.Focus(); } }
public CaptchaController() { CaptchaImage = new CaptchaImage(); }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BindData(); CaptchaImage cImage = new CaptchaImage(CaptchaImage.generateRandomCode(), 160, 50); cImage.Image.Save(Server.MapPath("~\\CaptchaImages\\" + Convert.ToString(Session["CaptchaCode"]) + ".jpg"), ImageFormat.Jpeg); CaptachaImage.ImageUrl = "~\\CaptchaImages\\" + Convert.ToString(Session["CaptchaCode"]) + ".jpg"; cImage.Dispose(); } CaptchaCode = Convert.ToString(Session["CaptchaCode"]); }
protected void btn_Validate(object sender, EventArgs e) { if (CaptchaCode == txt_ccode.Text) { if (txtImePrezime.Text != "" && txtUlica.Text != "" && txtBroj.Text != "" && txtTelefon.Text != "") { try { odrediBroj(); PokupiPodatkeDokument(); for (brojac = 0; brojac < GridView1.Rows.Count; brojac++) { PokupiStavke(); } ShoppingCart cart = ShoppingCart.GetShoppingCart(); cart.ClearItems(); Response.Redirect("Odjava.aspx?value=" + brojNarudzbe + ""); Alert.Show("Vaša narudžba je zaprimljena! \r\n Uskoro će vas kontaktirati operater radi potvrde narudžbe. \r\n Kontrolni broj Vaše narudžbe je " + brojNarudzbe + " \r\n Hvala na Vašoj kupnji."); } catch (Exception ex) { Alert.Show(ex.Message); } } else { Alert.Show("Morate popuniti sva polja sa oznakom *"); } } else { ClientScript.RegisterClientScriptBlock(typeof(Page), "ValidateMsg", "<script>alert('Upisali ste netočne znakove!');</script>"); CaptchaImage cImage = new CaptchaImage(CaptchaImage.generateRandomCode(), 160, 50); cImage.Image.Save(Server.MapPath("~\\CaptchaImages\\" + Convert.ToString(Session["CaptchaCode"]) + ".jpg"), ImageFormat.Jpeg); CaptachaImage.ImageUrl = "~\\CaptchaImages\\" + Convert.ToString(Session["CaptchaCode"]) + ".jpg"; cImage.Dispose(); txt_ccode.Text = ""; txt_ccode.Focus(); } }