Thursday, October 23, 2008
Javascript validation for input limited text into textbox or textarea in ASP.NET
On design page source::
----------------------------
On b/h code source page:
protected void Page_Load(object sender, EventArgs e)
{
txtLocation.Attributes.Add("onkeypress", "return LocationLength()");
txtLocation.Attributes.Add("onkeyup", "return LocationLength()");
}
Happy Coding..!!
Saturday, October 18, 2008
Get And Set The System Date And Time using c#
here it is, C# code snippet that uses unmanaged code to retrieve the current date and time of the Windows operating system, and also sets it to the specified values.
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Windows.Forms;
- using System.Runtime.InteropServices;
- namespace Sample
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- public struct SystemTime
- {
- public ushort Year;
- public ushort Month;
- public ushort DayOfWeek;
- public ushort Day;
- public ushort Hour;
- public ushort Minute;
- public ushort Second;
- public ushort Millisecond;
- };
- [DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
- public extern static void Win32GetSystemTime(ref SystemTime sysTime);
- [DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
- public extern static bool Win32SetSystemTime(ref SystemTime sysTime);
- private void button1_Click(object sender, EventArgs e)
- {
- // Set system date and time
- updatedTime.Year = (ushort)2008;
- updatedTime.Month = (ushort)4;
- updatedTime.Day = (ushort)23;
- // UTC time; it will be modified according to the regional settings of the target computer so the actual hour might differ
- updatedTime.Hour = (ushort)10;
- updatedTime.Minute = (ushort)0;
- updatedTime.Second = (ushort)0;
- // Call the unmanaged function that sets the new date and time instantly
- Win32SetSystemTime(ref updatedTime);
- // Retrieve the current system date and time
- Win32GetSystemTime(ref currTime);
- // You can now use the struct to retrieve the date and time
- MessageBox.Show("It's " + currTime.Hour + " o'clock. Do you know where your C# code is?");
- }
- }
- }
Delete All Temporary Internet Files Of Internet Explorer
- using System.IO;
- public static void Main()
- {
- ClearFolder(new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache))); // Execute ClearFolder() on the IE's cache folder
- }
- void ClearFolder(DirectoryInfo diPath)
- {
- foreach (FileInfo fiCurrFile in diPath.GetFiles())
- {
- fiCurrFile.Delete();
- }
- foreach (DirectoryInfo diSubFolder in diPath.GetDirectories())
- {
- ClearFolder(diSubFolder); // Call recursively for all subfolders
- }
- }
Thursday, October 16, 2008
How to get IP address of the Current Machine?
{
string hostName = Dns.GetHostName();
Console.WriteLine("Host Name = " + hostName);
IPHostEntry local = Dns.GetHostByName(hostName);
foreach(IPAddress ipaddress in local.AddressList)
{
Console.WriteLine("IPAddress = " + ipaddress.ToString());
}
}
Saturday, October 11, 2008
Resolving w3c validation issues details...
please read Why should we Validate our WebSites?
When validating your website using W3C some weird errors might occur
An Example is
there is no attribute "border".
even if you haven't given the border attribute
The Reason
The ASP.NET engines sees the W3C validator as down-level browser and renders
non-XHTML compliant code. Your code is most likely fine. The problem is with
ASP.NET.
The Solution(Step Wise)
1.Right Click on your Solution Explorer
2.Click on Add ASP.NET Folder ---> App_Browsers
3.Now Click on App_Browsers ---> Add New Item
4.A dialog Box now pops up with some Visual Studio Installed Templates.
Select the Browser File Template from there, change the name as W3CValidations.browser(any other convenient name also) and Click on the Add Button
5.Delete the whole XML MarkUp code inside the W3CValidations.browser
6.Place the following code instead
7.Now upload this Folder nad File to your Hosting Service
8.Re Validate using W3C Validator
9.Bingo! You got a Clean Validation Certificate.
10. Show off the Validation Certificate to all those who cares [:)]
Happy coding..!!
ref:
http://fun2code.blogspot.com/search?updated-max=2008-08-28T15%3A02%3A00%2B05%3A30&max-results=3
Saturday, October 4, 2008
use Messagebox in asp.net
using System.Windows.Forms;
Code:
MessageBox.Show("message right here!!");
Msgbox for ASP.Net
Call this function from the server side, and a msgbox will appear on the client browser. As a bonus, the msgbox javascript is added after the rest of the form, so the browser displays the html for the page and then the msgbox.
Declaration:
Imports System.Text
Code:
Public Sub UserMsgBox(ByVal sMsg As String)
Dim sb As New StringBuilder()
Dim oFormObject As System.Web.UI.Control
sMsg = sMsg.Replace("'", "\'")
sMsg = sMsg.Replace(Chr(34), "\" & Chr(34))
sMsg = sMsg.Replace(vbCrLf, "\n")
sMsg = ""
sb = New StringBuilder()
sb.Append(sMsg)
For Each oFormObject In Me.Controls
If TypeOf oFormObject Is HtmlForm Then
Exit For
End If
Next
' Add the javascript after the form object so that the
' message doesn't appear on a blank screen.
oFormObject.Controls.AddAt(oFormObject.Controls.Count, New LiteralControl(sb.ToString()))
end sub
Happy coding..!!
Monday, September 29, 2008
Error - GetTypeHashCode() : no suitable method found to override
After creating an ASP.NET web form using Microsoft Visual Studio 2005 or Microsoft Visual Studio 2005 Team Suite, I renamed the form from it's default name "Default.aspx" to a more user-friendly name "Order.aspx" within MS VS. After adding more code to the C# code-behind page, I discovered the following line: "public partial class _Default"
Being new to the ASP.NET programming language, I changed the "_Default" to "Order" thinking MS VS had failed to rename items within the code it generates. This caused the following error to display at debug/run time: "GetTypeHashCode() : no suitable method found to override"
There were several other errors displayed as well.
The class names must match between the .aspx and .aspx.cs web pages. Here is what the lines in each file should look like:
In the ASPX source file: %@ Page Language="C#" codefile="FormName.aspx.cs" Inherits="FormName_aspx" %
In the ASPX.CS source file: public partial class FormName_aspx : Page
Once I changed the .ASPX file to match the class name in the .ASPX.CS file, the errors were resolved.
Ref::
http://forums.asp.net/t/1225330.aspx
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/7dbed154-34c6-41e3-b44f-23a594e9ccba/
Saturday, September 27, 2008
GenerateRandomName for images in asp.net 2.0 using c#
{
string allowedChars = "";
allowedChars = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,";
allowedChars += "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,";
allowedChars += "1,2,3,4,5,6,7,8,9,0";
char[] sep ={ ',' };
string[] arr = allowedChars.Split(sep);
string fname = "";
string temp = "";
Random rand = new Random();
for (int i = 0; i < 10; i++)
{
temp = arr[rand.Next(0, arr.Length)];
fname += temp;
}
return fname;
}
just call this like::
string getrandomname = GenerateRandomName;
Happy Coding..!!
Friday, September 26, 2008
code to store and retrieve image from sql server
System.IO.MemoryStream memBuffer = new System.IO.MemoryStream();
tmpImg.Save(memBuffer, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] output = new byte[memBuffer.Length];
memBuffer.Read(output, 0, (int)memBuffer.Length);
// Write to SQL here
// Read from SQL here
memBuffer.Write(output, 0, output.Length);
tmpImg = Image.FromStream(memBuffer);
pictureBox1.Image = tmpImg;
Friday, September 12, 2008
How to ping a computer using windows application
public void PingHost(string host)
{
try
{
System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingReply pingReply = ping.Send(host);
MessageBox.Show("Status: " + pingReply.Status.ToString());
}
catch (System.Net.NetworkInformation.PingException e)
{
MessageBox.Show(e.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
PingHost(textBox1.Text.Trim());
}
Code for Lock Computer, VS 2005, c#
“ C:\WINDOWS\system32\rundll32.exe user32.dll,LockWorkStation” command. There
are Command for shut down, log off , restart....
using System;
using System.Collections.Generic;
using System.Text;
//using System.linq;
using System.Diagnostics;
namespace r.LockComputer
{
class Program
{
static void Main(string[] args)
{
Process.Start(@"C:\WINDOWS\system32\rundll32.exe", "user32.dll,LockWorkStation");
}
}
}
Tuesday, August 26, 2008
Store Image or Picture into DataBase and Retrieve from Database
Here is an example for How to store image into database and retrive that and display one by one
steps
*****
1. create one temp folder under root
2. save this 3 files into that
3. create database in ms-sql server
4. note : if connection not establishing with this driver , better to use jdbc :-> Odbc :-> driver
5. database code for ms-sqlserver
-create table image (uid numeric(6) identity (1001,1), img image )
-select * from image
getfile.html
************
Gettostore.jsp
**************
<%@ page language=”java” import=”java.sql.*,java.io.*” errorPage=”" %>
<%
try
{
Connection con = null;
System.setProperty( “jdbc.drivers”, “com.microsoft.jdbc.sqlserver.SQLServerDriver” );
Class.forName( “com.microsoft.jdbc.sqlserver.SQLServerDriver” );
con = DriverManager.getConnection( “jdbc:microsoft:sqlserver://SCALAR6:1433;DatabaseName=JAVATEAM;SelectMethod=cursor;User=sa;Password=ontrack20″ );
PreparedStatement pst = con.prepareStatement(”insert into image(img) values(?)”);
//logo path is a value which is come from file browser
FileInputStream fis=new FileInputStream(request.getParameter ( “path” ) );
byte[] b= new byte[fis.available()+1];
fis.read(b);
pst.setBytes(1,b);
pst.executeUpdate();
pst.close();
con.close();
}
catch(SQLException e)
{
out.println ( e);
}
catch (ClassNotFoundException e)
{
out.println( e );
}
%>
link –>
Puttoview.jsp
*************
<%@ page contentType=”text/html; charset=iso-8859-1″ language=”java” import=”java.io.*,java.sql.*” errorPage=”" %>
Home
<%
try
{
Connection con = null;
System.setProperty( “jdbc.drivers”, “com.microsoft.jdbc.sqlserver.SQLServerDriver” );
Class.forName( “com.microsoft.jdbc.sqlserver.SQLServerDriver” );
con = DriverManager.getConnection( “jdbc:microsoft:sqlserver://SCALAR6:1433;DatabaseName=JAVATEAM;SelectMethod=cursor;User=sa;Password=ontrack20″ );
PreparedStatement pst = null;
ResultSet rs=null;
FileOutputStream fos;
int i = 0;
%>
.jpg” mce_src=”./image<%=i%>.jpg” >
<%=i%> |
//run : http://localhost:8080/temp/getfile.html
Tricks with Server.MapPath
' the current directory
currDir = Server.MapPath(".")
' the parent directory
parentDir = Server.MapPath("..")
' the application's root directory
rootDir = Server.MapPath("/")
For example, you can store the application's root directory in an Application variable, and use it to dynamically build physical paths to other files and directories.
Happy Coding..!!
Monday, August 25, 2008
Thursday, July 24, 2008
ASP.NET: How To Name A Variable Or Property Using .NET’s “Reserved” Words
Public Property [Error]() As Boolean
Do it .! and Enjoying Coding with Reserved Keywords...
Happy Coding..!
Visual Studio.NET: How To Comment/Uncomment Large Blocks of Code
This One is for you,
To comment a large block of code (VS.NET), highlight the area you want to comment out and hold Ctrl and press K and then C.
To uncomment, highlight the commented area and hit Ctrl + K + U.
The mass uncommenting merely removes the forward-most apostrophe, so if you have actual comments in your commented code that were included in your initial highlighted region, they will remain comments upon uncommenting.
This tips is using at debugging time is most used by me.
Happy Coding..!
Monday, July 21, 2008
Get Total and Free Disk Space
Private Declare Function GetDiskFreeSpaceEx _
Lib "kernel32" _
Alias "GetDiskFreeSpaceExA" _
(ByVal lpDirectoryName As String, _
ByRef lpFreeBytesAvailableToCaller As Long, _
ByRef lpTotalNumberOfBytes As Long, _
ByRef lpTotalNumberOfFreeBytes As Long) As Long
Code:
Public Function GetFreeSpace(ByVal Drive As String) As Long
'returns free space in MB, formatted to two decimal places
'e.g., msgbox("Free Space on C: "& GetFreeSpace("C:\") & "MB")
Dim lBytesTotal, lFreeBytes, lFreeBytesAvailable As Long
Dim iAns As Long
iAns = GetDiskFreeSpaceEx(Drive, lFreeBytesAvailable, _
lBytesTotal, lFreeBytes)
If ians > 0 Then
Return BytesToMegabytes(lFreeBytes)
Else
Throw New Exception("Invalid or unreadable drive")
End If
End Function
Public Function GetTotalSpace(ByVal Drive As String) As String
'returns total space in MB, formatted to two decimal places
'e.g., msgbox("Free Space on C: "& GetTotalSpace("C:\") & "MB")
Dim lBytesTotal, lFreeBytes, lFreeBytesAvailable As Long
Dim iAns As Long
iAns = GetDiskFreeSpaceEx(Drive, lFreeBytesAvailable, _
lBytesTotal, lFreeBytes)
If iAns > 0 Then
Return BytesToMegabytes(lBytesTotal)
Else
Throw New Exception("Invalid or unreadable drive")
End If
End Function
Private Function BytesToMegabytes(ByVal Bytes As Long) _
As Long
Dim dblAns As Double
dblAns = (Bytes / 1024) / 1024
BytesToMegabytes = Format(dblAns, "###,###,##0.00")
End Function
Wednesday, July 16, 2008
screen keyword - vb.net, Centering a form in VB.NET
frm.Top = (Screen.PrimaryScreen.WorkingArea.Height - frm.Height) / 2
frm.Left = (Screen.PrimaryScreen.WorkingArea.Width - frm.Width) / 2
Get the Current Screen Resolution (VB.NET)
Dim intX As Integer = Screen.PrimaryScreen.Bounds.Width
Dim intY As Integer = Screen.PrimaryScreen.Bounds.Height
Return intX & " X " & intY
End Function
Thursday, July 10, 2008
How to get CAPS LOCK IS ON (VB.NET)
Private Sub txtPassword_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPassword.TextChanged
If My.Computer.Keyboard.CapsLock = True Then
'MsgBox("CAPS LOCK is ON", MsgBoxStyle.Information, "Password")
End If
End Sub
Change password(VB.NET)
If txtretype.Text = "" And txtold.Text = txtnew.Text Then
Try
cmd = New SqlCommand("insert into login values(@a, @B)", con)
cmd.Parameters.Add("@a", txtname.Text)
cmd.Parameters.Add("@b", txtretype.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("USER CREATED SUCCESSFULLY", "REGISTRATION", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub
Wednesday, July 2, 2008
Zoom Text Javascript
You can add as many messages as you like and change the colors to suit.
STEP 1
Copy the code below and paste this into the section of your html document. Add your messages and change font type, size and colors, etc, where the comments are indicated.
STEP 2
Copy the event handler code and paste this into the body tag of your html document.
onLoad="start()" onUnload="stop()"
STEP 3
Copy the code below and place this directly below the tag of your html document. Change the position of the zoom text effect by altering the" left" and "top" co-ordinates.
That;s it .!
Ref : http://www.hypergurl.com/zoomintro.html
Tuesday, July 1, 2008
Check Existing Duplicate Process
Module Module1
Sub Main()
Dim MatchingNames As System.Diagnostics.Process()
Dim TargetName As String
TargetName = System.Diagnostics.Process.GetCurrentProcess.ProcessName
MatchingNames = System.Diagnostics.Process.GetProcessesByName(TargetName)
If (MatchingNames.Length = 1) Then
Console.WriteLine("Started...")
Else
Console.WriteLine("Process already running")
End If
End Sub
End Module
Friday, June 27, 2008
SQL Server 2005 Paging Performance Tip
I've seen the following technique in several beginner code samples for demonstrating SQL Server 2005's ability to return paged results.
I've added the TotalRows = Count(*) OVER() line to demonstrate how return the total rows returned above and beyond the row count for the paged set. This removes the need for a second query to get the total rows available for paging techniques in your application. In your application, just check to make sure your resultset has records, then just grab the first record and retrieve its TotalRows column value.
Notice that in this query, the JOIN between the Orders table and the Users table is being run across all records that are found NOT just the records returned in the paged set.
declare @StartRow int
declare @MaxRows int
select @StartRow = 1
select @MaxRows = 10
select * from
(select o.*,u.FirstName,u.LastName,
TotalRows=Count(*) OVER(),
ROW_NUMBER() OVER(ORDER BY o.CreateDateTime desc) as RowNum
from Orders o , Users u
WHERE o.CreateDateTime > getdate() -30
AND (o.UserID = u.UserID) )
WHERE RowNum BETWEEN @StartRow AND (@StartRow + @MaxRows) -1
If you adjust your query as follows, you will see a substantial boost in performance. Notice this query only performs the join on the returned resultset which is much, much smaller.
SELECT MyTable.*,u.FirstName,u.LastName
FROM
(SELECT o.*, TotalRows=Count(*) OVER(),
ROW_NUMBER() OVER(ORDER BY o.CreateDateTime desc) as RowNum
FROM Orders o
WHERE o.CreateDateTime > getdate() -30
) as MyTable, Users u
WHERE RowNum BETWEEN @StartRow AND (@StartRow + @MaxRows) -1
and (MyTable.UserID = u.UserID)
URL validation in vb.net 2005
Public Function UrlIsValid(ByVal url As String) As Boolean
If url.ToLower().StartsWith("www.") Then url = "http://" & url
Dim webResponse As Net.HttpWebResponse = Nothing
Try
Dim webRequest As Net.HttpWebRequest = Net.HttpWebRequest.Create(url)
webResponse = DirectCast(webRequest.GetResponse(), Net.HttpWebResponse)
Return True
Catch
Return False
Finally
If webResponse IsNot Nothing Then webResponse.Close()
End Try
End Function
Email validation in vb.net 2005
Public Function EmailValid(ByVal email As String) As Boolean
' The regular expression rule
Dim Expression As New System.Text.RegularExpressions.Regex("\S+@\S+\.\S+")
' If the email matches the regular expression
If Expression.IsMatch(email) Then
' MessageBox.Show("The email address is valid.")
Return True
Else
' MessageBox.Show("The email address is NOT valid.")
Return False
End If
End Function
Numeric Validation in vb.net 2005
If (Microsoft.VisualBasic.Asc(key_char) <> 57) Then
'e.Handled = True
handel1 = True
End If
If (Microsoft.VisualBasic.Asc(key_char) = 8) Then
'e.Handled = False
handel1 = False
End If
If handel1 = True Then
Return 1
Else
Return 0
End If
End Function
Character Validation in vb.net 2005 without using control
Public Function CharValid(ByVal key_char As String) As Int32
If (Microsoft.VisualBasic.Asc(key_char) <> 90) _
And (Microsoft.VisualBasic.Asc(key_char) <> 122) Then
'Allowed space
If (Microsoft.VisualBasic.Asc(key_char) <> 32) Then
'e.Handled = True
handel1 = True
End If
End If
' Allowed backspace
If (Microsoft.VisualBasic.Asc(key_char) = 8) Then
'e.Handled = False
handel1 = False
End If
If handel1 = True Then
Return 1
Else
Return 0
End If
End Function
UTF8 encoded php mail function
The problem with the php mail is that it does not encode the names and subjects and they could get lost in the transport or be misinterpreted from the email readers. This function actually does the proper encoding and overcomes the php mail deficiency.
—————————–
function UTF8_mail($from,$to,$subject,$message,$cc=”",$bcc=”"){
$from = explode(”<”,$from );
$headers =“From: =?UTF-8?B?”.base64_encode($from[0]).”?= <”. $from[1] . “\r\n”;
$to = explode(”<”,$to );$to = “=?UTF-8?B?”.base64_encode($to[0]).”?= <”. $to[1] ;
$subject=”=?UTF-8?B?”.base64_encode($subject).”?=\n”;
if($cc!=”"){$cc = explode(”<”,$cc );$headers .= “Cc: =?UTF-8?B?”.base64_encode($cc[0]).”?= <”. $cc[1] . “\r\n”;}
if($bcc!=”"){$bcc = explode(”<”,$bcc );$headers .= “Bcc: =?UTF-8?B?”.base64_encode($bcc[0]).”?= <”. $bcc[1] . “\r\n”;}
$headers .=“Content-Type: text/plain; ”. “charset=UTF-8; format=flowed\n”. “MIME-Version: 1.0\n”. “Content-Transfer-Encoding: 8bit\n”. “X-Mailer: PHP\n”;
return mail($to, $subject, $message, $headers);
}
UTF8_mail(“Γιω�?γος Κοντοπουλος
—————————–
All this function is accomplishing is to encode each
Name
to
=?UTF-8?B?zpzOuc+HzrHOu863z4I=?= email@domain.com
The emails themselves don’t need to be encoded since an email conventionally can only consist of of latin characters but, we could also confuse the mail server if we did encode them.
Sending E-Mail(s) in PHP
E-mails in PHP can be easily sent using the library function 'mail'. This function takes four arguments to send E-mails from a PHP web page and returns 'true' upon successful delivery of Email. The parameters of this function are as follows:
-Recipient E-mail address
-E-mail Subject
-E-mail message (body)
-Headers and additional parameters like the Sender E-mail address
Syntax:
mail( string to, string subject, string message [, string additional_headers [, string additional_parameters]] )
This function returns the boolean value 'True' if the mail is sent successfully, otherwise it returns 'False'.
Example:
To : textbox
From : textbox
Subject : textbox
Message(body) : textbox or textarea
Send : button
Above forms shows how to send email through PHP. And code for the above examples given below, use this code and try it.
Sample PHP Code
//Check whether the submission is made
if(isset($hidSubmit)){
//Declarate the necessary variables
$mail_to=$txtEmailto;
$mail_from=$txtEmailfrm;
$mail_sub=$txtSub;
$mail_mesg=$txtMsg;
//Check for success/failure of delivery
if(mail($mail_to,$mail_sub,$mail_mesg,"From:$mail_from/r/nReply-to:$mail_from"))
echo "E-mail has been sent successfully from $mail_sub to $mail_to";
else
echo "Failed to send the E-mail from $mail_sub to $mail_to";
}
?>