PHP SMTP Authentication: send an email through an authenticated SMTP server @ 26-09-2007 22:25
Author: Matthew R. Miller,
http://www.bytemycode.com/snippets/snippet/223/<?php
function mymail($to,$subject,$message,$headers)
{
// set as global variable
global $GLOBAL;
// get From address
if ( preg_match("/From:.*?[A-Za-z0-9\._%-]+\@[A-Za-z0-9\._%-]+.*/", $headers, $froms) ) {
preg_match("/[A-Za-z0-9\._%-]+\@[A-Za-z0-9\._%-]+/", $froms[0], $fromarr);
$from = $fromarr[0];
}
// Open an SMTP connection
$cp = fsockopen ($GLOBAL["SMTP_SERVER"], $GLOBAL["SMTP_PORT"], &$errno, &$errstr, 1);
if (!$cp)
return "Failed to even make a connection";
$res=fgets($cp,256);
if(substr($res,0,3) != "220") return "Failed to connect";
// Say hello...
fputs($cp, "HELO ".$GLOBAL["SMTP_SERVER"]."\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "250") return "Failed to Introduce";
// perform authentication
fputs($cp, "auth login\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "334") return "Failed to Initiate Authentication";
fputs($cp, base64_encode($GLOBAL["SMTP_USERNAME"])."\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "334") return "Failed to Provide Username for Authentication";
fputs($cp, base64_encode($GLOBAL["SMTP_PASSWORD"])."\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "235") return "Failed to Authenticate";
// Mail from...
fputs($cp, "MAIL FROM: <$from>\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "250") return "MAIL FROM failed";
// Rcpt to...
fputs($cp, "RCPT TO: <$to>\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "250") return "RCPT TO failed";
// Data...
fputs($cp, "DATA\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "354") return "DATA failed";
// Send To:, From:, Subject:, other headers, blank line, message, and finish
// with a period on its own line (for end of message)
fputs($cp, "To: $to\r\nFrom: $from\r\nSubject: $subject\r\n$headers\r\n\r\n$message\r\n.\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "250") return "Message Body Failed";
// ...And time to quit...
fputs($cp,"QUIT\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "221") return "QUIT failed";
return true;
}
?>
Extracts all email adresses from a given string, and returns them as array @ 26-09-2007 22:22
Author: Jonas John, http://codedump.jonasjohn.de/
<?php
/*
** Function: extract_emails (PHP)
** Desc: This function extracts all E-Mail adresses from a given string, and returns them as array.
** Author: Jonas John
*/
function extract_emails($str)
{
// This regular expression extracts all emails from
// a string:
$regexp = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
preg_match_all($regexp, $str, $m);
return isset($m[0]) ? $m[0] : array();
}
?>
Email address validator @ 26-09-2007 22:17
Author: Tobias Ratschiller & izzy, http://www.zend.com/tips/tips.php?id=224&single=1
<?php
/*
Original script by Tobias Ratschiller.
* top level domain must have at least 2 chars
* there can be more than one dot in the address
*/
function is_email($address) {
$rc1 = (ereg('^[-!#$%&'*+./0-9=?A-Z^_`a-z{}~]+'.
'@'.
'[-!#$%&'*+\/0-9=?A-Z^_`a-z{}~]+.'.
'[-!#$%&'*+\./0-9=?A-Z^_`a-z{}~]+$',
$address));
$rc2 = (preg_match('/.+.ww+$/',$address));
return ($rc1 && $rc2);
}
?>
Emailer Class @ 26-09-2007 22:09
author: edolecki, http://www.bigbold.com/snippets/tag/php/6
<?php
import mx.events.EventDispatcher;
import mx.utils.Delegate;
class Emailer {
// required for EventDispatcher:
public var addEventListener:Function;
public var removeEventListener:Function;
private var dispatchEvent:Function;
// use to communicate with php script
private var _lv:LoadVars;
// holds address of sender
private var _sentFrom:String;
// constructor
public function Emailer() {
EventDispatcher.initialize(this);
_lv = new LoadVars();
}
//
private function dataReceived(dataxfer_ok:Boolean):Void {
// if some problem with loadVars transfer, pass back error=2
if (!dataxfer_ok) dispatchEvent({target:this, type:'mailSent', errorFlag:2});
// otherwise pass back error code returned from script
else dispatchEvent({target:this, type:'mailSent', errorFlag:Number(_lv["faultCode"])});
}
// Use loadvars object to send data (set to call dataReceived when script returns data)
public function sendEmail(sub:String, fn:String, fe:String, msg:String, rep:String):Void {
// if user already sent from this address, show error msg
if (_sentFrom == fe) dataReceived(false);
// otherwise set up and send
else {
_sentFrom = fe;
// specify function to handle results, make scope = Emailer
_lv.onLoad = Delegate.create(this, dataReceived);
// set up properties of lv to items to be POSTed
_lv.subject = sub;
_lv.name = fn;
_lv.email = fe;
_lv.message = msg;
_lv.reply = rep;
// call script
_lv.sendAndLoad("sendemail.php", _lv, "POST");
}
}
}
?>
Asp Report Maker @ 06-09-2007 15:14

- Detail and Summary Report
- Crosstab Report
- Simple Charts
- Advanced Security
- Export to HTML/Excel/Word
- Custom View
- Customizable Template
- Database Synchronization
demo
Asp XmlMaker @ 06-09-2007 15:09

- Field as Element/Attribute
- Filtering and Sorting
- Master/Detail Data
- Field Value Formatting
- Null Value Handling
- Custom View
- Customizable Template
- Template Extensions
- Database Synchronization
demo
Jsp Maker @ 06-09-2007 15:05

- Create JSP for all tables
- Form validation
- User authentication
- Database re-synchronization
- Quick Generate Wizard
- Customizable template
- Master/Detail
- File upload to folder or database
- CSS stylesheet
- Field Aggregation
demo
Php maker @ 06-09-2007 15:01

* Advanced Security
* User registration system
* Export to CSV/HTML/Excel/Word/XML
* File uploading to database or folder
* Master/Detail
* Custom View
* Report
* Customizable template
* Database re-synchronization
Demo
Asp.net Maker @ 06-09-2007 14:52

* All ASP.NET 2.0 scripts linked up properly
* Optional list, add/copy, view, edit, delete and search pages for each table/view. (See
Table Setup) Customizable table display order.
* Fully customizable View and Edit format for each field. (See
Field Setup) Customizable field display order.
* Various ASP.NET validators
* Optional search features (Basic/Advanced/Both) for each table/view
* Optional Advanced Security to protect data from unauthorized access (See
Security Settings)
Complete user registration system
* Optional HTML settings. Charset, font, CSS, HTML colors, HTML table settings with preview. (See
HTML Settings)
* Fully customizable template
* Master/Detail pages
* Various ASP.NET options (See
ASP.NET Settings)
* Saving and restoring project from
Project File*
Synchronizes project settings with changes in database.
* Creates virtual directory in IIS automatically
* Cassini or IIS as testing web server
* CSS stylesheet integration
* Field aggregation (sum, average and count)
* Custom View with built-in visual query builder
* Basic reporting
* ASP.NET inline editing
* Export to HTML/Word/Excel/CSV/XML
* Multi-column Sorting
* User Selectable Page Size
* Table-specific List Page Options
* File Uploading to Folder and Database
* Dynamic Table Loading
* Composite key
* Inline Delete
* Highlight and select row color
* Auto suggest textbox (ASP.NET AJAX)
* Adding option to Selection List (ASP.NET AJAX)
* Dynamic Selection List (ASP.NET AJAX)
* Dynamic User Levels
* Parent User ID
* Auto-login
* Extended quick search
* Multi-page update
* Fully customizable template and extensions
* Audit trail and email notification on Add/Edit/Delete
demo
Aptana ide @ 05-09-2007 23:39

Aptana is a robust, JavaScript-focused IDE for building dynamic web applications.Highlights
include the following features:
* Code Assist on JavaScript, HTML, and CSS languages, including your own JavaScript functions *Outliner that gives a snapshot view of your JavaScript, HTML, and CSS code structure
* FTP/SFTP uploading, downloading and synchronization
* JavaScript debugger to troubleshoot your code
* Error and warning notification for your code
* Support for Aptana UI customization and extensions
* Cross-platform support
* Free and source open under the
Aptana Public License, v1.0.
* Please note that milestone 9 is still a preview release
Asp express 5.0 @ 26-08-2007 16:31

- 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 @ 26-08-2007 16:15

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
Print Exception Class Hieararchy @ 23-08-2007 10:15
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 @ 23-08-2007 10:12
Source:
http://stephan.walter.name/Ruby_snippetsmodule 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 @ 23-08-2007 10:06
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 @ 23-08-2007 10:01
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(/"/, "'").gsub(/</, "<").gsub(/>/, ">").gsub(/&/, "&")
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 @ 23-08-2007 09:55
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
How to Find the Current URL with PHP @ 22-08-2007 12:16
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;
?>
Encrypting data from one stream to another and attaching hash of the password @ 18-08-2007 19:12
resource:
http://devdistrict.com/CodeDetails.aspx?A=54using 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 @ 18-08-2007 19:09
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];
}
}
Use VB Component in C# @ 15-08-2007 17:10
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
Using Cryptography to Encrypt Data in ASP.NET @ 13-08-2007 21:37
'author: Wayne Plourde ,
http://www.15seconds.com/issue/021210.htmImports 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 @ 13-08-2007 21:34
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 @ 13-08-2007 21:31
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 @ 13-08-2007 21:25
--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