Yasserzaid’s Weblog

January 31, 2009

Add Text To Uploaded Image

Filed under: ASP.Net — yasserzaid @ 10:07 pm

Hi

try this example:

First :- create a web form and add Fileupload and Button controls

Secod: in code behind

private Bitmap yaz(System.Drawing.Image resim, int width, int hieght, string name, float font)
    {
        Bitmap resmim = new Bitmap(resim, width, hieght);
        System.Drawing.Graphics graf = System.Drawing.Graphics.FromImage(resmim);
        System.Drawing.SolidBrush firca = new SolidBrush(System.Drawing.Color.Red);
        System.Drawing.Font fnt = new Font("calibri", font);//font type
        System.Drawing.SizeF size = new SizeF(0, 0);
        System.Drawing.PointF coor = new PointF(0, 0);
        System.Drawing.RectangleF kutu = new RectangleF(coor, size);
        StringFormat sf = new StringFormat();
        sf.FormatFlags = StringFormatFlags.DirectionVertical;
        graf.DrawString(name, fnt, firca, kutu, sf);
        return resmim;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        System.Drawing.Image i = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
        Bitmap b = yaz(i, i.Width, i.Height, "Yasser Zaid", 16); //
        b.Save(Server.MapPath("~/Ads/" + FileUpload1.FileName));
    }

Hope this helps

Good Luck

Regular Expression for email address validation

Filed under: ASP.Net — yasserzaid @ 1:06 pm

Hi

use this regular expression for email address validation

^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$

Hope this helps

Good Luck

January 29, 2009

Change TextBox Color if Empty

Filed under: ASP.Net — yasserzaid @ 8:01 pm

This is example of how to create Textbox user control that when textbox is empty
will change it’s background to red else change background to white

Create MyTextBox  control:  MyTextBox.ascx

 <%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyTextBox.ascx.cs" Inherits="WebUserControl" %>
<asp:TextBox ID="txtText" runat="server"/>
<asp:CustomValidator id="valCustom" runat="server"
    ControlToValidate="txtText"
    ClientValidationFunction="MyTextBox_ClientValidate" Display="None" ></asp:CustomValidator>

and in code behind :

 using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Text;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class WebUserControl : System.Web.UI.UserControl
{

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        StringBuilder script = new StringBuilder();
        script.AppendLine("<script type='text/javascript' language='javascript'>");
        script.AppendLine("   function MyTextBox_ClientValidate(source, arguments){");
        script.AppendLine("   var textBox = document.getElementById(source.controltovalidate);");
        script.AppendLine("   if (arguments.Value != \"\"){");
        script.AppendLine("      arguments.IsValid = true;");
        script.AppendLine("      textBox.style.background = \"white\";");
        script.AppendLine("   }else{");
        script.AppendLine("      arguments.IsValid = false;");
        script.AppendLine("      textBox.style.background = \"red\";");
        script.AppendLine("   }");
        script.AppendLine("}\n");

        // OVERRIDE THE NORMAL VALIDATOR FRAMEWORK
        script.AppendLine("function CustomValidatorEvaluateIsValid(val){");
        script.AppendLine("   var value = \"\";");
        script.AppendLine("   if (typeof(val.controltovalidate) == \"string\") {");
        script.AppendLine("      value = ValidatorGetValue(val.controltovalidate);");
        script.AppendLine("   }");
        script.AppendLine("   var args = { Value:value, IsValid:true };");
        script.AppendLine("   if (typeof(val.clientvalidationfunction) == \"string\") {");
        script.AppendLine("      eval(val.clientvalidationfunction + \"(val, args)\");");
        script.AppendLine("   }");
        script.AppendLine("   return args.IsValid;");
        script.AppendLine("}");
        script.AppendLine("</script>");
        this.Page.RegisterStartupScript("TextClientValidate", script.ToString());
    }   
}

Hope this helps

Good Luck

Remooving a scrolbar from a Textbox

Filed under: ASP.Net, CSS — yasserzaid @ 7:57 pm

Hi

try this example:

<asp:TextBox ID="BigTextBox"  runat="server" Style="white-space: pre; overflow: hidden;" Height="401px" TextMode="MultiLine" Width="484px" />

//——or this

<style>.text{overflow: hidden;}</style>

<asp:TextBox ID="BigTextBox" runat="server" Style="white-space: pre;" Height="401px" TextMode="MultiLine" Width="484px"  CssClass="text"/>

Good Luck

Validate at Least one of two TextBoxes

Filed under: ASP.Net — Tags: — yasserzaid @ 7:54 pm

Hi

try this example:

** using Client Side:

<script type="text/javascript">
function AtLeastOneContact_ClientValidate(source, args)
{
if (document.getElementById("<%= Phone.ClientID %>").value =="" &&
document.getElementById("<%= Email.ClientID %>").value == "" )
{
args.IsValid = false;
}
else
{
args.IsValid = true;   
}
}

</script>
<b>Phone: </b><asp:TextBox id="Phone" runat="server"></asp:TextBox><br />
<b>Email: </b><asp:TextBox id="Email" runat="server"></asp:TextBox>
<asp:Button id="Submit" Text="Submit" runat="server" /><br />

<%-- AtLeastOneContact Custom Validator --%>
<asp:CustomValidator id="AtLeastOneContact" runat="server" 
  ErrorMessage="Phone or Email Required"
  Display="Dynamic"
  OnServerValidate="AtLeastOneContact_ServerValidate"
  ClientValidationFunction="AtLeastOneContact_ClientValidate" />

in code behind :

** using server side

protected void AtLeastOneContact_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (Phone.Text!="" && Email.Text != "")
            args.IsValid = true;
        else
        {
            args.IsValid = false;
        }
    }

Good Luck

Make TextBox Accept only Decimal

Filed under: ASP.Net — yasserzaid @ 7:51 pm

Hi

try this example:

Javascript function

// function to make the textboxes accept only decimals
    function decimalOnly(evt)
    {
        evt = (evt) ? evt : event;
        var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
        if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode!= 46)
        {
            return false;
        }
        return true;
    }

and in code behind in Page Load:

TextBox1.Attributes.Add("onkeypress", "return decimalOnly(event)");

Good Luck

Make TextBox accept Number only

Filed under: ASP.Net — yasserzaid @ 6:56 pm

Hi

try thes example to Make TextBox accept Number only

Example 1:

Use this Javascript function

//-- allow textbox to accept numbers only
    function numeralsOnly(evt)
    {
        evt = (evt) ? evt : event;
        var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
        if (charCode > 31 && (charCode < 48 || charCode > 57))
        {
            //alert("Enter numerals only in this field.");
            return false;
        }
        return true;
    }

and in code behind in Page Load:

TextBox1.Attributes.Add("onkeypress", "return numeralsOnly(event)");

Example 2:

using  RegularExpressionValidator control

<asp:RegularExpressionValidator ValidationGroup="reg" ID="RegularExpressionValidator2" ControlToValidate="txtMobile"
runat="server" ErrorMessage="Invalid Mobile No" ValidationExpression="^[0-9]*$">*</asp:RegularExpressionValidator>

Good Luck

Create Rss using Generic Handler

Filed under: ASP.Net — Tags: — yasserzaid @ 6:19 pm

Hi

try this Example :

<%@ WebHandler Language="C#" Class="FeedRss" %>

using System;
using System.Text;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Configuration;
public class FeedRss : IHttpHandler
{

public void ProcessRequest (HttpContext context)
{
//context.Response.ContentType = "text/plain";
context.Response.Clear();
context.Response.ContentType = "text/xml";
XmlTextWriter rssfeed = new XmlTextWriter(context.Response.OutputStream,Encoding.UTF8);
rssfeed.WriteStartDocument();
// The mandatory rss tag
rssfeed.WriteStartElement("rss");
rssfeed.WriteAttributeString("version", "2.0");
// The channel tag contains RSS feed details
rssfeed.WriteStartElement("channel");
rssfeed.WriteElementString("title", "News");
rssfeed.WriteElementString("link", "<a href="http://www.yourwebsite.com">http://www.yourwebsite.com</a>");
rssfeed.WriteElementString("description", "The latest news");
rssfeed.WriteElementString("copyright", "All rights reserved.-Created by Suresh");
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString());
SqlCommand cmd = new SqlCommand("select * from news", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{

rssfeed.WriteStartElement("item");
rssfeed.WriteElementString("title", dr["Title"].ToString());
rssfeed.WriteElementString("description", sdr["Description"].ToString());
rssfeed.WriteElementString("link", "http://localhost:4329/News_Details.aspx?Id=" + dr["articleid"]);
rssfeed.WriteElementString("category", dr["category"].ToString());
rssfeed.WriteElementString("pubDate", dr["pubdate"].ToString());
rssfeed.WriteElementString("ttl", dr["ttl"].ToString());
rssfeed.WriteEndElement();
}
sdr.Close();
con.Close();
rssfeed.WriteEndElement();
rssfeed.WriteEndElement();
rssfeed.WriteEndDocument();
rssfeed.Flush();
rssfeed.Close();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}

Good Luck

Application Level Error Handling with HttpModule

Filed under: ASP.Net — yasserzaid @ 7:49 am

Hi !

Some of ASP.NET Developers I saw use the Global.asax file in order to Handle Application Level Errors… It’s a pretty simple way, yes. But .. HttpModules might be a better way to Handle HttpRequests.

So here is the way to Handle Application Level Error with an HttpModule


public</span> <span class="kwrd">class</span> ApplicationLevelErrorHttpModule : IHttpModule
{
    <span class="preproc">#region</span> IHttpModule Members

    <span class="kwrd">public</span> <span class="kwrd">void</span> Dispose()
    {
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Init(HttpApplication context)
    {
        context.Error += <span class="kwrd">new</span> EventHandler(context_Error);
    }

    <span class="kwrd">void</span> context_Error(<span class="kwrd">object</span> sender, EventArgs e)
    {
        HttpApplication Application = sender <span class="kwrd">as</span> HttpApplication;
        Application.Context.Response.Redirect(<span class="str">"~/Error.aspx"</span>);
    }

    <span class="preproc">#endregion</span>
}

Web.config HttpModules Section


<</span><span class="html">httpModules</span><span class="kwrd">></span>
  <span class="kwrd"><</span><span class="html">add</span> <span class="attr">name</span><span class="kwrd">="ApplicationLevelError"</span> <span class="attr">type</span><span class="kwrd">="ApplicationErrorModule.ApplicationLevelErrorHttpModule"</span><span class="kwrd">/></span>
<span class="kwrd"></</span><span class="html">httpModules</span><span class="kwrd">>

Hope this Helps

Good Luck

Custom TextBox Required Field Validator

Filed under: ASP.Net — yasserzaid @ 7:45 am

Here is the Custom TextBox Required Field Validator Code

[DefaultProperty("Text")]
[ToolboxData("<{0}:TextBoxRequiredFieldValidator runat=server></{0}:TextBoxRequiredFieldValidator>")]
public class TextBoxRequiredFieldValidator : RequiredFieldValidator
{
    #region Public Properties

    public Color ErrorBackgroundColor
    {
        get
        {
            if (ViewState["ErrorBackgroundColor"] == null)
                return Color.LightGray;
            else
                return (Color)ViewState["ErrorBackgroundColor"];
        }
        set
        {
            ViewState["ErrorBackgroundColor"] = value;
        }
    }
    public Color ErrorBorderColor
    {
        get
        {
            if (ViewState["ErrorBorderColor"] == null)
                return Color.Red;
            else
                return (Color)ViewState["ErrorBorderColor"];
        }
        set
        {
            ViewState["ErrorBorderColor"] = value;
        }
    }

    #endregion

    #region Private Properties

    private Color OriginalBackgroundColor
    {
        get
        {
            if (ViewState["OriginalBackgroundColor"] == null)
                return Color.LightGray;
            else
                return (Color)ViewState["OriginalBackgroundColor"];
        }
        set
        {
            ViewState["OriginalBackgroundColor"] = value;
        }
    }
    private Color OriginalBorderColor
    {
        get
        {
            if (ViewState["OriginalBorderColor"] == null)
                return Color.Red;
            else
                return (Color)ViewState["OriginalBorderColor"];
        }
        set
        {
            ViewState["OriginalBorderColor"] = value;
        }
    }
    private TextBox TextBoxToValidate { get; set; }

    #endregion

    #region Protected Overrides Methods

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        TextBox txt = this.FindControl(base.ControlToValidate) as TextBox;
        if (txt != null)
        {
            TextBoxToValidate = txt;

            OriginalBackgroundColor = TextBoxToValidate.BackColor;
            OriginalBorderColor = TextBoxToValidate.BorderColor;
        }
    }
    protected override bool EvaluateIsValid()
    {
        Boolean bIsValid = false;
        String Value = base.GetControlValidationValue(base.ControlToValidate);
        if (String.IsNullOrEmpty(Value))
        {
            if (TextBoxToValidate != null)
            {
                TextBoxToValidate.BackColor = ErrorBackgroundColor;
                TextBoxToValidate.BorderColor = ErrorBorderColor;
                bIsValid = false;
            }
        }
        else
        {
            if (TextBoxToValidate != null)
            {
                TextBoxToValidate.BackColor = OriginalBackgroundColor;
                TextBoxToValidate.BorderColor = OriginalBorderColor;
                bIsValid = true;
            }
        }
        return bIsValid;
    }
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        if (Page.ClientScript.IsClientScriptBlockRegistered("ValidationScript"))
            return;

        String ControlToValidateClientId = base.GetControlRenderID(base.ControlToValidate);

        StringBuilder Script = new StringBuilder();
        Script.Append("<script language=\"javascript\">");

        Script.Append("function RequiredFieldValidatorEvaluateIsValid(val) {");
        Script.Append("    var value = ValidatorGetValue(val.controltovalidate);");
        Script.Append("if (value == '') {");

        Script.Append("document.getElementById(val.controltovalidate).style.backgroundColor = '$$BGCOLOR$$';");
        Script.Replace("$$BGCOLOR$$", ColorTranslator.ToHtml(ErrorBackgroundColor));

        Script.Append("document.getElementById(val.controltovalidate).style.borderColor = '$$BRCOLOR$$';");
        Script.Replace("$$BRCOLOR$$", ColorTranslator.ToHtml(ErrorBorderColor));

        Script.Append("return false;    }");
        Script.Append("else {");

        Script.Append("document.getElementById(val.controltovalidate).style.backgroundColor = '$$ORIG_BGCOLOR$$';");
        Script.Replace("$$ORIG_BGCOLOR$$", ColorTranslator.ToHtml(OriginalBackgroundColor));

        Script.Append("document.getElementById(val.controltovalidate).style.borderColor = '$$ORIG_BRCOLOR$$';");
        Script.Replace("$$ORIG_BRCOLOR$$", ColorTranslator.ToHtml(OriginalBorderColor));

        Script.Append("return true;} }");
        Script.Append("</script>");

        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ValidationScript", Script.ToString());
    }

    #endregion
}

Here is the Sample Default.aspx Page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Validators._Default" %>

<%@ Register TagPrefix="MyCtrl" Namespace="Validators" Assembly="Validators" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>">
<html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
        <MyCtrl:TextBoxRequiredFieldValidator ID="valid1" runat="server" ControlToValidate="TextBox1"
            ErrorBackgroundColor="LightGray" ErrorBorderColor="Red"></MyCtrl:TextBoxRequiredFieldValidator>
        <br />
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
        <MyCtrl:TextBoxRequiredFieldValidator ID="TextBoxRequiredFieldValidator1" runat="server"
            ControlToValidate="TextBox2" ErrorBackgroundColor="LightGray" ErrorBorderColor="Red">
        </MyCtrl:TextBoxRequiredFieldValidator>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </div>
    </form>
</body>
</html>

Hope this help’s!

Good Luck

Older Posts »

Blog at WordPress.com.