26 Ağustos 2007 Pazar

Asp express 5.0


  • ASP Express allows you the extreme flexibility of an HTML text editor, while giving you the automation of a great ASP and ASP.Net text editor. Just look at some of the features:ASP Features:Basic Structures, like:SelectIf-ThenDo-WhileFor/Next
  • ADO Connection Assistant
  • Here's one of the best ASP or ASP.Net additions to hit an editor in a long time.Automatically insert all the information for an ADO Connection with very little work at all. Just insert your variable names for Connection, Recordset, DSN & SQL Select & Insert Statements. Then - for the best part of all - the SQL Select & Insert Statement Assistants - use your local database copy to easily assemble your SQL Select or Insert Statements!
  • SQL Builder Assistant(works with MS Access AND SQL Server 7/2000)
  • Create complex SQL statements to use with your ADO connection - both SELECT (including Inner Join) & INSERT statements. All your tables & fields are automatically accessible from pull-down menus, along with all the variable names you created on the page!Once you've done these short steps, voila - your ADO connection and your basic SQL statement is inserted and you didn't even break a sweat!(For direct SQL Server utilization, SQL tools must be installed on your development computer, like Enterprise Mgr/Client Network Utility) You can even choose to automatically insert the output in an HTML table or a Select List if you want!
  • Email Asstant
  • Easily create an ASP document using CDO to do your email jobs
  • Automatic FORM CODE GENERATOR
  • Choose your MS Access or SQL Server 7/200 database and table - ASP Express automatically generates the HTML for the input form!Choose between regular form format, or ASP.Net format!
  • The Express Toolbox
  • One tab lists all your commonly used ASP, ASP.Net VBScript , Javascript, & HTML tags and Assistants; one tab allows you to have a listing of your local files, and one tab allows for opening and saving your files web site files directly from the File Server using FTP
  • DataServer Window
  • Keep your data connections handy during ASP Express sessions - easily see which tables/fields are in the database and much more!
  • Greatly Improved FTP Capabilites - now FTP'ing of files is easier than ever!
  • Express Menus
  • Auto/Pop-up Completion for common ASP syntax such as Response, Request, & Server. Soon - even more (Connection, Recordset, FilesystemObject)
  • Global ASA Template creation
  • Simple Key Strokes for opening & closing ASP scriptCode Librarian stocked with many code snippets - allows you to build your own often-used code snippet library!
  • ASP Hit Counter Assistant
  • Make any HTML tag phrase 'Response.Write' - ready - highlight and convert your HTML into a Response.Write statement!Go To Line Number FeatureTurn WordWrapping on or off as needed .A 'REQUEST' Assistant for easily adding Request.Form & Request.QueryString Variables & Form Field Text Box Input Names, along with Server Variables in a pull down list!
  • An Easy RESPONSE Assistant for easily adding Response.Write statements!
    Seamlessly add include statements, browsing for the files
  • Easily Drag & Drop between ASP Express & other applications
  • When you format your HTML text - it stays highlighted to more easily add other HTML formatting or links to existing text
  • Easily create an HTML Table from Excel or Access data pasted into ASP Express - with a simple double-click!
  • Full Search & Replace within open documents or even entire subdirectories!

45 days shareware download


phpDesigner 2007 Professional 5.5.1















Syntax Highlighters


•Intelligent Highlighter that automatically switch between PHP, HTML, CSS, and JavaScript depending on your position!
•PHP (both version 4 and 5 are supported)
•SQL (MySQL, MSSQL 2000, MSSQL 7, Ingres, Interbase 6, Oracle, Sybase)
•HTML/XHTML
•CSS (both version 1 and 2.1 are supported)
•JavaScript
•VBScript
•Java
•C#
•Perl
•Python
•Ruby

Intelligent and Advanced Editing

•PHP code explorer shows all classes, extended classes, interfaces, properties, functions, constants and variables
•Intelligent code suggestions for PHP with full support for PHP 5.2, nested objects and object-oriented programming!
•Intelligent code suggestions for HTML/XHTML
•Intelligent code suggestions for CSS (both version 1 and 2.1 are supported)
•Intelligent code tip are displayed as you type, it shows you description, arguments and returning values for typed PHP functions including what version its available in!
•Highlight (un)matching brackets/tags
•Select or jump to matching brackets/tags
•Automatic indent or close brackets
•Jump to any declaration with filtering by classes, interfaces, functions, variables or constants
•Auto completions and corrections
•Bookmarks (1-9)
•Search and replace in multiple files with support for highlighting search results and regular expression
•Drag-n-drop text and files are supported
•Advanced printing options

Project and File Management

•PHP Code explorer shows all classes, extends, interfaces, properties, functions, constants and variables in the project
•Jump to any declaration in project files with filtering by classes, interfaces, functions, variables or constants
•Framework support
•Integration with 3rd party tools like Tortoise SVN or Tortoise CVS in the file and project browser

PHP

•Support for both PHP 4 and PHP 5
•Work with any PHP frameworks!
•Support for PHP heredoc
•Enclose strings with single- or double quotes, linefeed, carriage return or tabs
•PHP server variables
•PHP statement templates (if, else, then, while…)
•PHP code beautifier with many configurations
•phpDocumentor wizard
•Add phpDocumentor documentation to functions and classes with one click!
•phpDocumentor tags
•Smarty tags
•Comment or uncomment with one click!

Debug/Run & Preview

•Live syntax check for PHP, HTML and CSS
•Debug/Run PHP using the PHP Interpreter
•Syntax check PHP using the PHP Interpreter
•Localhost Preview
•Preview with Internet Explorer, Firefox, Netscape, Opera and Safari

HTML/XHTML

•Support for HTML 4.01 strict/transitional/frameset
•Support for XHTML 1.0 strict/transitional/frameset
•Link-, image-, table-, list-, meta-, flash, forms-, font and color dialog
•Formatting tools
•Color picker
•HTML Tidy (code beutifier for HTML/XHTML)

Integrated Help

•Contextual help for PHP (detailed information about more than 3000 native PHP functions on the fly using the PHP manual)
•Contextual search (search engines)

Code Libraries

•PHP
•phpDocumentor
•Smarty
•SQL (MySQL, MSSQL 2000, MSSQL 7, Ingres, Interbase 6, Oracle, Sybase)
•HTML
•XML
•CSS
•JavaScript
•VBScript
•Java
•C#
•Perl
•Python
•Ruby

Tools

•Application Manager
•Code Snippets
•Code templates allow you to type whole code fragments with one single click!
•Remote FTP editing
•Todo & Bug manager (embedded and external)
•Database connection manager
•Database browser (using phpMyAdmin)
•Date/Time Manager
•SSI
•TortoiseSVN integration
•Export to HTML, RTF and LaTeX

File Encoding

•ANSI (iso/windows)
•UTF-8 (with and without BOM)
•UTF 16 LE/BE (with and without BOM)

User Interface

•Fully customizable workspace with drag- and floatable toolbars/panels
•Theme support
•Save/load desktop layout

Free trial download


23 Ağustos 2007 Perşembe

Print Exception Class Hieararchy

Author: dr_bob

require 'pp'
tree = (cr = lambda {h,k h[k] = Hash.new &cr})[{},nil]
ObjectSpace.each_object(Class) {cl if cl.ancestors.include? Exception
then cl.ancestors.reverse.inject(tree){tr,cl tr[cl]} end}
pp tree


Extend Float and FixNum to do calculations in S.I. units

Source: http://stephan.walter.name/Ruby_snippets

module SiUnits
def mega; self * 1000.kilo; end
def kilo; self * 1000; end
def milli; self * 0.001; end
def micro; self * 0.001.milli; end

def seconds; self; end
def minutes; self * 60; end
def hours; self * 60.minutes; end
def days; self * 24.hours; end
def years; self * 365.days; end


def metres; self; end
def grams; self * 0.001; end
end

class Float; include SiUnits; end
class Fixnum; include SiUnits; end

p 2.days # => 172800
p 3.milli.metres # => 0.003
p 4.kilo.grams # => 4.0


Extend String to use ActionView's Text Helpers

Author: curtissummers, http://www.csummers.org/index.php/2006/08/07/extend-string-to-use-actionviews-text-helpers/

#ActionView's TextHelper methods are useful, but I often need to use them in my controller or my model. For several of the TextHelper methods that expect a string as input, it makes sense to extend the String class.
#So, if I want to strip HTML tags, auto link any URLs, and then simple format a comment (in that order) before I save it in the database I can do:
class Comment < ActiveRecord::Base
#...

def before_save
self.text = self.text.strip_tags.auto_link.simple_format
end
end

# This method is much cleaner than including ActionView::Helpers::TextHelper in whatever class I'm in and passing the string as an argument to each method.
# Below is the magic code. Since TextHelper is a module, we create a Singleton class to reference the methods, create the wrapper methods in their own module, and finally include that module in the String class. Note that not all TextHelper methods are included–just the ones that make sense. Drop this code into a file and require it in your environment or within a plugin.
# ActionView Text Helpers are great!
# Let's extend the String class to allow us to call
# some of these methods directly on a String.
# Note:
# - cycle-related methods are not included
# - concat is not included
# - pluralize is not included because it is in
# ActiveSupport String extensions already
# (though they differ).
# - markdown requires BlueCloth
# - textilize methods require RedCloth
# Example:
# "<b>coolness</b>".strip_tags -> "coolness"

require 'singleton'

# Singleton to be called in wrapper module
class TextHelperSingleton
include Singleton
include ActionView::Helpers::TextHelper
include ActionView::Helpers::TagHelper #tag_options needed by auto_link
end

# Wrapper module
module MyExtensions #:nodoc:
module CoreExtensions #:nodoc:
module String #:nodoc:
module TextHelper

def auto_link(link = :all, href_options = {}, &block)
TextHelperSingleton.instance.auto_link(self, link, href_options, &block)
end

def excerpt(phrase, radius = 100, excerpt_string = "…")
TextHelperSingleton.instance.excerpt(self, phrase, radius, excerpt_string)
end

def highlight(phrase, highlighter = '<strong class="highlight">\1</strong>')
TextHelperSingleton.instance.highlight(self, phrase, highlighter)
end
begin
require_library_or_gem 'bluecloth'
def markdown
TextHelperSingleton.instance.markdown(self)
end
rescue LoadError
# do nothing. method will be undefined
end
def sanitize
TextHelperSingleton.instance.sanitize(self)
end
def simple_format
TextHelperSingleton.instance.simple_format(self)
end
def strip_tags
TextHelperSingleton.instance.strip_tags(self)
end
begin
require_library_or_gem 'redcloth'
def textilize
TextHelperSingleton.instance.textilize(self)
end
def textilize_without_paragraph
TextHelperSingleton.instance.textilize_without_paragraph(self)
end
rescue LoadError
# do nothing. methods will be undefined
end
def truncate(length = 30, truncate_string = "…")
TextHelperSingleton.instance.truncate(self, length, truncate_string)
end
def word_wrap(line_width = 80)
TextHelperSingleton.instance.word_wrap(self, line_width)
end
end
end
end
end

# extend String with the TextHelper functions
class String #:nodoc:
include MyExtensions::CoreExtensions::String::TextHelper
end


Full text searching for ri content

Author: zenspider, http://blog.zenspider.com/archives/2006/08/full_text_searc.html


#From ZenSpider, http://blog.zenspider.com/archives/2006/08/full_text_searc.html:
#Check it out. Quick and dirty searching of ri content:
#Updated using: http://blog.zenspider.com/archives/2006/08/new_and_improve.html
# They added path independence and searching of gems and local installed ri/rdoc. Enjoy!#!/usr/local/bin/ruby -w

require 'rdoc/ri/ri_paths'
require 'find'
require 'yaml'
search = ARGV.shift
puts "Searching for #{search}"
puts
dirs = RI::Paths::PATH
dirs.each do dir
Dir.chdir dir do
Find.find('.') do path
next unless test ?f, path
yaml = File.read path
if yaml =~ /#{search}/io then
full_name = $1 if yaml[/full_name: (.*)/]
puts "** FOUND IN: #{full_name}"
data = YAML.load yaml.gsub(/ \!.*/, '')
desc = data['comment'].map { x x.values }.flatten.join("\n").gsub(/&quot;/, "'").gsub(/&lt;/, "<").gsub(/&gt;/, ">").gsub(/&amp;/, "&")
puts
puts desc
puts
end
end
end
end

# Lets you do stuff like:
% ./risearch.rb duplicate
# Searching for duplicate

[...]

** FOUND IN: Array#uniq!
# Removes duplicate elements from self. Returns nil if no changes are made (that is, no duplicates are found).
a = [ 'a', 'a', 'b', 'b', 'c' ]
a.uniq! #=> ['a', 'b', 'c']
b = [ 'a', 'b', 'c' ]
b.uniq! #=> nil
** FOUND IN: Array#
# Set Union---Returns a new array by joining this array with other_array, removing duplicates.
[ 'a', 'b', 'c' ] [ 'c', 'd', 'a' ]
#=> [ 'a', 'b', 'c', 'd' ]
[...]


Load a Web page in Ruby and print information

Author: jswizard , http://www.juretta.com/log/2006/08/13/ruby_net_http_and_open-uri/

require 'open-uri'
require 'pp'
open('http://www.juretta.com/') do f
# hash with meta information
pp f.meta

#
pp "Content-Type: " + f.content_type
pp "last modified" + f.last_modified.to_s
no = 1

# print the first three lines
f.each do line
print "#{no}: #{line}"
no += 1
break if no > 4
end
end


22 Ağustos 2007 Çarşamba

How to Find the Current URL with PHP

source: http://discomoose.org/2005/11/02/how-to-find-the-current-url-with-php/

<?php
// find out the domain:
$domain = $_SERVER['HTTP_HOST'];

// find out the path to the current file:
$path = $_SERVER['SCRIPT_NAME'];

// find out the QueryString:
$queryString = $_SERVER['QUERY_STRING'];

// put it all together:
$url = "http://" . $domain . $path . "?" . $queryString;
echo "The current URL is: " . $url . "<br />";

// An alternative way is to use REQUEST_URI instead of both
// SCRIPT_NAME and QUERY_STRING, if you don't need them seperate:
$url2 = "http://" . $domain . $_SERVER['REQUEST_URI'];
echo "The alternative way: " . $url2;
?>


18 Ağustos 2007 Cumartesi

Encrypting data from one stream to another and attaching hash of the password

resource: http://devdistrict.com/CodeDetails.aspx?A=54
using System.Security.Cryptography;
using System.IO;
using System.Data;
using System;
using System.Collections;
using System.ComponentModel;

public class PasswordEncryptor
{
private byte[] _keyBytes;
private byte[] _IVBytes;
private int _bufferSize=256;
private byte[] _hash;

public PasswordEncryptor(string password)
{
byte[] saltValueBytes = null;
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password,saltValueBytes,"SHA1",50);
_keyBytes = pdb.GetBytes(32);
_IVBytes = pdb.GetBytes(16);
HashAlgorithm hasher = SHA256.Create();
_hash = hasher.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes("password"));
}
public void EncryptWithHash(Stream input, ref Stream output)
{
output.Write(_hash,0,_hash.Length);
RijndaelManaged rj = new System.Security.Cryptography.RijndaelManaged();
rj.Mode= CipherMode.CBC;
ICryptoTransform trans = rj.CreateEncryptor(_keyBytes, _IVBytes);
CryptoStream cs = new CryptoStream(output, trans, CryptoStreamMode.Write);
byte[] bytes = new byte[_bufferSize];
int byteCount;
while((byteCount = input.Read(bytes, 0, bytes.Length))!= 0)
{
cs.Write(bytes,0,byteCount);
}
cs.FlushFinalBlock();
//cs.Close();
}
public void DecryptWithHash(Stream input, ref Stream output)
{
byte[] inputHash = new byte[_hash.Length];
input.Read(inputHash,0,_hash.Length);
if (inputHash.Length!=_hash.Length) throw new Exception("Invalid Password");
for (int i=0;i<_hash.Length;i++)
{
if (_hash[i]!=inputHash[i]) throw new Exception("Invalid Password");
}
RijndaelManaged rj = new System.Security.Cryptography.RijndaelManaged();
rj.Mode= CipherMode.CBC;
ICryptoTransform trans = rj.CreateDecryptor(_keyBytes, _IVBytes);
CryptoStream cs = new CryptoStream(input, trans, CryptoStreamMode.Read);
byte[] bytes = new byte[_bufferSize];
int byteCount;
while((byteCount = cs.Read(bytes, 0, bytes.Length))!= 0)
{
output.Write(bytes,0,byteCount);
}
cs.Flush();
}
}


RC4 Encryption

author: Rick Sands, http://www.bytemycode.com/snippets/snippet/93/
// RC4 Encryption

/*
From RSA Security's website:
"RC4 is a stream cipher designed by Rivest for RSA Data
Security (now RSA Security). It is a variable key-size stream
cipher with byte-oriented operations. The algorithm is based on
the use of a random permutation. Analysis shows that the period
of the cipher is overwhelmingly likely to be greater than 10^100.
Eight to sixteen machine operations are required per output byte,
and the cipher can be expected to run very quickly in software.
Independent analysts have scrutinized the algorithm and it is
considered secure."
This implementation encodes the byte stream to be encrypted
"in-place".
------------
// Examples:
------------
Byte[] Key = new Byte[5] { 12, 34, 22, 12, 32 };
Byte[] B = new Byte[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Examine B array before and after this next call.
RC4(ref B, Key);
// Examine B array before and after this next call.
RC4(ref B, Key);
*/

public void RC4(ref Byte[] bytes, Byte[] key )
{
Byte[] s = new Byte[256];
Byte[] k = new Byte[256];
Byte temp;
int i, j, t;
int byteLen = bytes.GetLength(0);
int keyLen = key.GetLength(0);

// Generate "8x8 S-Box" and initialize key index
for (i = 0; i < 256; i++)
{
s[i] = (Byte) i;
k[i] = key[i % keyLen];
}

j = 0;
for (i = 0; i<256; i++)
{
j = (j + s[i] + k[i]) % 256;
// swap
temp = s[i];
s[i] = s[j];
s[j] = temp;
}

i = j = 0;
for (int x = 0; x < byteLen; x++)
{
// The following is used to generate a random byte
i = (i + 1) % 256;
j = (j + s[i]) % 256;
temp = s[i];
s[i] = s[j];
s[j] = temp;
t = ((int)s[i] + s[j]) % 256;
// which is xor'd to the source
bytes[x] ^= s[t];
}
}


15 Ağustos 2007 Çarşamba

Use VB Component in C#

Imports System
Namespace hellovb
Public Class HelloString
Public Function GetString() As String

Console.WriteLine ("Hello World in Visual Basic Program")

End Function
End Class
End Namespace


' Compile it using vbc /t:library hellovb.vb
' This command will generate hellovb.dll
' Hello World program in C# (hellocs.cs)


using System;
namespace hellocs{
public class displayA

{

public void Displayhello()
{
Console.WriteLine("Hello in C# Program");
}
}
}

' Compile it using csc /t:library hellocs.cs
' This command will generate hellocs.dll
' Main program(in c#) in which we will use these libraries

Main Program in C# (maincs.cs)
using System;
using hellocs;
using hellovb;
class maincs

{
public static void Main()
{

hellovb.HelloString vb = new hellovb.HelloString(); // namespace.classname of hellovb.vb
vb.GetString(); //Calling vb function
hellocs.displayA cs = new hellocs.displayA(); // namespace.classname of hellocs.cs
cs.Displayhello(); //Calling vb function
}
}

' Compile it using command csc maincs.cs /r:hellocs.dll;hellovb.dll
' Output will be
' Hello World in Visual Basic Program
' Hello in C# Program


13 Ağustos 2007 Pazartesi

Using Cryptography to Encrypt Data in ASP.NET

'author: Wayne Plourde , http://www.15seconds.com/issue/021210.htm

Imports System.Diagnostics
Imports System.Security.Cryptography
Imports System.Text
Imports System.IO

Public Class CryptoUtil
'8 bytes randomly selected for both the Key and the Initialization Vector
'the IV is used to encrypt the first block of text so that any repetitive
'patterns are not apparent
Private Shared KEY_64() As Byte = {42, 16, 93, 156, 78, 4, 218, 32}
Private Shared IV_64() As Byte = {55, 103, 246, 79, 36, 99, 167, 3}

'24 byte or 192 bit key and IV for TripleDES
Private Shared KEY_192() As Byte = {42, 16, 93, 156, 78, 4, 218, 32, _
15, 167, 44, 80, 26, 250, 155, 112, _
2, 94, 11, 204, 119, 35, 184, 197}
Private Shared IV_192() As Byte = {55, 103, 246, 79, 36, 99, 167, 3, _
42, 5, 62, 83, 184, 7, 209, 13, _
145, 23, 200, 58, 173, 10, 121, 222}
'Standard DES encryption
Public Shared Function Encrypt(ByVal value As String) As String
If value <> "" Then
Dim cryptoProvider As DESCryptoServiceProvider = _
New DESCryptoServiceProvider()
Dim ms As MemoryStream = New MemoryStream()
Dim cs As CryptoStream = _
New CryptoStream(ms, cryptoProvider.CreateEncryptor(KEY_64, IV_64), _
CryptoStreamMode.Write)
Dim sw As StreamWriter = New StreamWriter(cs)

sw.Write(value)
sw.Flush()
cs.FlushFinalBlock()
ms.Flush()

'convert back to a string
Return Convert.ToBase64String(ms.GetBuffer(), 0, ms.Length)
End If
End Function

'Standard DES decryption
Public Shared Function Decrypt(ByVal value As String) As String
If value <> "" Then
Dim cryptoProvider As DESCryptoServiceProvider = _
New DESCryptoServiceProvider()

'convert from string to byte array
Dim buffer As Byte() = Convert.FromBase64String(value)
Dim ms As MemoryStream = New MemoryStream(buffer)
Dim cs As CryptoStream = _
New CryptoStream(ms, cryptoProvider.CreateDecryptor(KEY_64, IV_64), _
CryptoStreamMode.Read)
Dim sr As StreamReader = New StreamReader(cs)
Return sr.ReadToEnd()
End If
End Function


'TRIPLE DES encryption
Public Shared Function EncryptTripleDES(ByVal value As String) As String
If value <> "" Then
Dim cryptoProvider As TripleDESCryptoServiceProvider = _
New TripleDESCryptoServiceProvider()
Dim ms As MemoryStream = New MemoryStream()
Dim cs As CryptoStream = _
New CryptoStream(ms, cryptoProvider.CreateEncryptor(KEY_192, IV_192), _
CryptoStreamMode.Write)
Dim sw As StreamWriter = New StreamWriter(cs)
sw.Write(value)
sw.Flush()
cs.FlushFinalBlock()
ms.Flush()

'convert back to a string
Return Convert.ToBase64String(ms.GetBuffer(), 0, ms.Length)
End If
End Function

'TRIPLE DES decryption
Public Shared Function DecryptTripleDES(ByVal value As String) As String
If value <> "" Then
Dim cryptoProvider As TripleDESCryptoServiceProvider = _
New TripleDESCryptoServiceProvider()

'convert from string to byte array
Dim buffer As Byte() = Convert.FromBase64String(value)
Dim ms As MemoryStream = New MemoryStream(buffer)
Dim cs As CryptoStream = _
New CryptoStream(ms, cryptoProvider.CreateDecryptor(KEY_192, IV_192), _
CryptoStreamMode.Read)
Dim sr As StreamReader = New StreamReader(cs)

Return sr.ReadToEnd()
End If
End Function
End Class


Read Excel files from ASP.NET

source: aspfree , http://www.aspfree.com/c/a/ASP.NET-Code/Read-Excel-files-from-ASPNET/

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System" %>


<script language="C#" runat="server">
protected void Page_Load(Object Src, EventArgs E)
{
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\\exceltest.xls;" +
"Extended Properties=Excel 8.0;";
//You must use the $ after the object you reference in the spreadsheet
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]",strConn);

DataSet myDataSet = new DataSet();
myCommand.Fill(myDataSet, "ExcelInfo");
DataGrid1.DataSource = myDataSet.Tables["ExcelInfo"].DefaultView;
DataGrid1.DataBind();
}

</script>
<html>
<head></head>
<body>
<p><asp:Label id=Label1 runat="server">SpreadSheetContents:</asp:Label></p>

<asp:DataGrid id=DataGrid1 runat="server"/>\
</body>
</html>


How to Search an XML File

source: http://aspnet101.com/aspnet101/aspnet/codesample.aspx?code=xmlsearch

<%@ Import Namespace="System.Data" %>
<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
Dim ds as DataSet = new DataSet()
ds.ReadXml(Server.MapPath("/data/cars.xml"))
ddlPrice.DataSource=ds
ddlPrice.DataTextField="Price"
ddlPrice.DataBind
end if
End Sub

Sub GetCar(Source as Object, E as EventArgs)
Dim dsProducts as DataSet = new DataSet()
dsProducts.ReadXml(Server.MapPath("/data/cars.xml"))
Dim dv as DataView = new DataView(dsProducts.Tables("Products"))
dv.Sort = "Price"

Dim rowIndex as integer = dv.Find(ddlPrice.SelectedItem.Text)
Dim Price, Vehicle as String
if (rowIndex = -1) Then
Response.Write("Car not found")
else
ph1.visible="True"
Price = dv(rowIndex)("Price").ToString()
lblPrice.text = "Price: " + FormatCurrency(Price) + "<br>"
Vehicle = dv(rowIndex)("Vehicle").ToString()
lblCar.text="Vehicle : " + Vehicle
End If
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 3.1">
<title>Searching an XML File</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:DropDownList id="ddlPrice" Runat="server"/>
<asp:Button id="button1"
Text="Get Car"
onclick="GetCar"
Runat="server" /><br>
<asp:placeholder ID="ph1" Visible="False" Runat="server">
<asp:Label ID="lblCar" Runat="server" /> --
<asp:Label ID="lblPrice" Runat="server" /><br>
</asp:placeholder>
</form>
</body>
</html>


Deleting Duplicate Rows

--author: barkın ünüulu

--**************************************
-- Name: Deleting Duplicate Rows
-- Description:The Purpose of this code
-- is to delete the duplicate values occuring in a table. This code is column-orien
-- ted. That means the code works for the duplicate values occuring in a specified
-- column and deletes the values of the rows corresponding to that column.
-- By: barkın ünüulu
--
-- Inputs:I am going to specify the column name as COLUMNNAME and table name as
-- TABLENAME. It should be noted that the developers that are willing to run this c
--ode should put an "id" column in to their tables, which increments automatically
-- Side Effects:As the row number increa
-- ses, the time elapsed for the code increases...
--
--**************************************

DECLARE @i int
DECLARE @j int
DECLARE @k int
SET @k=(select count(*) FROM TABLENAME)
SET @i=1
WHILE @i<=@k
BEGIN
SET @j=@i+1
WHILE @j<=@k
BEGIN
IF ((select COLUMNNAME FROM TABLENAME WHERE ID=@i)=
(select COLUMNNAME FROM TABLENAME WHERE ID=@j))
begin
DELETE FROM TABLENAME
WHERE ID=@j
end
SET @j=@j+1
end
SET @i=@i+1
END


SQL Cursor Example

author: Robert Wawszkiewicz

DECLARE authors_cursor CURSOR FOR
SELECT au_id, au_fname, au_lname
FROM authors
WHERE state = 'UT'
ORDER BY au_idOPEN authors_cursorFETCH NEXT FROM authors_cursor
INTO @au_id, @au_fname, @au_lnameWHILE @@FETCH_STATUS = 0
BEGIN
PRINT ' '
SELECT @message = '----- Books by Author: ' +
@au_fname + ' ' + @au_lname PRINT @message -- Declare an inner cursor based
-- on au_id from the outer cursor. DECLARE titles_cursor CURSOR FOR
SELECT t.title
FROM titleauthor ta, titles t
WHERE ta.title_id = t.title_id AND
ta.au_id = @au_id -- Variable value from the outer cursor OPEN titles_cursor
FETCH NEXT FROM titles_cursor INTO @title IF @@FETCH_STATUS <> 0
PRINT ' <<No Books>>' WHILE @@FETCH_STATUS = 0
BEGIN SELECT @message = ' ' + @title
PRINT @message
FETCH NEXT FROM titles_cursor INTO @title END CLOSE titles_cursor
DEALLOCATE titles_cursor -- Get the next author.
FETCH NEXT FROM authors_cursor
INTO @au_id, @au_fname, @au_lname
ENDCLOSE authors_cursor
DEALLOCATE authors_cursor
GO


Sending file via bluetooth

#author: korakot, http://www.bigbold.com/snippets/user/korakot/13
#Python for series 60 enables many fun bluetooth stuff.

from socket import *
a = '00:10:60:ab:25:6f'
bt_obex_discover(a) # found at port 3
f = u'C:\\Nokia\\Startermonlog.txt'
bt_obex_send_file(a, 3, f)


Efficiently process big xml files with cElementTree

#ElementTree is becoming python's standard XML framework.
#It also supports processing data as it coming/loading.

import cElementTree

for event, elem in cElementTree.iterparse(file):
if elem.tag == "record":
# ... process record element ...
elem.clear()


Get link popularity on delicious

#author: dfdeshom , http://www.bigbold.com/snippets/user/dfdeshom/14

#We are using python's delicious-py module


def get_popular_count(user="user"):
import delicious
notapi = delicious.DeliciousNOTAPI()

#Get user's posts
user_posts = notapi.get_posts_by_user(user)
data = '#tagID popularity\n'

#For each url, get how popular it is
for i in range(len(user_posts)):
data += str(i)+" "+str(len(notapi.get_posts_by_url(user_posts[i]["url"])))+'\n'
str1 = user + "-data" #file name
data_file = file(str1,'w')
data_file.write(data)
data_file.close()
The resulting file will look like this:
$ less jemisa-data

#tagID popularity
0 6
1 744
2 928
3 120
4 1934
5 111
6 425
7 16
8 19
9 2
10 44
11 308
12 12
13 1
14 1
15 7
16 3
17 46
18 7
19 139
20 318
21 174
22 288
23 3
24 1
25 33
26 3
27 154


Get recent tags used by any user on delicious

author: dfdeshom

>>>import delicious

>>> delicious.get_userposts('dfdeshom').tags[1:]
[u'gnuplot', u'math math/culture', u'python', u'music', u'creativity', u'python', u'academia/culture advice gradschool', u'academia/culture advice gradschool', u'wordpress', u'python unicode', u'advice creativity', u'delicious', u'creativity', u'code programming tags', u'delicious', u'math/culture', u'wordpress', u'linux', u'wordpress', u'python', u'python', u'python', u'python', u'computer-algebra math number-theory python', u'php', u'haiti', u'delicious', u'haiti', u'delicious', u'creativity']
>>>


Recursive program to compute n!

def factorial(n)
if n == 0
return 1
else
return n * factorial(n - 1)
end
end


Full information for Ruby errors

#author: ciconia , http://www.bigbold.com/snippets/user/ciconia/2

#Sometimes I want to be able to print out everything about an error: it's class, message and the stack trace. So how about this:
#Update: followed suggestion by onarap and changed the line breaks to $/. No syntax highlighting because the code breaks the snippet parser.
class StandardError
def info
"#{self.class}: #{message}#$/#{backtrace.join($/)}"
end
end


Create classes at runtime

#author: nicwilliams , http://drnicwilliams.com/2006/08/07/ann-dr-nics-magic-models/
#For example, if you want to create a new class at runtime, and assign it a superclass, try the following:
def create_class(class_name, superclass, &block)
klass = Class.new superclass, &block
Object.const_set class_name, klass
end
With this code, you can create a class as follows:

create_class('Person', ActiveRecord::Base) do
set_table_name :people

def fullname
"#{firstname} #{lastname}" # assuming the people table has firstname,lastname columns
end
end


Nice post slug

#author: sligowaths http://www.bigbold.com/snippets/user/sligowaths/2
#-------------------------------------------------------------------------
#This code replaces accents to normal chars(e.g "á" => "a"), everything that isn´t in "a-zA-Z0-9" to "", multiples spaces to one space, and one space to "-".
#This is useful to make URLs from titles, like Netscape.com does...
#"A new report recommends only work 4 -6 hrs a day" => #"A-new-report-recommends-only-work-4-6-hrs-a-day"
#"Video: \"Popular Mechanics\" editor debunks 9/11 myths" => "Video-Popular-Mechanics-editor-debunks-911-myths"
# etc..
# The code is 95% based on http://textsnippets.com/posts/show/451
def self.nice_slug(str)
accents = {
['á','à','â','ä','ã'] => 'a',
['Ã','Ä','Â','À','Á'] => 'A',
['é','è','ê','ë'] => 'e',
['Ë','É','È','Ê'] => 'E',
['í','ì','î','ï'] => 'i',
['Í','Î','Ì','Ï'] => 'I',
['ó','ò','ô','ö','õ'] => 'o',
['Õ','Ö','Ô','Ò','Ó'] => 'O',
['ú','ù','û','ü'] => 'u',
['Ú','Û','Ù','Ü'] => 'U',
['ç'] => 'c', ['Ç'] => 'C',
['ñ'] => 'n', ['Ñ'] => 'N'
}
accents.each do ac,rep
ac.each do s
str = str.gsub(s, rep)
end
end
str = str.gsub(/[^a-zA-Z0-9 ]/,"")
str = str.gsub(/[ ]+/," ")
str = str.gsub(/ /,"-")
#str = str.downcase
end


Simple "Send Email from Ruby" Method

author: Peter (Ian Purton)
----------------------------
def send_email(from, from_alias, to, to_alias, subject, message)
msg = <<END_OF_MESSAGE
From: #{from_alias} <#{from}>
To: #{to_alias} <#{to}>
Subject: #{subject}

#{message}
END_OF_MESSAGE

Net::SMTP.start('localhost') do smtp
smtp.send_message msg, from, to
end
end


12 Ağustos 2007 Pazar

A Simple Centered Fixed Width Layout

body {
/* this is actually to make IE 5.5 happy as most browsers
understand auto for margin left and right */
text-align: center;
}

div#container {
/* we want the text aligned left, not centered so we first
center it on BODY and then left on the main container */
width: 776px;
margin-right: auto;
margin-left: auto;
text-align: left;
}


Remove margin/padding using CSS: Set Everything to Square One

/* Remove margin/padding */
* {
margin:0;
padding: 0;
}


Conditional Comments for IE

<!--
-----------------------------
Conditional Comments for IE :
-----------------------------
Say you have a rule that works fine in FireFox and Opera
but it's a little off in Internet Explorer.
-->

Keep your styles optimized for Firefox, but in the markup
add this:

<!--[if IE]>
<style type="text/css">
.yourclass
{
width:400px;
}
</style>
<![endif]-->

Where .yourclass is the offending item

You can do more:

<!--[if IE gte 5.5]>
Only if Internet Explorer greater than or equal to
version 5.5
<![endif]-->

You can also use lt, lte, gte and ! (! means 'not')


Add scrollbar to a Table

<!-- Add scrollbar to a Table -->
<html>
<head>
<title></title>
<style type="text/css">
<!--
.scroll {
overflow: scroll;
height: 80px;
width: 100%;
overflow: auto
}
-->
</style>
</head>

<body>
<div class="scroll">
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tr>
<td>test</td>
</tr>

<tr>
<td>test</td>
</tr>

<tr>
<td>test</td>
</tr>

<tr>
<td>test</td>
</tr>

<tr>
<td>test</td>
</tr>

<tr>
<td>test</td>
</tr>
</table>
</div>
</body>
</html>


Restrict input to alphanumeric and uppercase

<!--
Restrict input to alphanumeric and uppercase :
-->
<input type="text" onkeydown="f(this)" onkeyup="f(this)"
onblur="f(this)" onclick="f(this)" />
<!--
Javascript Code :
-->
<script language="javascript">
function f(o) {
o.value = o.value.toUpperCase().replace(/([^0-9A-Z])/g,"");
}
</script>


Remove IE's Image Toolbar

<!--
--------------------------
Remove IE's Image Toolbar
--------------------------
Simply add this meta element to your HTML documents to
disable the toolbar
-->
<meta http-equiv="imagetoolbar" content="no" />


Draggable Divs

<!--
Add dragging to your div elements. just adding class=”drag” to
the div element will make it draggable.

You can set the area in which the div(s) can be dragged
using setdragBounds function
-->

<!doctype html public "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<style>
.Text{
font-family: Verdana,Arial,Sans-serif,'Times New Roman';
font-size: 9pt;
font-weight: normal;
font-style: normal;
color: #666;
text-decoration: none;
}
.alertsBoxTitle{
font-family: Verdana,Arial,Sans-serif,'Times New Roman';
font-size: 9pt;
font-weight: bold;
font-style: normal;
color: #ffffff;
text-decoration: none;
}
.alertsBox{
background: #ECF1F9;
border: 1px #a1bcdf solid;
}
body{
overflow:hidden;
}
</style>
<script language="javascript">
// browser detection
var agt=navigator.userAgent.toLowerCase();
var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);

var is_nav = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
&amp;& (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
&& (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
var is_nav4 = (is_nav && (is_major == 4));
var is_nav6 = (is_nav && (is_major == 5));
var is_nav6up = (is_nav && (is_major >= 5));
var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var dragapproved=false
var z,x,y
var maxleft,maxtop,maxright,maxbottom;
function setdragBounds()
{

// you can set the bounds of the draggable area here
maxleft = 10;
maxtop = 10;
maxright = document.body.clientWidth - 10;
maxbottom = document.body.clientHeight - 100;
}
function move(e)
{
var tmpXpos = (!is_ie)? temp1+e.clientX-x: temp1+event.clientX-x;
var tmpYpos = (!is_ie)? temp2+e.clientY-y : temp2+event.clientY-y;
if (dragapproved)
{
z.style.left = tmpXpos;
z.style.top = tmpYpos;
if (tmpXpos < maxleft)
z.style.left = maxleft;
if (tmpXpos > maxright)
z.style.left = maxright;
if (tmpYpos < maxtop)
z.style.top = maxtop;
if (tmpYpos > maxbottom)
z.style.top = maxbottom;
return false
}
}
function drags(e)
{
if (!(is_ie)&&!(!is_ie)) return
var firedobj=(!is_ie)? e.target : event.srcElement
var topelement=(!is_ie)? "HTML" : "BODY"
while (firedobj.tagName!=topelement &amp;& firedobj.className!="drag" &amp;& firedobj.tagName!='SELECT' &amp;& firedobj.tagName!='TEXTAREA' && firedobj.tagName!='INPUT' && firedobj.tagName!='IMG')
{

// here you can add the elements that cannot be used for drag . using their class name or id or tag names
firedobj=(!is_ie)? firedobj.parentNode : firedobj.parentElement
}
if (firedobj.className=="drag")
{
dragapproved = true
z = firedobj
var tmpheight = z.style.height.split("px")
maxbottom = (tmpheight[0])?document.body.clientHeight - tmpheight[0]:document.body.clientHeight - 20;
temp1 = parseInt(z.style.left+0)
temp2 = parseInt(z.style.top+0)
x = (!is_ie)? e.clientX: event.clientX
y = (!is_ie)? e.clientY: event.clientY
document.onmousemove = move
return false
}
}
document.onmousedown=drags
document.onmouseup=new Function("dragapproved=false")
</script>
</head>
<body>
<div id="Dialog" style="width:316px;height:119px;max-width:316px;position:absolute;top:50px;left:140px; z-index:1000;" class="drag">
<table width="100%" style="width:315px;height:119px" cellspacing="0" cellpadding="0" class="alertsBox" id="dialog_table">
<tr style="cursor:move">
<td class="alertsBoxTitle notselectable" colspan="2" align="left" height="21" style="cursor:move;background-color:#32426F">Drag Me</td>
</tr>
<tr>
<td align="center" colspan="2" height="5"> </td>
</tr>
<tr>
<td align="center" colspan="2">
<table width="97%" border="0" cellspacing="0" cellpadding="0" align="center">
<tr>
<td valign='top' align="center">
</td>
</tr>
<tr>
<td valign='top' colspan="2" class="Text">You can place text here</td>
</tr>
<tr>
<td valign='top' colspan="2" align="center"><br/><input type="button" value="Ok"/></td>
</tr>
</table></td>
</tr>
</table>
</div>
</body>
</html>


Rake tasks to sync project hosted on freeonrails

// rake tasks to sync project hosted on freeonrails

require File.dirname(__FILE__) + "/scp_wrapper"
desc "pushes the app files onto freeonrails"
task :update_freeonrails => :environment do t
scp_wrapper = ScpWrapper.new
scp_wrapper.update_code
scp_wrapper.update_db
scp_wrapper.update_javascript
scp_wrapper.update_css
scp_wrapper.update_tests

# scp_wrapper.images
end
// ha .. moved over to rsync last moment
class ScpWrapper
def update_code
sync "app"
end


def update_db
sync "db/migrate", "db"
end

def update_javascript
sync "public/javascripts", "public"
end

def update_css
sync "public/stylesheets", "public"
end

def update_tests
sync "test"
end

def images
sync "public/images", "public"
end

private
def sync(source, dest = "")
system "rsync -avz #{RAILS_ROOT}/#{source} biketw@biketowork.info:/home/biketw/btw/#{dest}"
puts "#{source} synched"
endend


Simple enum creation

module Kernel
# simple (sequential) enumerated values
def enum(*syms)

syms.each { s const_set(s, s.to_s) }
const_set(:DEFAULT, syms.first) unless syms.nil?
end
end

//and the usage
require 'kernel'

module Constants
module Gradient
enum :DOWNSLOPE, :LEVEL, :UPSLOPE
end

module TreeCover
enum :GOOD, :BAD, :OK
end

module TrafficDensity
enum :LOW, :MEDIUM, :HIGH
end
end


11 Ağustos 2007 Cumartesi

Building drop down boxes using enum generated Constants

require 'constants'
module MapHelper
LOCAL_KEY =
FREE_ON_RAILS_KEY =
def key
case `hostname`.chomp
when 'localhost', 'rohan'

LOCAL_KEY
else
FREE_ON_RAILS_KEY
end
end
def tree_cover
build_options Constants::TreeCover
end
def gradient
build_options Constants::Gradient
end
def traffic_density
build_options Constants::TrafficDensity
end
def default(method)
eval "Constants::#{method}::DEFAULT"
end
private
def build_options(sym)
sym.constants.inject("") {str, value str + wrap(value) }
end
def wrap(option)
"<option value='#{option}'> #{option.downcase.capitalize} </option>"
end
end
// and the tests for this
require File.dirname(__FILE__) + '/../test_helper'
class MapHelperTest < Test::Unit::TestCase
include MapHelper
def test_options_for_combo_box_are_built_correctly
assert_tree_cover :GOOD
assert_gradient :DOWNSLOPE
assert_traffic_density :LOW
end
def test_defaulting
assert_default :TreeCover, :GOOD
assert_default :Gradient, :DOWNSLOPE
assert_default :TrafficDensity, :LOW
end
def assert_default(subject, const)
assert_equal const, default(subject)
end
def assert_tree_cover(const)
const = const.to_s
assert tree_cover.include?(option_string(const))
end
def assert_gradient(const)
const = const.to_s
assert gradient.include?(option_string(const))
end
def assert_traffic_density(const)
const = const.to_s
assert traffic_density.include?(option_string(const))
end
def option_string(const)
"<option value='#{const}'> #{const.downcase.capitalize} </option>"
end
end


Fix for ActiveRecord SQL Server adapter dates

# The SQL Server adapter for ActiveRecord uses Time objects to cast dates from the db. This fails for dates before 1970, thus some birthdates come back as nil. This is some kludge to use a DateTime in that case so we still get the value.
# A better approach may be to convert this code to use DateTime objects exclusively, but I'm not sure of the speed implications of doing so. The code below first tries to cast the value to a Time object; if that fails, it tries a DateTime object; if that fails, it returns nil.
# Stick this in a plugin to use with Rails.

module ActiveRecord
module ConnectionAdapters
class ColumnWithIdentity
def cast_to_time(value)
return value if value.is_a?(Time) or value.is_a?(DateTime)
time_array = ParseDate.parsedate(value)
time_array[0] = 2000
time_array[1] = 1
time_array[2] = 1
Time.send(Base.default_timezone, *time_array) rescue DateTime.new(*time_array[0..5]) rescue nil
end
def cast_to_datetime(value)
if value.is_a?(Time) or value.is_a?(DateTime)
if value.year != 0 and value.month != 0 and value.day != 0
return value
else
return Time.mktime(2000, 1, 1, value.hour, value.min, value.sec) rescue nil
end
end
return cast_to_time(value) if value.is_a?(Date) or value.is_a?(String) rescue nil
value
end
end
end
end


Read and parse RSS feed

require 'open-uri'
require 'rss/0.9'
require 'rss/1.0'
require 'rss/2.0'
require 'rss/parser'
url = 'http://some.host/rss.xml'
rss = RSS::Parser.parse(open(url){fdfd.read})
puts rss.items.collect{itemitem.title}.join("\n")


Displaying the last 10 pages visited from a session

# I wanted to store and display an array of the last 10 visited pages in a session. With the help of some folks in #rubyonrails (particularly aqua) this is what i've come up with:
class ApplicationController < ActionController::Base
before_filter :add_to_history
before_filter :page_title def add_to_history
session[:history] = []
session[:history].unshift ({"url" => @request.request_uri, "name" => page_title })
session[:history].pop while session[:history].length > 11
end
# This bit came from Peter Cooper's snippets source and was moved into the application controller: def page_title
case self.controller_name
when 'tag'
title = "Tags &raquo; " + @params[:tags].join(" &gt; ")
when 'user'
title = "Users &raquo; #{@params[:user]}"
when 'features'
case self.action_name
when 'show' then title = "Feature &raquo; #{Feature.find(@params[:id]).title}"
else title = APP_CONFIG["default_title"]
end
else
title = APP_CONFIG["default_title"] + self.controller_name + ":" + self.action_name
end
end
helper_method :page_title...
end
# In your partial you might do something like this:
<h4>User History</h4>
<% for cur in session[:history][0..9] -%>
<p><a href="<%= cur["url"] %>"><%= cur["name"] %></a></p>
<% end -%>


Practical.JavaScript.DOM.Scripting.and.Ajax.Projects


TITLE : Practical JavaScript, DOM Scripting and Ajax Projects (Paperback)
AUTHOR : by Frank Zammetti (Author) PUBLISHER : Apress publisher
ISBN : 1590598164
EDITION : 1st
PUB DATE : April 16, 2007 LANGUAGE : English
FORMAT : PDF
SIZE : 05 x 2.88 MB
----------------------------------------------

Practical JavaScript, DOM, and Ajax Projects is ideal for web developers already experienced in JavaScript who want to take their knowledge to the next level. It presents ten complete example projects for you to learn from and adapt for use in your own work. The book starts with a quick recap of the fundamentals of modern JavaScript development before moving right along to the applications. For each application, you are taken through the planning, design, and implementation stages. There's something for everyone here--a utility library, a validation framework, a GUI widget framework, a dynamic event calendar application, a drag-and-drop shopping cart, and more!
Over the course of the book, author Frank Zammetti covers JavaScript best practices, Ajax techniques, and some of the most popular JavaScript libraries, such as Prototype, Script.aculo.us, and the Yahoo YUI. One of the main premises of this book is to help you learn by example so you can then apply your knowledge to your own projects. This book will save you countless hours of development time and help further your JavaScript knowledge!

download pdf


ajax in practice


Ajax in Practice provides example-rich coverage of Ajax packed with ready-to-use code and practical recipes for common and not-so-common tasks. Ajax developers now face the move from Ajax-as-theory to Ajax-in-practice. Ajax in Practice guides web developers through the transition from learning about Ajax to successfully applying Ajax-driven techniques in real-world development scenarios. Ajax gives web developers the potential to create rich user-centered internet applications. But Ajax also adds a new level of complexity and sophistication to those applications. Ajax in Practice tackles Ajax head-on, providing countless hands-on techniques and tons of reusable code to address the specific issues developers face when building Ajax-driven solutions. After a brief overview of Ajax, this book takes the reader through dozens of working examples, all presented in an easy-to-use cookbook format. Readers will learn how to implement drag-and-drop interfaces and will discover how to create effective nagigation strategies for their applications. Unlike a traditional cookbook, though, Ajax in Practice provides a thorough discussion of each technique presented and shows how the individual components can be connected to create powerful solutions. A fun "mash-up" chapter concludes the book. Throughout Ajax in Practice, the examples chosen are interesting, entertaining, and practical.


beginning ajax with asp.net


Author(s): Wallace B. McClure, Scott Cate, Paul Glavich, Craig Shoemaker Publisher: Wrox Year: Sep 2006 ISBN: 047178544X Language: English Pages: 428 File type: PDF Size (for download): 6.8 MB

Ajax is a set of technologies that will revolutionize the way that web-based applications are designed. It revolutionizes the way that applications are used, provides users a responsive application, and provides developers with the alternatives for building their applications. We believe that this book will meet your needs regarding programming Ajax on the ASP.NET platform.
People interested in this book will be developers who are working in the ASP.NET environment and are looking to create a more responsive and modern application using technologies that are very similar to the desktop methodologies. Developers who are looking to improve the user experience of their existing applications, develop new applications, develop internal line-of-business applications, and those who want to bulk up with the latest technology that developers all over the world are talking about will find what they are looking for here.
This book is for programmers who use ASP.NET and are just starting to use Ajax technologies. This book will assist developers working on ASP.NET-based applications who want to improve their applications and skills, by providing a background in Ajax for them before delving into how to apply Ajax to their applications.
TABLE OF CONTENT: Chapter 1: Introduction to Ajax on ASP.NET Chapter
2: Introduction to DHTML Chapter
3: JavaScript and the Document Object Model Chapter
4: The XMLHttpRequest Object Chapter
5: Data Communication: XML, XSLT, and JSON Chapter
6: What Is Built into ASP.NET Chapter
7: Ajax.NET Professional Library Chapter
8: Anatomy of Ajax.NET Pro Library Chapter
9: Other Ajax Frameworks for .NET Chapter
10: Atlas Client Script Chapter
11: Atlas Controls Chapter
12: Atlas Integration with ASP.NET Services Chapter
13: Debugging
password: ganelon


The Essential Guide to Dreamweaver CS3 with CSS, Ajax, and PHP (Paperback)


With over 3 million users worldwide, Adobe's Dreamweaver is the most popular web development software in the world, and it just took another step forward with CS3, the new version released in 2007. Having come a long way from it's humble beginnings as a as a simple web design tool, CS3 allows you to rapidly put together standards compliant web sites and dynamic web sites with server -side languages and Ajax, and much more.

What youll learn:
* How to set up your ideal development environment, using Mac OSX/Windows, Apache (and IIS on Windows,) Apache, MySQL, and phpMyAdmin
* Creating standards compliant web sites using CS3's XHTML and CSS features
* Creating dynamic web applications using CS3's PHP and Spry Ajax server behaviors
* Building several real world web site functions, such as form validation, random quote generator, search function, user management/login pages, dynamic Ajax gallery, and much more.
* Creating an interface design in Fireworks CS3 and importing it into Dreamweaver CS3.
* How use Dreamweaver CS3's XML functionality, to consume RSS feeds, and create Spry data sets
* Using includes, templates and master detail pages.
* How to publish your site after you've created it


Add or Subtract a number of Business days from a Date

' Note that it doesn't take Christmas, Easter and
' other holidays into account

Function BusinessDateAdd(ByVal days As Long, ByVal StartDate As Date, _
Optional ByVal SaturdayIsHoliday As Boolean = True) As Date
Do While days
' increment or decrement the date
StartDate = StartDate + Sgn(days)
' check that it is a week day
If Weekday(StartDate) <> vbSunday And (Weekday(StartDate) <> vbSaturday _
Or Not SaturdayIsHoliday) Then
' days becomes closer to zero
days = days - Sgn(days)
End If
Loop
BusinessDateAdd = StartDate
End Function


Pagination in ASP

'***************************************
'
' *
' iNumPerPage is the number of items to
' display on each page
' sURL is the page to put with the link
' , sQuerystring is additional qs stuff
' adodbConnection, adodbCommand, sTable
' are all for the table to get row count from. *
' *
' Print out the numbers (if any) betwee
' n the "previous" and "next" buttons
' It'll act like this (current # is in
' bold):
' 1 2 3 4 5 6 7 8 9 <b>10</b> >> next
' previous << <b>11</b> 12 13 14 15 16 17 18 *
' *
'' ****************************************

Sub PrintRecordsetNav( iNumPerPage, adodbConnection, adodbCommand, sTable, sURL, sQuerystring )

Dim iTtlNumItems, iDBLoc, sSqlTemp, iTtlTemp
Dim iDBLocTemp, sURLBeg, iA, iB, x, iTemp, rsObj

iDBLoc = CInt(Request("iDBLoc"))
iTtlNumItems = CInt(Request("iTtlNumItems"))
' Get ttl num of items from the database if it's Not already In the QueryString
If (iTtlNumItems = 0) Then
Set rsObj = Server.CreateObject("ADODB.Recordset")
sSqlTemp = "SELECT COUNT(*) FROM " & sTable
adodbCommand.CommandText = sSqlTemp
rsObj.Open adodbCommand
If Not(rsObj.EOF) Then
iTtlNumItems = rsObj(0)
End If
rsObj.Close
Set rsObj = Nothing
End If
iTtlTemp = iTtlNumItems \ iNumPerPage ' this is the number of numbers overall (use the "\" To return int)
iDBLocTemp = iDBLoc \ iNumPerPage ' this is which number we are currently On (use the "\" To return int)
If (sQuerystring <> "") Then
sURLBeg = "<A href = """ & sURL & "?" & sQuerystring & "&iTtlNumItems=" & iTtlNumItems & "&iDBLoc="
Else
sURLBeg = "<A href = """ & sURL & "?iTtlNumItems=" & iTtlNumItems & "&iDBLoc="
End If

'***** BEGIN DISPLAY *****
' Print the "Previous"
If (iDBLoc <> 0) Then
Response.Write sURLBeg & (iDBLoc - iNumPerPage) & """>Previous</A> "
End If
' Print the <<
If (iDBLocTemp >= iNumPerPage) Then
Response.Write sURLBeg & (( iDBLocTemp \ iNumPerPage ) * iNumPerPage ^ 2) - (iNumPerPage * 9) & """><<</A> "
End If

' Print the numbers in between. Print them out in sets of 10.
iA = ( iDBLocTemp \ iNumPerPage ) * iNumPerPage
iB = ( iDBLocTemp \ iNumPerPage ) * iNumPerPage + iNumPerPage
For x = iA To iB
iTemp = (x * iNumPerPage)
If (iTemp < iTtlNumItems) Then ' takes care of extra numbers after the overall final number
If (iDBLoc = iTemp) Then
Response.Write " <B>[" & x+1 & "]</B>"
Else
Response.Write " " & sURLBeg & (x * iNumPerPage) & """>" & x+1 & "</A>"
End If
Else
Exit For
End If
Next

' Print the >>
If (iTtlTemp > iDBLocTemp) Then
If ((iDBLocTemp + iNumPerPage) <= iTtlTemp) Then
Response.Write " " & sURLBeg & (( iDBLocTemp \ iNumPerPage ) * iNumPerPage + iNumPerPage ) * iNumPerPage & """>>></A> "
End If
End If
' Print the "Next"
If ((iDBLoc + iNumPerPage) < iTtlNumItems) Then
Response.Write " " & sURLBeg & (iDBLoc + iNumPerPage) & """>Next</A>"
End If
'***** End DISPLAY *****

End Sub


Calculate the Time to Download Files

<%
Function DownloadTime(intFileSize, strModemType)
Dim TimeInSeconds, ModemSpeed, strDownloadTime, AppendString
Dim intYears, intWeeks, intDays
Dim intHours, intMinutes, intSeconds
intYears = 0
intWeeks = 0
intDays = 0
intHours = 0
intMinutes = 0
intSeconds = 0
strDownloadTime = ""
Select Case strModemType
Case "Cable"
ModemSpeed = 400000
Case "56kbps"
ModemSpeed = 7000
Case "33.6kbps"
ModemSpeed = 4200
Case "28.8kbps"
ModemSpeed = 3600
End Select
TimeInSeconds = int(intFileSize / ModemSpeed)
'year maths added 1/4 of a day. 1 exact orbit of the sub is 365.25 days.
If (Int(TimeInSeconds / 31471200) <> 0) Then intYears = Int(TimeInSeconds / 31449600)
If ((Int(TimeInSeconds / 604800) Mod 52) <> 0) Then intWeeks = Int(TimeInSeconds / 604800) Mod 52
If ((Int(TimeInSeconds / 86400) Mod 7) <> 0) Then intDays = Int(TimeInSeconds / 86400) Mod 7
If TimeInSeconds >= 3600 Then intHours = Int(TimeInSeconds / 3600) Mod 24
If TimeInSeconds >= 60 Then intMinutes = Int(TimeInSeconds / 60) Mod 60
If TimeInSeconds >= 0 Then intSeconds = Int(TimeInSeconds) Mod 60
If intYears <> 0 Then
If intYears = 1 Then AppendString = "" Else AppendString = "s"
strDownloadTime = strDownloadTime & intYears & " year" & AppendString & ", "
End If
If intWeeks <> 0 Then
If intWeeks = 1 Then AppendString = "" Else AppendString = "s"
strDownloadTime = strDownloadTime & intWeeks & " week" & AppendString & ", "
End If
If intDays <> 0 Then
If intDays = 1 Then AppendString = "" Else AppendString = "s"
strDownloadTime = strDownloadTime & intDays & " day" & AppendString & ", "
End If
If intHours <> 0 Then
If intHours = 1 Then AppendString = "" Else AppendString = "s"
strDownloadTime = strDownloadTime & intHours & " hour" & AppendString & ", "
End If
If intMinutes <> 0 Then
If intMinutes = 1 Then AppendString = "" Else AppendString = "s"
strDownloadTime = strDownloadTime & intMinutes & " minute" & AppendString
End If
If ((intYears = 0) And (intWeeks = 0) And (intDays = 0) And (intHours = 0)) Then
If intSeconds = 1 Then AppendString = "" Else AppendString = "s"
If intMinutes > 0 Then
strDownloadTime = strDownloadTime & ", " & intSeconds & " second" & AppendString
Else
strDownloadTime = strDownloadTime & intSeconds & " second" & AppendString
End If
End If
DownloadTime = strDownloadTime
End Function
%>
<html>
<body>
It is going to take about
<%=DownloadTime(123456,Cable)%> to download this file.
</body>
</html>


How to Create Bar Charts

<%
Sub ShowChart(ByRef aValues, ByRef aLabels, ByRef strTitle, ByRef strXAxisLabel, ByRef strYAxisLabel)
Const gr_WIDTH = 450
Const gr_HEIGHT = 250
Const gr_BORDER = 5
Const gr_SPACER = 2
Const tbl_BORDER = 0
iMaxValue = 0
For I = 0 To UBound(aValues)
If iMaxValue < aValues(I) Then iMaxValue = aValues(I)
Next
iBarWidth = (gr_WIDTH \ (UBound(aValues) + 1)) - gr_SPACER
'NOTE: Each of the images you see in this code are just 1 pixel by 1 pixel
'wide, but we make them in different colors for the chart, and then
'stretch them to the size that we need them with the code below:
Response.Write"<table border="&tbl_BORDER&" cellspacing=0 cellpadding=0>"&_
"<tr><td colspan=3 align=center><h2>"&strTitle&"</h2></td></tr>"&_
"<tr>"&_
"<td valign=center><b>"&strYAxisLabel&"</td>"&_
"<td valign=top>"&_
"<table border="&tbl_BORDER&" cellspacing=0 cellpadding=0>"&_
"<tr>"&_
"<td rowspan=2><img src=""images/spacer.gif"" border=0 width=1 height="&gr_HEIGHT&"></td>"&_
"<td valign=top align=right>"&iMaxValue&" </td>"&_
"</tr>"&_
"<tr><td valign=bottom align=right>. </td></tr>"&_
"</table>"&_
"</td>"&_
"<td>"&_
"<table border="&tbl_BORDER&" cellspacing=0 cellpadding=0>"&_
"<tr>"&_
"<td valign=bottom><img src=""images/spacer_black.gif"" border=0 width="&gr_BORDER&" height="&gr_HEIGHT&"></td>"
For I = 0 To UBound(aValues)
iBarHeight = Int((aValues(I) / iMaxValue) * gr_HEIGHT)
If iBarHeight = 0 Then iBarHeight = 1
Response.Write"<td valign=bottom><img src=""images/spacer.gif"" border=0 width="&gr_SPACER&" height=1></td>"&_
"<td valign=bottom><img src=""images/spacer_red.gif"" border=0 width="&iBarWidth&" height="&iBarHeight&" alt="""&aValues(I)&"""></a></td>"
Next
Response.Write"</tr>"&_
"<tr><td colspan="&(2*(UBound(aValues)+1))+1&"><img src=""images/spacer_black.gif"" border=0 width="&gr_BORDER+((UBound(aValues)+1)*(iBarWidth+gr_SPACER))&" height="&gr_BORDER&"></td></tr>"
If IsArray(aLabels) Then
Response.Write"<tr><td> </td>"
For I = 0 To UBound(aValues)
Response.Write"<td> </td><td align=center><font size=1>"&aLabels(I)&"</td>"
Next
Response.Write"</tr>"
End If
Response.Write"</table></td></tr><tr><td colspan=2> </td><td align=center><br><b>"&strXAxisLabel&"</td></tr></table>"
End Sub
%>
<html><body bgcolor=white>
<%
ShowChart Array(6, 10, 12, 18, 23, 26, 27, 28, 30, 34, 37, 45, 55), Array("P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8", "P9", "P10", "P11", "P12", "P13"), "Chart Title", "X Label", "Y Label"
Response.Write"<br><br><br>"
Randomize
For I = 0 To 49
aTemp(I) = Int((50+1)*Rnd)
Next
ShowChart aTemp, "Note that this ain't an Array!", "Chart of 50 Random Numbers", "Index", "Value"
%>
</body></html>


Printing the data coming through an InputStream without copying that data into memory first

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class DebugInputStream extends FilterInputStream {

private OutputStream debugOut;

public DebugInputStream(InputStream in, OutputStream debugOut) {
super(in);
this.debugOut = debugOut;
}

public int read() throws IOException {
int c = super.read();
debugOut.write((char) c);
return c;
}

public int read(byte[] b) throws IOException {
int readCount = super.read(b);
for (int i = 0; i < readCount; i++) {
debugOut.write((char) b[i]);
}
return readCount;
}

public int read(byte[] b, int offset, int length) throws IOException {
int readCount = super.read(b, offset, length);
int readTo = offset + readCount;
for (int i = offset; i < readTo; i++) {
debugOut.write((char) b[i]);
}
return readCount;
}

}


Writer implementation which provides a means for writing directly to a JTextArea

import java.io.Writer;
import java.io.IOException;

import javax.swing.JTextArea;

/** A implementation of the java.io.Writer class which facilitates writing to a JTextArea via a stream.

<p><b>Note:</b> There appears to be bug in the Macintosh implementation of
the JDK 1.1 where a PrintWriter writing to this class will not include the
correct line feeds for display in a JTextArea. There is a simple test of
the "java.version" system property which, if it starts with the String "1.1"
will cause newlines to be written each time the buffer is flushed.</p>

@author Anthony Eden
*/

public class JTextAreaWriter extends Writer{

private boolean closed = false;
private JTextArea textArea;
private StringBuffer buffer;

/** Constructor.

@param textArea The JTextArea to write to.
*/

public JTextAreaWriter(JTextArea textArea){
setTextArea(textArea);
}

/** Set the JTextArea to write to.

@param textArea The JTextArea
*/

public void setTextArea(JTextArea textArea){
if(textArea == null){
throw new IllegalArgumentException("The text area must not be null.");
}
this.textArea = textArea;
}

/** Close the stream. */

public void close(){
closed = true;
}

/** Flush the data that is currently in the buffer.

@throws IOException
*/

public void flush() throws IOException{
if(closed){
throw new IOException("The stream is not open.");
}
// the newline character should not be necessary. The PrintWriter
// should autmatically put the newline, but it doesn't seem to work
textArea.append(getBuffer().toString());
if(System.getProperty("java.version").startsWith("1.1")){
textArea.append("\n");
}
textArea.setCaretPosition(textArea.getDocument().getLength());
buffer = null;
}

/** Write the given character array to the output stream.

@param charArray The character array
@throws IOException
*/

public void write(char[] charArray) throws IOException{
write(charArray, 0, charArray.length);
}

/** Write the given character array to the output stream beginning from
the given offset and proceeding to until the given length is reached.

@param charArray The character array
@param offset The start offset
@param length The length to write
@throws IOException
*/

public void write(char[] charArray, int offset, int length) throws IOException{
if(closed){
throw new IOException("The stream is not open.");
}
getBuffer().append(charArray, offset, length);
}

/** Write the given character to the output stream.

@param c The character
@throws IOException
*/

public void write(int c) throws IOException{
if(closed){
throw new IOException("The stream is not open.");
}
getBuffer().append((char)c);
}

/** Write the given String to the output stream.

@param string The String
@throws IOException
*/

public void write(String string) throws IOException{
if(closed){
throw new IOException("The stream is not open.");
}
getBuffer().append(string);
}

/** Write the given String to the output stream beginning from the given offset
and proceeding to until the given length is reached.

@param string The String
@param offset The start offset
@param length The length to write
@throws IOException
*/

public void write(String string, int offset, int length) throws IOException{
if(closed){
throw new IOException("The stream is not open.");
}
getBuffer().append(string.substring(offset, length));
}

// protected methods

/** Get the StringBuffer which holds the data prior to writing via
a call to the <code>flush()

method. This method should
never return null.

@return A StringBuffer
*/

protected StringBuffer getBuffer(){
if(buffer == null){
buffer = new StringBuffer();
}
return buffer;
}

}


Sending Mail

/*
This code requires JavaMail. Specifically it requires mailapi.jar
and smtp.jar from the JavaMail distribution (available
at http://java.sun.com/) as well as activation.jar from the
JavaBeans Activation Framework (available
at http://java.sun.com/beans/glasgow/jaf.html).
*/

Properties props = new Properties();
props.put("mail.smtp.host", "your-smtp-host.com");
Session session = Session.getDefaultInstance(props, null);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setContent(message, "text/plain");
Transport.send(msg);


Find files in zip, jar, war, ear and nested archives

// The following java class takes two arguments; a directory name and a regular expression. The directory is searched for files matching the regexp. Zip files (and zip-alikes) are also searched including nested zips.

import java.io.*;
import java.util.*;
import java.util.zip.*;

public class Finder {
public static void main(String[] args) throws Exception {
String path = args[0];
final String expr = args[1];

List l = new ArrayList();
findFile(new File(path), new P() {
public boolean accept(String t) {
return t.matches(expr) isZip(t);
}
}, l);

List r = new ArrayList();
for (Iterator it = l.iterator(); it.hasNext();) {
File f = (File) it.next();
String fn = f + "";
if (fn.matches(expr)) r.add(fn);
if (isZip(f.getName())) {
findZip(fn, new FileInputStream(f), new P() {
public boolean accept(String t) {
return t.matches(expr);
}
}, r);
}
}

for (Iterator it = r.iterator(); it.hasNext();) {
System.out.println(it.next());
}
}

static void findFile(File f, P p, List r) {
if (f.isDirectory()) {
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++) findFile(files[i], p, r);
} else if (p.accept(f + "")) {
r.add(f);
}
}

static void findZip(String f, InputStream in, P p, List r) throws IOException {
ZipInputStream zin = new ZipInputStream(in);

ZipEntry en;
while ((en = zin.getNextEntry()) != null) {
if (p.accept(en.getName())) r.add(f + "!" + en);
if (isZip(en.getName())) findZip(f + "!" + en, zin, p, r);
}
}

static String[] ZIP_EXTENSIONS = { ".zip", ".jar", ".war", ".ear" };

static boolean isZip(String t) {
for (int i = 0; i < ZIP_EXTENSIONS.length; i++) {
if (t.endsWith(ZIP_EXTENSIONS[i])) {
return true;
}
}
return false;
}

static interface P {
public boolean accept(String t);
}
}


Read a properties file inside jar file

String sConfigFile = "config/mail.properties";
InputStream in = mailSender.class.getClassLoader().getResourceAsStream(sConfigFile);
if (in == null) {
// File not found! (Manage the problem)
}
Properties props = new java.util.Properties();
props.load(in);


Reads the given filename into a string. Path handling is not too good and buffer sizes are hardcoded right now

/** @param filePath the name of the file to open. Not sure if it can accept URLs or just filenames. Path handling could be better, and buffer sizes are hardcoded
*/
private static String readFileAsString(String filePath)
throws java.io.IOException{
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = new BufferedReader(
new FileReader(filePath));
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
return fileData.toString();
}

// insert code here..


Round in Java

Math.ceil(1.1); // Returns 2
Math.ceil(1.9); // Returns 2
Math.floor(1.1); // Returns 1
Math.floor(1.9); // Returns 1


Sort Vectors of objects in Java

// Your object must implement the interface Comparable
// For example:
public class Link implements Comparable {
String id_link = "";
public int compareTo(java.lang.Object o) {
// Here you can put your code for compare two objects. Something like this:
Link tmp = (Link) o;
return this.getId_link().compareTo(tmp.getId_link());
}
}
// Sorting the Vector:
java.util.Collections.sort(myVector);


Recursive listFiles with filter

// Java's File class provides listFiles for listing all files in a directory but this does not recurse into subdirectories. This implementation does with an optional filter:

// NB: This uses Java5 features such as foreach loop and generics but these can be removed to work with Java4 (see comments)

public static File[] listFilesAsArray(
File directory,
FilenameFilter filter,
boolean recurse)
{
Collection<File> files = listFiles(directory,
filter, recurse);
// Java4: Collection files = listFiles(directory, filter, recurse);

File[] arr = new File[files.size()];
return files.toArray(arr);
}

public static Collection<File> listFiles(
// Java4: public static Collection listFiles(
File directory,
FilenameFilter filter,
boolean recurse)
{
// List of files / directories
Vector<File> files = new Vector<File>();
// Java4: Vector files = new Vector();

// Get files / directories in the directory
File[] entries = directory.listFiles();

// Go over entries
for (File entry : entries)
{
// Java4: for (int f = 0; f < files.length; f++) {
// Java4: File entry = (File) files[f];

// If there is no filter or the filter accepts the
// file / directory, add it to the list
if (filter == null filter.accept(directory, entry.getName()))
{
files.add(entry);
}

// If the file is a directory and the recurse flag
// is set, recurse into the directory
if (recurse && entry.isDirectory())
{
files.addAll(listFiles(entry, filter, recurse));
}
}

// Return collection of files
return files;
}


Open a JDBC connection

//This opens a JDBC connection givine a driver class name, database URL, user name and password. It is possible this method is deprecated and some newer procedure is preferred. I need to look into that.

/*
** driverClass is the JDBC driver class name as a String.
*/

try
{
Class.forName (driverClass);
connection = DriverManager.getConnection (url,
userName, password);
connection.setAutoCommit (false);
}
catch (SQLException ex)
{
/*
** "Connect error"...
*/
}
catch (java.lang.ClassNotFoundException ex)
{
/*
** "Driver error"...
*/
}


Pass more than one parameter to struts action using html:link tag

<bean:define id="param1" name="recogida" property="fechaRuta" type="java.lang.String"/>
<bean:define id="param2" name="recogida" property="ruta" type="java.lang.String"/>
<%
java.util.HashMap params = new java.util.HashMap();
params.put("index", index);
params.put("fecha_ruta", param2);
params.put("ruta", param1);
pageContext.setAttribute("paramsName", params);
%>
<html:link styleClass='linkazulC' action="/pgActDetRecogidaT" name="paramsName">
<bean:message key="etiqueta.relacionRecogidasG.detalle" />
</html:link>


Obtain highest day of a month

//f.e: get highest day of february/2006//Months starts at 0 and ends at 11!!
Calendar cal = GregorianCalendar.getInstance();cal.set(2006, 1, 1);System.out.println("Highest day: " + cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH));


Simple Mouse Wheel support for GWT

source : http://www.bigbold.com/snippets/user/sligowaths

public interface MouseWheelListener {
public void onMouseWheelUp(int intensity);
public void onMouseWheelDown(int intensity);
}

public class MouseWheel {
private MouseWheel(Element e, MouseWheelListener listener) {
attachMouseWheelListener(e, listener);
}


/**
* Sets a MouseWheelListener to a given Element
*/

public static void setMouseWheelListener(Element e, MouseWheelListener listener) {
new MouseWheel(e, listener);
}

/**
* This method is used by FF
* @param event
*/

private static native void dispatchMouseWheelEvent(JavaScriptObject event) /*-{
@br.com.example.client.util.MouseWheel::dispatchMouseWheelEvent(Lcom/google/gwt/core/client/JavaScriptObject;Lbr/com/example/client/util/MouseWheelListener;)(event, this.__mousewheellistener);
}-*/;


/**
* This method is used by IE and FF
* Part of this method was retrieved from http://adomas.org/notes/mouse-wheel.html
*
* @param event
* @param listener
*/

private static native void dispatchMouseWheelEvent(JavaScriptObject event, MouseWheelListener listener) /*-{
if (!event) event = $wnd.event; // For IE

var delta = 0;
if (event.wheelDelta) // IE case, delta is multiple of 120
delta = event.wheelDelta / 120;
else if (event.detail ) // Mozilla case
delta = -event.detail / 3; // different sign and multiple of 3

if ( delta > 0 ) {
listener.@br.com.example.client.util.MouseWheelListener::onMouseWheelUp(I)(delta);
} else {
listener.@br.com.example.client.util.MouseWheelListener::onMouseWheelDown(I)(-delta);
}
}-*/;

private native void attachMouseWheelListener(Element e, MouseWheelListener listener) /*-{
e.__mousewheellistener = listener;
// for FF
if (e.addEventListener) {
e.addEventListener('DOMMouseScroll', @br.com.example.client.util.MouseWheel::dispatchMouseWheelEvent(Lcom/google/gwt/core/client/JavaScriptObject;), false);
return;
}
// for IE
e.onmousewheel = function(event) {
@br.com.example.client.util.MouseWheel::dispatchMouseWheelEvent (Lcom/google/gwt/core/client/JavaScriptObject;Lbr/com/example/client/util/MouseWheelListener;)(event, this.__mousewheellistener);
}
}-*/;
}

And here is how to use it:
MouseWheel.setMouseWheelListener(RootPanel.get("slot2").getElement(), new MouseWheelListener() {
public void onMouseWheelUp(int intensity) {
Window.alert("up.. " + intensity);
}

public void onMouseWheelDown(int intensity) {
Window.alert("down..." + intensity);
}
});

Remember to replace my hardcoded package name (br.com.example) for your own..


Accessing private methods and fields of a Java class

//This class uses reflection to enable you to invoke private methods on a class, or access its private fields. This can be useful for unit testing.
import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;
import junit.framework.Assert;
/** * Provides access to private members in classes. */public class PrivateAccessor {
public static Object getPrivateField (Object o, String fieldName) { // Check we have valid arguments... Assert.assertNotNull(o); Assert.assertNotNull(fieldName);
// Go and find the private field... final Field fields[] = o.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; ++i) { if (fieldName.equals(fields[i].getName())) { try { fields[i].setAccessible(true); return fields[i].get(o); } catch (IllegalAccessException ex) { Assert.fail ("IllegalAccessException accessing " + fieldName); } } } Assert.fail ("Field '" + fieldName +"' not found"); return null; }
public static Object invokePrivateMethod (Object o, String methodName, Object[] params) { // Check we have valid arguments... Assert.assertNotNull(o); Assert.assertNotNull(methodName); Assert.assertNotNull(params);
// Go and find the private method... final Method methods[] = o.getClass().getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (methodName.equals(methods[i].getName())) { try { methods[i].setAccessible(true); return methods[i].invoke(o, params); } catch (IllegalAccessException ex) { Assert.fail ("IllegalAccessException accessing " + methodName); } catch (InvocationTargetException ite) { Assert.fail ("InvocationTargetException accessing " + methodName); } } } Assert.fail ("Method '" + methodName +"' not found"); return null; }}


Find an Images Dimensions

<%
dim iWidth, iHeight, iType
sub ImgDimension(img)
dim myImg, fs
Set fs= CreateObject("Scripting.FileSystemObject")
if not fs.fileExists(img) then exit sub
set myImg = loadpicture(img)
iWidth = round(myImg.width / 26.4583)
iHeight = round(myImg.height / 26.4583)
iType = myImg.Type
select case iType
case 0
iType = "None"
case 1
iType = "Bitmap"
case 2
iType = "Metafile"
case 3
iType = "Icon"
case 4
iType = "Win32-enhanced metafile"
end select
set myImg = nothing
end sub

' so if you whant to test it in asp just give the path to your image
ImgDimension(Server.MapPath("../.") & "\images\header.gif")

response.write("Dimensions: " & iWidth & " x " & iHeight & "<br>")
response.write("Image Type: " & iType & "<br>")


Validate Email Addresses using Regex in ASP

<%
'our function to check email addresses
'a fantastic list of regular expressions
Function CheckMail(strEmail)
'our variables
Dim objRegExp , blnValid
'create a new instance of the RegExp object , note we do not need Server.CreateObject("")
Set objRegExp = New RegExp
'this is our pattern we check .
objRegExp.Pattern = "^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}[0-9]{1,3})(\]?)$"
'store the result either true or false in blnValid
blnValid = objRegExp.Test(strEmail)
If blnValid Then
'display this if it is a vlid email address
Response.Write "This is a valid email address<br>"
Else
'display this if it is an invalid email address
Response.Write "That email address is invalid<br>"
End If
End Function
%>
<%CheckMail("validmail@email.com") 'correct email address %>
<%CheckMail("invalid1") 'incorrect , many errors%>
<%CheckMail("invalid+email.com") 'invalid + sign instead of @%>
<%CheckMail("invalid@email,com") 'invalid , sneaky uses a comma instead of a full stop%>


Testing for the XMLHTTP Request object

<% Option Explicit %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>XMLHTTP Request Object</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<%
'put the objects that we wish to test for into a declared array
Dim InstalledObjects(4)

InstalledObjects(0) ="Microsoft.XMLHTTP"
InstalledObjects(1) ="Msxml2.ServerXMLHTTP"
InstalledObjects(2) ="MSXML2.ServerXMLHTTP"
InstalledObjects(3) ="MSXML2.XMLHTTP.3.0"
InstalledObjects(4) ="MSXML2.XMLHTTP.4.0"

Function ObjCreated(sClass)
'create variable
Dim ObjInstance
On Error Resume Next
'initialize default values
ObjCreated = False
'create instance of the class - an object
Set ObjInstance = Server.CreateObject(sClass)
If Err.Number=0 Then ObjCreated = True
'close object
Set ObjInstance = Nothing
Err.Clear
End Function
%>
<table border="0">
<%
Dim i
For i=0 to UBound(InstalledObjects)
Response.Write "<tr><td>" & InstalledObjects(i) & "</td><td>"
If ObjCreated(InstalledObjects(i)) Then
Response.Write "<strong>Installed</strong>"
Else
Response.Write "<strong>not installed</strong>"
End If
Response.Write "</td></tr>"
Next
%>
</table>
</body>
</html>


A Feedback Form Script

<html>
<head>
<title>Feedback Form</title>
</head>
<body>

<%
'If the form has not been submitted execute the following code
If Request.Form="" Then %>
<form method="post" action="feedback.asp" name="form1">
<div align="center">Send us your Feedback.<br>
<br>
</div>
<div align="center">
<table width="75%" border="0">
<tr>
<td>name</td>
<td>
<input type="text" name="txtName">
</td>
</tr>
<tr>
<td>email</td>
<td>
<input type="text" name="txtEmail">
</td>
</tr>
<tr>
<td>comment</td>
<td>
<textarea name="txtFeedback" cols="40" rows="7"></textarea>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>
<input type="submit" name="Submit" value="Submit">
<input type="reset" name="Reset" value="Reset">
</td>
</tr>
</table>
</div>
</form>
<br>
<%
'If the form has been submitted execute the following code
Else

'receive the form values
Dim sName, sEmail, sFeedback
sName=Request.Form("txtName")
sEmail=Request.Form("txtEmail")
sFeedback=Request.Form("txtFeedback")

' create the HTML formatted email text
Dim sEmailText
sEmailText = sEmailText & "<html>"
sEmailText = sEmailText & "<head>"
sEmailText = sEmailText & "<title>HTML Email</title>"
sEmailText = sEmailText & "</head>"
sEmailText = sEmailText & "<body>"
sEmailText = sEmailText & "Feedback message from: " & sName & "<br>"
sEmailText = sEmailText & "Message:" & sFeedback & "<br>"
sEmailText = sEmailText & "Date & Time:" & Now() & "<br>"
sEmailText = sEmailText & "IP :" & Request.ServerVariables("REMOTE_ADDR")
sEmailText = sEmailText & "</body>"
sEmailText = sEmailText & "</html>"

'create the mail object
Set NewMailObj=Server.CreateObject("CDONTS.NewMail")
NewMailObj.From=sEmail 'This is the email of the feedback sender
NewMailObj.To = "michael@codefixer.com" 'change to your address
NewMailObj.Subject = "Feedback"
NewMailObj.Body = sEmailText
'you need to add these 2 lines for the mail to be sent in HTML format
'remove them and the email will be sent in Text format
NewMailObj.BodyFormat = 0
NewMailObj.MailFormat = 0
NewMailObj.Send
Set NewMailObj=Nothing

Response.write "<div align='center'>Thank you for sending your feedback.<br>"
Response.write "We will get back to you if necessary.</div>"
End If
%>
</body>
</html>