Watermark the textbox using javascript

Posted by Venkat | Labels: ,

Hi , Now we have to discuss about the watermark the textbox using javascript

for that you have to use onblur and onfocus property of your textbox


<script type = "text/javascript">

var defaultText = "Enter your text here";

function WaterMark(txt, evt)

{

if(txt.value.length == 0 && evt.type == "blur")

{

txt.style.color = "gray";

txt.value = defaultText;

}

if(txt.value == defaultText && evt.type == "focus")

{

txt.style.color = "black";

txt.value="";

}

}

</script>


Here is the HTML Code of the Textbox control

<asp:TextBox ID="TextBox1" runat="server" Text = "Enter your text here"

ForeColor = "Gray" onblur = "WaterMark(this, event);"

onfocus = "WaterMark(this, event);">

</asp:TextBox>

Now we have to write the attributes through code on your Page_load Event

TextBox1.Attributes.Add("onblur", "WaterMark(this, event);")

TextBox1.Attributes.Add("onfocus", "WaterMark(this, event);")

Textbox should allow minimum 5 Character

Posted by Venkat | Labels: ,

Hi Use this code.


<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator
ID="valUserName" runat="server" ControlToValidate="TextBox1"
Display="Dynamic" ErrorMessage="Minimum length 6 characters"
ForeColor="" ValidationExpression=".{6}.*" ></asp:RegularExpressionValidator>

Limit the Maximum number of Characters in the texbox

Posted by Venkat | Labels: , ,

Here is the code how to limit the no.of charater entered by the user in TextBox , mostly this can be implemented on Post comment , Feedback , Message board ...



This example demonstrates on how are we going to limit the number of characters to be typed into the TextBox using JavaScript and display the remaining characters in a Label Control.


<script type="text/javascript" language="javascript">

function validatelimit(obj, maxchar)
{

if(this.id) obj = this;

var remaningChar = maxchar - obj.value.length;
document.getElementById('<%= Label1.ClientID %>').innerHTML = remaningChar;

if( remaningChar <= 0)
{
obj.value = obj.value.substring(maxchar,0);
alert('Character Limit exceeds!');
return false;

}
else
{return true;}
}

</script>

<body runat="server">
<form id="form1" runat="server">

<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" onkeyup="validatelimit(this,300)"> </asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="0"></asp:Label>

</form>

</body>
Note: 300 is the MAX length of the characters in the TextBox..Just change the value of 300 based on your requirements..

Clear all the control values in webpage

Posted by Venkat | Labels:

Here is the code to clear all the control values in the page. this function should call on Reset button Click event.


private void ResetFormValues(Control parent)
{
foreach (Control c in parent.Controls)
{
if (c.Controls.Count > 0)
{
ResetFormValues(c);
}
else
{
switch(c.GetType().ToString())
{
case "System.Web.UI.WebControls.TextBox":
((TextBox)c).Text = "";
break;
case "System.Web.UI.WebControls.CheckBox":
((CheckBox)c).Checked = false;
break;
case "System.Web.UI.WebControls.RadioButton":
((RadioButton)c).Checked = false;
break;

}
}
}
}

The same you can do it on JAVASCRIPT

Ex:

<input id="Button1" type='button' onclick='ClearAllControls()' value='Clear All Controls Using Javascript' />


<script language="javascript" type='text/javascript'>
function ClearAllControls() {
for (i = 0; i <>
doc = document.forms[0].elements[i];
switch (doc.type) {
case "text":
doc.value = "";
break;
case "checkbox":
doc.checked = false;
break;
case "radio":
doc.checked = false;
break;
case "select-one":
doc.options[doc.selectedIndex].selected = false;
break;
case "select-multiple":
while (doc.selectedIndex != -1) {
indx = doc.selectedIndex;
doc.options[indx].selected = false;
}
doc.selected = false;
break;
default:
break;
}
}
}
</script>

Editor controls

Posted by Venkat | Labels: ,

There are so many free editor controls Avaliable for .net control

http://www.freetextbox.com/
http://tinymce.moxiecode.com/
http://www.asp.net/AJAX/AjaxControlToolkit/Samples/HTMLEditor/HTMLEditor.aspx
I will post the each editor controls ,like how to declare and use it on ASP.NET etc..
Shortly...,

Installation of Freetexbox control

http://www.a2zdotnet.com/View.aspx?id=28
This is the Initialization of TinyMCE Editor control and you can also the downlaod the support folder

http://www.dotnetspider.com/resources/27037-TinyMCE-Editor-Control.aspx

Number of way pass the data between Webpages

Posted by Venkat | Labels:

Here is the link i have given , which shows the no. of way to pass the data between page like session,Querystring, Cross page Posting , etc..

http://dotnetslackers.com/Community/blogs/haissam/archive/2007/11/26/ways-to-pass-data-between-webforms.aspx

http://www.dotnetbips.com/articles/c585b4d3-93c5-4c66-9d49-8e1946f4d311.aspx

I will post the workout code shortly..,

Jump Link within Page

Posted by Venkat | Labels:

Here is the code how to switch the view like top or bottom

for ex: we have seen on FAQ pages there if we click top it goes to top of the page the same functionality we have to implement.

<asp:HyperLink ID="top" runat="server" />

<br />asdsadasdsadsadadas<br />

<asp:HyperLink ID="bottom" runat="server" NavigateUrl="#top" Text="top" />

or

<a id="identifier"> </a>
<br />asdhsa<br />asdjksahd<br />

<a href="#identifier"> to top</a>

How to Detect the user Close the page

Posted by Venkat | Labels:

You can use the onunload or the onbeforeunload events to execute codes when the browser is about to closed.

You may also use Page Methods, see below

http://aspalliance.com/1294_CodeSnip_Handle_Browser_Close_Event_on_the_ServerSide.all

The code below will simulates the closed button of the browser when the user invoked the button and display an alert message..

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function doSomething()
{
alert('Widnow is about to close');
}
</script>

</head>
<body onunload="doSomething();">
<form id="form1" runat="server">

</form>
</body&gt;

Small trick to hide HTML element

Posted by Venkat | Labels:

In this post I’m going to only show a simple trick how to hide an image by using XPath expression and by not adding “server side” code into codebehind or inside a server side script block. I got this simple idea from a post I recently answered on the ASP.Net forum. Maybe some other may find this useful.


<img runat="server" visible='<%# (XPath("@value") == "35" ) %>' src='<%# "images/" + XPath("@img") + ".gif" %>'>


The XPath expression for the @value attribute will return true if the value is 35, if not it will return false. The visible attribute that is added to the img element, can only hide an element if it’s turned into a html server control. That is done by adding the runat attribute.


Ref: http://fredrik.nsquared2.com/ViewPost.aspx?PostId=324

Watermark of images

Posted by Venkat | Labels: ,

We are going to discuss about watermarking the image , the importance of doing the watermark is protected and not to be redistributed , Suppose if you take some online gallery images , like arts,some site which selling photos are restricted his site image. They might be not to allow users to save image by right click on image , or saving the web page.


'Creating Dynamic Watermark on image
Dim objImage As System.Drawing.Image = System.Drawing.Image.FromFile(Server.MapPath("~/images/" & "Management.jpg"))
'From File
Dim height As Integer = objImage.Height
'Actual image width
Dim width As Integer = objImage.Width
'Actual image height
Dim bitmapimage As New System.Drawing.Bitmap(objImage, width, height)
' create bitmap with same size of Actual image
Dim g As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bitmapimage)
'Creates a System.Drawing.Color structure from the four ARGB component
'(alpha, red, green, and blue) values. Although this method allows a 32-bit value
' to be passed for each component, the value of each component is limited to 8 bits.
'create Brush
Dim brush As New SolidBrush(Color.FromArgb(113, 255, 255, 255))
'Adding watermark text on image
g.DrawString("Copywright", New Font("Arial", 18, System.Drawing.FontStyle.Bold), brush, 0, 100)
'save image with Watermark image/picture
'bitmapimage.Save("watermark-image.jpg"); //if u want to save image
Response.ContentType = "image/jpeg"
bitmapimage.Save(Server.MapPath("~/images/Copy.jpg"), ImageFormat.Jpeg)
bitmapimage.Dispose()
objImage.Dispose()

Resize an image using asp.net (vb.net) - Method 2

Posted by Venkat | Labels:

This is the second method of dynamically resizing the image ,


Resize an image using asp.net (vb.net) while uploading it into the server
======================Copy following code to Invoke upload======================

Dim fileExt = System.IO.Path.GetExtension(FileUpload.FileName).ToLower()
Dim previewName As String = Me.txtName.Text & "_preview" & fileExt
If fileExt.ToString.ToLower = ".jpeg" Or fileExt.ToString.ToLower = ".jpg" Or
fileExt.ToString.ToLower = ".gif" Then
Dim previewPic As Bitmap = (ResizeImage(FileUpload.PostedFile.InputStream, 500,
695))
previewPic.Save(Server.MapPath("Images/preview/") & previewName,
ImageFormat.Jpeg)
previewPic.Dispose()
End If
==================Copy following Function for resizing image====================
Function ResizeImage(ByVal streamImage As Stream, ByVal maxWidth As Int32, ByVal
maxHeight As Int32) As Bitmap

Dim originalImage As New Bitmap(streamImage)
Dim newWidth As Int32 = originalImage.Width
Dim newHeight As Int32 = originalImage.Height
Dim aspectRatio As Double = Double.Parse(originalImage.Width) /
Double.Parse(originalImage.Height)
If (aspectRatio <= 1 And originalImage.Width > maxWidth) Then
newWidth = maxWidth
newHeight = CInt(Math.Round(newWidth / aspectRatio))
Else
If (aspectRatio > 1 And originalImage.Height > maxHeight) Then
newHeight = maxHeight
newWidth = CInt(Math.Round(newHeight * aspectRatio))
End If
End If
Dim newImage As New Bitmap(originalImage, newWidth, newHeight)
Dim g As Graphics = Graphics.FromImage(newImage)
g.InterpolationMode =
System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear
g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height)
originalImage.Dispose()
Return newImage
End Function

Resize Image using asp.net Method - 1

Posted by Venkat | Labels: ,

Here We have to discuss, how to dynamically resize the images using asp.net , generally we used two image one as Thumbnail and another one is big image , so if you upload the big image , we can set the default height and width on code to resize that image , at the same while we upload small image , on resizing the image it will be stretched to the specified height and width and also not seen qualify of image is not good ,

so here , we calculate the width , as per we resize the image

I would prefer this method.

this is the First Method , for this place one fileupload control and button on you design form


Dim thumbWidth As Integer = 132
Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream)
'Create a System.Drawing.Bitmap with the desired width and height of the thumbnail.
Dim srcWidth As Integer = image.Width
Dim srcHeight As Integer = image.Height
Dim thumbHeight As Integer = (srcHeight / srcWidth) * thumbWidth
Dim bmp As New Bitmap(thumbWidth, thumbHeight)
'Create a System.Drawing.Graphics object from the Bitmap which we will use to draw the high quality scaled image
Dim gr As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bmp)
'Set the System.Drawing.Graphics object property SmoothingMode to HighQuality
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
'Set the System.Drawing.Graphics object property CompositingQuality to HighQuality
gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
'Set the System.Drawing.Graphics object property InterpolationMode to High
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High

' Draw the original image into the target Graphics object scaling to the desired width and height
Dim rectDestination As New System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight)
gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel)

'Save to destination file
bmp.Save(Server.MapPath("~/images/" & FileUpload1.PostedFile.FileName))

' dispose / release resources
bmp.Dispose()
image.Dispose()

Get the directories

Posted by Venkat | Labels:

Here is the code how to get all directories and save them to a List:


//Path with all directories in

String Path = Server.MapPath("Folder1\\"); //Declare List

List<String> GetThreads = new List<String>();

//Get all direcotories

System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Path);

foreach (System.IO.DirectoryInfo file in dir.GetDirectories())

{

//This saves all Direcory names like "Folder1", "Folder2", "Folder3", "Folder4";

GetThreads.Add(file.Name);

}

Validate textbox it should contains atleast 20 characters

Posted by Venkat | Labels:

Here we have to discuss the validation of the field , the textbox should contain atleast 20 Characters


ValidationExpression=^.{20,1999}$ - >

This expression should accept atleast 20 charactes and maximum of 1999 - it does not accept less than 20 characters

If I assumed that you want to enter only alphabets ie a-z into your textbox for which the validation expression is:

ValidationExpression="^\D{20,}$"

For having both alphabets and digits expression:

ValidationExpression="^[a-z0-9]{20,}$"

Your expression below will allow all alphabets, digits as well as special chars as #, $ etc to be entered incase thats what you want:

ValidationExpression="^.{20,1999}$"

Validate URL

Posted by Venkat | Labels: ,

Validate URL 

<asp:RegularExpressionValidator 
            ID="RegularExpressionValidator1"
            runat="server" 
            ValidationExpression="(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?"
            ControlToValidate="TextBox1"
            ErrorMessage="Input valid Internet URL!"
            ></asp:RegularExpressionValidator> 
 
Here i update the Regex this will accept the URL like:
http://regxlib.com/Default.aspx | http://electronics.cnet.com/electronics/0-6342366-8-8994967-1.html 

Validate US Zip Code

Posted by Venkat | Labels: ,

To validate US Zip Code


<asp:RegularExpressionValidator
ID="RegularExpressionValidator1"
runat="server"
ValidationExpression="\d{5}(-\d{4})?"
ControlToValidate="TextBox1"
ErrorMessage="Input valid U.S. Zip Code!"
></asp:RegularExpressionValidator>

Validate US Phone number

Posted by Venkat | Labels: ,

Validate US Phone number


<asp:RegularExpressionValidator
ID="RegularExpressionValidator1"
runat="server"
ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"
ControlToValidate="TextBox1"
ErrorMessage="Input valid U.S. Phone Number!"
></asp:RegularExpressionValidator>

Validate US Social Security Number

Posted by Venkat | Labels: ,

Here we have to discuss how to validate US Social security number


<asp:regularexpressionvalidator id="RegularExpressionValidator1" runat="server" validationexpression="\d{3}-\d{2}-\d{4}"
controltovalidate="TextBox1" errormessage="Input valid U.S. Social Security Number!"></asp:regularexpressionvalidator>

Disable past dates in Calendar control

Posted by Venkat | Labels:

Here we are going to see how to disable the past date in the Calendar contorl




<asp:Calendar ID="Calendar1" runat="server" OnDayRender="Calendar_DayRender"></asp:Calendar>

protected void Calender_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.Date < DateTime.Today.Date)
{
e.Day.IsSelectable = false;
}
}

Upload and show the images from database

Posted by Venkat | Labels: ,

Hi , Here we are going to see how to upload the image file to database ie : we store the image as a binary format in database.

create the table(name myImages) in sqlserver

with the following columns.

Img_Id --> datatype int (Primary Key with identity)

Image_Content --> datatype image

Image_Type --> datatype varchar(50)

Image_Size --> datatype bigint

Now create a page with name ImageUpload.aspx write the following code....

HtmlCode...


<asp:fileupload id="FileUpload1" runat="server">
<asp:button id="Button1" runat="server" onclick="Button1_Click" text="Button">
</asp:button></asp:fileupload>



CodeBehind..

protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{
byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Image = FileUpload1.PostedFile;
Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);

SqlConnection myConnection = new SqlConnection(@"integrated security=yes;data source=.\sqlexpress;database=aaa");
SqlCommand storeimage = new SqlCommand("INSERT INTO myImages(Image_Content, Image_Type, Image_Size) values (@image, @imagetype, @imagesize)", myConnection);
storeimage.Parameters.Add("@image", SqlDbType.Image, myimage.Length).Value = myimage;
storeimage.Parameters.Add("@imagetype", SqlDbType.VarChar, 100).Value = FileUpload1.PostedFile.ContentType;
storeimage.Parameters.Add("@imagesize", SqlDbType.BigInt, 99999).Value = FileUpload1.PostedFile.ContentLength;

myConnection.Open();
storeimage.ExecuteNonQuery();
myConnection.Close();
}
}

To display the image....

Create one HttpHandler class with name Handler.ashx write the following code...


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

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.IO;

public class Handler : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
SqlConnection myConnection = new SqlConnection(@"integrated security=yes;data source=.\sqlexpress;database=aaa");
myConnection.Open();
string sql = "Select * from myImages where Img_Id=@ImageId";
SqlCommand cmd = new SqlCommand(sql, myConnection);
cmd.Parameters.Add("@ImageId", SqlDbType.Int).Value = context.Request.QueryString["id"];
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.ContentType = dr["Image_Type"].ToString();
context.Response.BinaryWrite((byte[])dr["Image_Content"]);
context.Response.End();
dr.Close();
myConnection.Close();

}

public bool IsReusable
{
get
{
return false;
}
}

}

and create one aspx file with name.... ImageDisplay.aspx

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%#"Handler.ashx?id="+Eval("Img_Id") %>' Height="100" Width="100" />
<asp:Label ID="Label1" runat="server" Text='<%#Eval("Img_Id") %>'></asp:Label>
<asp:Label ID="Label2" runat="server" Text='<%#Eval("Image_Type") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = FetchAllImagesInfo();
GridView1.DataBind();
}
public DataTable FetchAllImagesInfo()
{
string sql = "Select * from myImages";
SqlDataAdapter da = new SqlDataAdapter(sql, @"integrated security=yes;data source=.\sqlexpress;database=aaa");
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}

Get filename without extension

Posted by Venkat | Labels:

To get the filename without extension

There's an existing method in the System.IO namespace which can return a file name without the extension. You can call this passing in either a full file path, or just a file name.

For example:


string fileName = System.IO.Path.GetFileNameWithoutExtension("building.jpg")

Get details error msg through email

Posted by Venkat | Labels:

Here we discuss how to get the html errormessage ie: yellow asp.net error message ie: show on stack trace if any error occurs in our project so we have to pass this msg to user through email.

we just get that Asp.net yellow error msg

this is the code

Exception err = Server.GetLastError();
Response.Clear();
HttpUnhandledException httpUnhEx = err as HttpUnhandledException;
if (httpUnhEx != null)
{
Response.Write("<h1>ASP.NET Error Page:
\n"+ httpUnhEx.GetHtmlErrorMessage());
}

how to pass if condition through the inline HTML Code

Posted by Venkat | Labels: ,

Here is the code we are passing the if condition through inline code..

ex:

Visible='<%# IIf((((Eval("productsize")).ToString().Length > 0) OrElse (Decimal.Parse(Eval("productsize
")) <= 0)), "true", "false") %>'

instead of using some function or procedure or by writing code on Gridview_Rowdatabound
just we simple pass the condition to make the control visible True or flase

PayOffers.in