ASP.NET Ajax toolkit has a CalendarExtender control which is very cool as you can associate the CalendarExtender to a a TextBox and also to a Button/ImageButton so that you can popup the calendar.
Below is the code to get started with CalendarExtender:
<asp:TextBox ID="TextBox1" runat="server"width="200pt" /><asp:ImageButton ID="btnCalenderPopup"
Width="16" Height="16" runat="server"
ImageUrl="~/images/calender.bmp" CausesValidation="False" />
<ajaxToolkit:CalendarExtender
ID="CalendarExtender1" runat="server"
TargetControlID="TextBox1"
PopupButtonID="btnCalenderPopup"
Format="dd/MM/yyyy" />and,
Wait! What’s that grayed text in the textbox that says – Enter the Date of Birth (dd/mm/yyyy)
Certainly that’s not the part of CalendarExtender, but part of ASP.NET Ajax Toolkit. We can use the TextBoxWatermarkExtender which can display watermarked (grayed) texts on controls. Below is the code for our CalendarExtender :
class="csharpcode"><ajaxToolkit:TextBoxWatermarkExtender
ID="WatermarkExtender1"
runat="server"
TargetControlID="TextBox1"
WatermarkCssClass="watermarked"
WatermarkText="Enter the Date of Birth (dd/mm/yyyy)" />And below is the CSS style that’s used with this watermark extender :
.watermarked
{
color: #C0C0C0;
font-style: italic;
}All looks good now and the user is happy the way Calendar pops up, choosing the date and also the fact that he can type in the date in the textbox in the desired format. Now comes the problem – Date Validation! – How are we going to validate the entered date? – I had to validate that the date entered is not more than today’s date.
There are two ways to do it :
1) Using Javascript (with our CalendarExtender)
2) Using RangeValidators for our textboxUsing Javascript:
The CalendarExtender has a property called OnClientDateSelectionChanged which can be set to a piece of javascript which can do the job for us. Below is the code:
<ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server"
TargetControlID="TextBox1" PopupButtonID="btnCalenderPopup"
OnClientDateSelectionChanged="checkMyDate"
Format="dd/MM/yyyy" />and below is the javascript:
<script type="text/javascript">
function checkDate(sender,args)
{
var dt = new Date();
if(sender._selectedDate > dt)
{
sender
._textbox
.set_Value(dt.format(sender._format));
}
}
</script>Using RangeValidator: Since we use a TextBox control to display our date once we choose from the calendar or to manually input the date, RangeValidators can be used to check whether the date is within a given range (minimum & maximum). Below is the code for RangeValidator :
<asp:RangeValidator
ID="RangeValidator1"
runat="server"
ControlToValidate="TextBox1"
ErrorMessage="*Please enter proper date"
Type="Date" Display="Dynamic" />And in your page load event we can set our maximum and minimum date values :
RangeValidator1.MinimumValue
= new DateTime(1600, 01, 01).ToString("dd/MM/yyyy");
RangeValidator1.MaximumValue
= DateTime.Now.ToString("dd/MM/yyyy");With these two methods you can easily validate the date. And yes, using both would sometimes lead you to race conditions where choosing a date from the calendar might be an invalid date and the RangeValidators would immediately come to the focus.
If you have better solution, just tell me !
Console application
Below is my little console application that ask for name and display it in the message dialog box. Unfortunately there is a problem when I try to iimports System.Windows.Forms The error message is Warning 1 Namespace or type specified in the Imports 'System.Windows.Forms' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. I'm using Visual Basic 2008 express edition. any help would be appreciated.
Public Class Form1
Dim number(10) As String
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
TextBox1.Text = number(ComboBox1.Items.IndexOf(ComboBox1.Text))
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ComboBox1.Items.Add(ComboBox1.Text)
number(ComboBox1.Items.IndexOf(ComboBox1.Text)) = TextBox1.Text
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ComboBox1.Items.Add("") : number(0) = ""
End Sub
End ClassPlease refer to MSDN.microsoft.com/en-us/library/system.windows.forms.aspx
Ajax CalendarExtender - Date Validation
I've just been asked to find a solution to stop users choosing dates in the past in a calendarextender control. After using a little google-phoo, I found a couple of solutions which involved extending the extender itself. Altering the calendar.js then recompiling it and putting it back into your solution. That just seems a bit excessive to me. So I got to thinking couldn't I just use some in page JavaScript to trap the date entered.
First we add a text box and a calendarextender:
<asp:TextBox ID="txtDate" MaxLength="10" runat="server"
ReadOnly="True"></asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender1" runat="server"
Format="dd/MM/yyyy" TargetControlID="txtDate"
OnClientDateSelectionChanged="checkDate"> </cc1:CalendarExtender>you may notice that the CalendarExtender has an event attached (checkDate) - this is the JavaScript function you want it to call when ever you select a new date, add this function the top of your aspx page:
<script type="text/javascript">
function checkDate(sender,args)
{
//create a new date var and set it to the
//value of the senders selected date
var selectedDate = new Date();
selectedDate = sender._selectedDate;
//create a date var and set it's value to today
var todayDate = new Date();
var mssge = "";if(selectedDate < todayDate)
{
//set the senders selected date to today
sender._selectedDate = todayDate;
//set the textbox assigned to the cal-ex to today
sender._textbox.set_Value(sender._selectedDate.format(sender._format));
//alert the user what we just did and why
alert("Warning! - Date Cannot be in the past");
}
}
</script>Simple and the nice thing is it's reusable for all the calendarextenders on your page, just add the checkDate function to your other extenders.
Happy Coding
Using Ajax to Validate Forms
Forms are such a common element on the Internet we tend to blunder through them without too much thought. However, if the web site has added a few nice touches that make the process easier, it tends to speed up the process and reduce any frustration in finding our preferred username (i.e. try getting your name under Hotmail!).
HowtoAs with all these tutorials, I expect that you have built your solution to the point where it works, but now we want to add our splash of JavaScript magic.In our baseline example, my requirements are:Username validation
Username validation kept in separate function Server side does the it’s normal job I can detect an Ajax request and return something differentOur PHP function to validate the username reads:
function check_username($username) {
$username = trim($username); // strip any white space
$response = array(); // our response
// if the username is blank
if (!$username) {
$response = array(
'ok' => false,
'msg' => "Please specify a username");
// if the username does not match a-z or '.', '-', '_' then// it's not valid
} else if (!preg_match('/^[a-z0-9\.\-_]+$/', $username)) {
$response = array(
'ok' => false,
'msg' => "Your username can only contain alphanumerics and period,dash and underscore (.-_)");
// this would live in an external library just to check if the username is taken
} else if (username_taken($username)) {
$response = array(
'ok' => false,
'msg' => "The selected username is not available");
// it's all good
} else {
$response = array(
'ok' => true,
'msg' => "This username is free");
}
return $response;
}
This format for a response is good, because we are using it to display error messages on the page, but we can also convert it to JSON and use it in our Ajax response later on.
MarkupAgain, it’s assumed your markup is already designed to show error messages.
For this example the following markup is being used within a fieldset.
<div>
<label for="username">Username, valid: a-z.-_</label>
<input type="text" name="username" value="<?=@$_REQUEST['username']?>" id="username" />
<span id="validateUsername"><?php if ($error) { echo $error['msg']; }?></span>
</div>jQuery
Our client side check will perform the following:
- Only if the value has changed run the check, i.e. ignore meta keys
- Use a nice ajax spinner to indicate activity
- Make an Ajax request and show the response
$(document).ready(function () {
var validateUsername = $('#validateUsername');
$('#username').keyup(function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validateUsername.removeClass('error').html('<img src="images/ajax-loader.gif"height="16" width="16" /> checking availability...');
this.timer = setTimeout(function () {
$.ajax({
url: 'ajax-validation.php',
data: 'action=check_username&username=' + t.value,
dataType: 'json',
type: 'post',
success: function (j) {
validateUsername.html(j.msg);
}
});
}, 200);
this.lastValue = this.value;
}
});
});Fire an ajax request in 1/5 of a second.
$.ajax({
url: 'ajax-validation.php',
data: 'action=check_username&username=' + t.value,
dataType: 'json',
type: 'post',
success: function (j) {
validateUsername.html(j.msg);
}
});The actual Ajax request. If the script ajax-validation.php returns any response, convert it to JSON and put the ‘msg’ field in to the validation message.
Ajax Validation code : Download
If you have better solution, just tell me !
Download a file from database
Hi , we have to discuss about how to download a file from the database , we generally upload a file to database in binary form so how to download that file that is going to see here..
suppose if i upload a file and bind the file detail in Gridview or datalist there i have give the Download link - here i am passing the id of the specific row so using this is i will retrieve the file.
so we pass the id to other page to make the file as download.
If Not Request.QueryString("id") Is Nothing Then
Dim As New SqlCommand("Select * from where download_id like @id", con)
Dim ID As New SqlParameter("@ID", SqlDbType.SmallInt, 2)
ID.Value = Request.QueryString("id")
ID.Direction = ParameterDirection.Input
cmd.Parameters.Add(ID)
cmd.Connection = con
con.Open()
Dim dRE As SqlDataReader
dRE = cmd.ExecuteReader()
While dRE.Read()
Dim myTitle As String = dRE.GetString(4).ToString 'document title
Dim myType As String = dRE.GetValue(5).ToString 'document type
If myTitle = "None" Or myType = "None" Then
message.Text = "No Attachements Present !"
Exit Sub
Else
Dim myDoc = dRE.GetSqlBinary(3) 'document
Response.Buffer = True
Response.Clear()
Response.AddHeader("content-disposition", "attachment; filename=" & myTitle)
'application/octet-stream
Select Case myType.ToLower
Case "doc"
Response.ContentType = "application/msword"
Case "docx"
Response.ContentType = "application/msword"
Case "ppt"
Response.ContentType = "application/vnd.ms-powerpoint"
Case "xls"
Response.ContentType = "application/x-msexcel"
Case "htm"
Response.ContentType = "text/HTML"
Case "html"
Response.ContentType = "text/HTML"
Case "jpg"
Response.ContentType = "image/JPEG"
Case "gif"
Response.ContentType = "image/GIF"
Case "pdf"
Response.ContentType = "application/pdf"
Case Else
Response.ContentType = "text/plain"
End Select
Response.BinaryWrite(myDoc.Value)
Response.Flush()
Response.Close()
If myDoc.isNull Then
message.Text &= "Retrieving File: " _
& myTitle & "." & myType & " Size: NULL
"
Else
message.Text &= "Retrieving File: " _
& myTitle & "." & myType & " Size: " & myDoc.ToString() & "
"
End If
End If
End While
con.Dispose()
con = Nothing
cmdDownloadDoc.Dispose()
cmdDownloadDoc = Nothing
End If
End SubResize Image using asp.net Method - 1
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 = 132Dim 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()If you have better solution, just tell me !
Get All Files from Directories and Sub-Directories - Vb.NET
Here i have to discuss about how to get all the files of Directories and SubDirectories.
Generally we know how to get the files from From directory
Vb.NET
Imports System.IO
Dim position as integer = 1
Public Sub GetFiles(ByVal path As String)
If File.Exists(path) Then
' This path is a file
ProcessFile(path)
ElseIf Directory.Exists(path) Then
' This path is a directory
ProcessDirectory(path)
End If
End Sub
' Process all files in the directory passed in, recurse on any directories
' that are found, and process the files they contain.
Public Sub ProcessDirectory(ByVal targetDirectory As String)
' Process the list of files found in the directory.
Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
For Each fileName As String In fileEntries
ProcessFile(fileName)
Next
' Recurse into subdirectories of this directory.
Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
For Each subdirectory As String In subdirectoryEntries
ProcessDirectory(subdirectory)
Next
End Sub
' Insert logic for processing found files here.
Public Sub ProcessFile(ByVal path As String)
Dim fi As New FileInfo(path)
Response.Write("File Number " + position.ToString() + ". Path: " + path + "
")
position += 1
End Sub
Give the path like this
GetFiles("C:\Test\")
And there is a simple way to get all files like this
Dim di as new IO.DirectoryInfo("C:\uploadfiles")
Dim finfo as IO.FileInfo() = di.GetFiles("*.*",IO.SearchOption.AllDirectories)If you have better solution, just tell me !