pl/sql 常用语法

1、procedure

CREATE [ OR REPLACE] PROCEDURE [schema.]procedure_name
[parameter_lister]
{AS|IS}
declaration_section
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name]
--举例
create or replace
procedure dos_fx
is
cursor c1 is
select get from dos_gj;
begin
 for c2 in c1 loop
 insert into dos_gj_1(ip,gettime,get)values(REGEXP_SUBSTR( c2.get, '(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3} '),
 REGEXP_SUBSTR( c2.get, '^(\d{4})-(\d{2})-(\d{2}) (\d{2}:\d{2}:\d{2})'),c2.get);
 end loop;
 commit;
end;

2、function

CREATE [ OR REPLACE] FINCTION [schema.]function_name
[parameter_list]
RETURN returning_datatype
{AS|IS}
declaration_section
BEGIN
executable_section
[EXCEPTION]
exception_section
END [procedure_name]
--举例
CREATE OR REPLACE function fn_md5(input_string VARCHAR2) return varchar2
IS
raw_input RAW(128) := UTL_RAW.CAST_TO_RAW(input_string);
decrypted_raw RAW(2048);
error_in_input_buffer_length EXCEPTION;
BEGIN
sys.dbms_obfuscation_toolkit.MD5(input => raw_input,checksum => decrypted_raw);
return rawtohex(decrypted_raw);
END;

3、package

--header
CREATE [OR REPLACE] PACKAGE package_name
{AS|IS}
public_variable_declarations |
public_type_declarations |
public_exception_declarations |
public_cursor_declarations |
function_declarations |
procedure_specifications
END [package_name]
--body
CREATE [OR REPLACE] PACKAGE BODY package_name
{AS|IS}
private_variable_declarations |
private_type_declarations |
private_exception_declarations |
private_cursor_declarations |
function_declarations |
procedure_specifications
END [package_name]
--举例
--header
create or replace
package pk_t1
as
procedure get_num(getnum in number,aname varchar2);
end pk_t1;
--body
create or replace
package body pk_t1
as
procedure get_num(getnum in number,aname varchar2)
is
begin
 insert into shell_1 values(getnum,aname);
end;
end pk_t1;

4、trigger

CREATE [OR REPLACE] TRIGGER trigger_name
{before|after|instead of} event
ON {table_or_view_name|DATABASE}
[FOR EACH ROW[WHEN condition]]
trigger_body
--举例
create or replace trigger add_shell
before update
on shell_1 for each row
declare
begin
 if :OLD.name!=:new.name then
  :new.name:='ggggg';
 end if;
end;

oracle 开机自动启动

一、使用root用户修改/etc/oratab 文件:
$ vi /etc/oratab
orcl:/u01/oracle:N (ORACLE_SID:ORACLE_HOME:N)
改为:
orcl:/u01/oracle:Y 也就是将最后的N改为Y
二、使用Oracle用户修改$ORACLE_HOME/bin/dbstart和dbstop文件:
ORACLE_HOME_LISTNER=$1
改为:
ORACLE_HOME_LISTNER=$ORACLE_HOME
三、创建服务
$su – root
# cd /etc/rc.d/init.d/
# vi oradb
在oradb中添加文本

#!/bin/bash
# chkconfig: 345 99 10
# description: Startup Script for Oracle Databases
export ORACLE_BASE=/u01
export ORACLE_HOME=/u01/oracle
export ORACLE_SID=orcl
export PATH=$PATH:$ORACLE_HOME/bin
ORA_OWNR="oracle"
# if the executables do not exist -- display error
if [ ! -f $ORACLE_HOME/bin/dbstart -o ! -d $ORACLE_HOME ]
then
echo "Oracle startup: cannot start"
exit 1
fi
# depending on parameter -- startup, shutdown, restart
# of the instance and listener or usage display
case "$1" in
start)
# Oracle listener and instance startup and oem
echo -n "Starting Oracle: "
# 启动listener and instance
su - $ORA_OWNR -c "$ORACLE_HOME/bin/dbstart"
touch /var/lock/Oracle
# 启动oem
su - $ORA_OWNR -c "$ORACLE_HOME/bin/emctl start dbconsole"
echo "OK"
;;
stop)
# Oracle listener and instance shutdown and oem
echo -n "Shutdown Oracle: "
# 关闭oem
su - $ORA_OWNR -c "$ORACLE_HOME/bin/emctl stop dbconsole"
# 关闭数据库和listener
su - $ORA_OWNR -c "$ORACLE_HOME/bin/dbshut"
rm -f /var/lock/Oracle
echo "OK"
;;
reload|restart)
$0 stop
$0 start
;;
*)
echo "Usage: `basename $0` start|stop|restart|reload"
exit 1
esac
exit 0

修改所属组和用户
#chown oracle.oinstall /etc/rc.d/init.d/oradb
修改访问权限
#chmod 775 /etc/rc.d/init.d/oradb
添加服务到自动启动中
#chkconfig –add oradb
查看数据库服务开机启动状态
#chkconfig –list oradb
四、# chkconfig: 345 99 10说明
指出3,4,5级别启动这个服务,99是在相应的/etc/rc.d/rcN.d(N为前面指定的级别,这里是345)目录下生成的链接文件的序号(启动优先级别)S99oradbstart,10为在除前面指出的级别对应的/etc/rc.d/rcN.d(N为除345之外的级别)目录生成的链接文件的序号(服务停止的优先级别)

oracle物化视图

一、创建物化视图主要语法

 create materialized view [view_name]
     {TABLESPACE (表空间名)}--保存表空间
     {BUILD [DEFERRED|IMMEDIATE(默认值)]} --延迟刷新还是立即刷新
refresh [fast|complete|force]
[
on [commit|demand] |
start with (start_time) next (next_time)
]
as
{创建物化视图用的查询语句}

二、相关参数说明
创建物化视图主要选项说明
创建物化视图时可以指定多种选项,下面对几种主要的选项进行简单说明:

名称 ON PREBUILD TABLE
描述 将已经存在的表注册为实体化视图。同时还必须提供描述创建该表的查询的 SELECT 子句。可能无法始终保证查询的精度与表的精度匹配。为了克服此问题,应该在规范中包含 WITH REDUCED PRECISION 子句。
名称 Build Clause 创建方式
描述 包括BUILD IMMEDIATE和BUILD DEFERRED两种
取值 BUILD IMMEDIATE 在创建实体化视图的时候就生成数据
BUILD DEFERRED 在创建时不生成数据,以后根据需要在生成数据
默认 BUILD IMMEDIATE
名称 Refresh 刷新子句
描述 当基表发生了DML操作后,实体化视图何时采用哪种方式和基表进行同步
语法
[refresh [fast | complete | force]
         [on demand | commit]
         [start with date]
         [next date]
         [with {primary key | rowid}]
]
取值 FAST 采用增量刷新,只刷新自上次刷新以后进行的修改
COMPLETE 对整个物化视图进行完全的刷新
FORCE(默认) Oracle在刷新时会去判断是否可以进行快速刷新,如果可以则采用Fast方式,否则采用Complete的方式,Force选项是默认选项
ON DEMAND(默认) 物化视图在用户需要的时候进行刷新,可以手工通过DBMS_MVIEW.REFRESH等方法来进行刷新,也可以通过JOB定时进行刷新
ON COMMIT 实体化视图在对基表的DML操作提交的同时进行刷新
START WITH 第一次刷新时间
NEXT 刷新时间间隔
WITH PRIMARY KEY(默认) 生成主键实体化视图,也就是说实体化视图是基于表的主键,而不是ROWID(对应于ROWID子句)。 为了生成PRIMARY KEY子句,应该在表上定义主键,否则应该用基于ROWID的实体化视图。主键实体化视图允许识别实体化视图表而不影响实体化视图增量刷新的可用性
WITH ROWID 只有一个单一的主表,不能包括下面任何一项:
●Distinct
●聚合函数
●Group by
●子查询
●连接
●SET操作
名称 Query Rewrite 查询重写
描述 包括ENABLE QUERY REWRITE和DISABLE QUERY REWRITE两种。分别指出创建的实体化视图是否支持查询重写。查询重写是指当对实体化视图的基表进行查询时,Oracle会自动判断能否通过查询实体化视图来得到结果,如果可以,则避免了聚集或连接操作,而直接从已经计算好的实体化视图中读取数据
取值 ENABLE QUERY REWRITE 支持查询重写
DISABLE QUERY REWRITE 不支持查询重写
默认 DISABLE QUERY REWRITE

创建实体化试图日志主要选项说明
如果需要进行快速刷新,则需要建立实体化视图日志。实体化视图日志根据不同实体化视图的快速刷新的需要,可以建立为ROWID或PRIMARY KEY类型的。还可以选择是否包括SEQUENCE、INCLUDING NEW VALUES以及指定列的列表。

名称 WITH Clause
描述
取值 OBJECT ID 如果是对象实体化视图(object materialized view),则只能采用该方式
PRIMARY KEY
ROWID
SEQUENCE
默认 PRIMARY KEY

三、举例说明
1、简单示例

 create materialized view MV_except_pattern_orders
refresh Complete on demand
      start with to_date('2010-11-06 13:20:51','YYYY-MM-DD HH24:MI:SS') next sysdate+1/(24*60)
as
    select * from v_except_pattern_orders

2、带日志物化视图

--创建物化视图日志
create materialized view log on table1
tablespace ts_data --日志保存在特定的表空间
with rowid;
--创建物化视图主体
create materialized view MV_LVY_LEVYDETAILDATA
TABLESPACE ZGMV_DATA --保存表空间
BUILD DEFERRED --延迟刷新不立即刷新
refresh force --如果可以快速刷新则进行快速刷新,否则完全刷新
on demand --按照指定方式刷新
start with to_date('24-11-2005 18:00:10', 'dd-mm-yyyy hh24:mi:ss') --第一次刷新时间
next TRUNC(SYSDATE+1)+18/24 --刷新时间间隔
as
as select * from table1;

sql server中操作mysql

一、安装mysql官方的odbc驱动
mysql-connector-odbc-5.1.7-win32 myodbc驱动补丁(由于驱动自身有bug,发布了补丁)
二、配置odbc

三、创建mysql链接服务

EXEC sp_addlinkedserver 'MySQL50','','MSDASQL','mysql5_test';
EXEC sp_addlinkedsrvlogin 'MySQL50','false','sa','root','4020894';

四、执行相关查询

--查询操作
SELECT TOP 3 * FROM OPENQUERY (MySQL50 ,'select * from abc  ' ) ORDER BY Access_Time desc;
--插入操作
INSERT INTO OPENQUERY (MySQL50, ' SELECT * FROM abc')
values('aaa', 'bbb','ccc','dddd','eeee','2010-11-4','ggggggg')
--更新操作
UPDATE OPENQUERY (MySQL50, 'SELECT Cur_url FROM abc WHERE Pre_url = ''bbb''')
SET Cur_url = 'feifei';
--删除操作
DELETE OPENQUERY (MySQL50, 'SELECT Cur_url FROM abc WHERE Pre_url = ''bbb''') 

ORACLE 外部表

一、简单创建外部表
1、简单模拟外部文件
10,20,30
40,50,60
70,80,90
2、创建外部表用户名和授权

create user test identified by “123” default tablespace test quota unlimited on test;
grant RESOURCE,create session,create any directory to test;

3、创建目录

conn test/"123"
create directory ext as '/sdb/orcl/file';

4、创建外部表

 create table exttable(
  id number,
     name varchar2(10),
     i number
)
organization external
 (
     type oracle_loader
  default directory ext
  access parameters
    (
         records delimited by newline
      fields terminated by ','
    )
     location('ext.dat')
 );

二、使用外部表管理alert文件

create directory alert as 'create directory bdump as '/oracle/u01/app/oracle/admin/db2/bdump';
create table alert_log
(
 text varchar2(400)
)
organization external
 (
     type oracle_loader
  default directory alert
  access parameters
  (
        records delimited by newline
  )
     location('alert_orcl.log')
 );
--查找到ora错误记录
select * from alert_log where TEXT like 'ORA-%';

oracle 建立分区表

从上次在亚旭培训的时候,我和dba讨论一次我开发系统中为了一张表不是非常的大,采用了动态sql创建多个部门的表,然后存取相应的数据,从而解决了一张表过大的问题。当时dba和我说了分区表,我第一感觉,如果当时我知道数据库还有这种表,那我当时开发起来应该轻松的多,后来就一直有个想法,去了解分区表,因为最近自己一直都比较忙,被琐事所困,今天晚上终于抽出了点时间,了解了相关的知识,并做了400多w条数据的一个分区表的测试。
一.范围分区
范围分区将数据基于范围映射到每一个分区,这个范围是你在创建分区时指定的分区键决定的。

--例一取值范围:
CREATE TABLE CUSTOMER
(
    CUSTOMER_ID NUMBER NOT NULL PRIMARY KEY,
    FIRST_NAME  VARCHAR2(30) NOT NULL,
    LAST_NAME   VARCHAR2(30) NOT NULL,
    PHONE        VARCHAR2(15) NOT NULL,
    EMAIL        VARCHAR2(80),
    STATUS       CHAR(1)
)
PARTITION BY RANGE (CUSTOMER_ID)
(
    PARTITION CUS_PART1 VALUES LESS THAN (100000) TABLESPACE CUS_TS01,
    PARTITION CUS_PART2 VALUES LESS THAN (200000) TABLESPACE CUS_TS02,
    PARTITION  CUS_PART3 VALUES  LESS  THEN (MAXVALUE) TABLESPACE  CUS_TS02
)
--例二按时间划分(随着时间的增长,还需要添加分区表):
CREATE TABLE ORDER_ACTIVITIES
(
    ORDER_ID      NUMBER(7) NOT NULL,
    ORDER_DATE    DATE,
    TOTAL_AMOUNT NUMBER,
    CUSTOTMER_ID NUMBER(7),
    PAID           CHAR(1)
)
PARTITION BY RANGE (ORDER_DATE)
(
  PARTITION ORD_ACT_PART01 VALUES LESS THAN (TO_DATE('01- MAY -2003','DD-MON-YYYY')) TABLESPACE ORD_TS01,
  PARTITION ORD_ACT_PART02 VALUES LESS THAN (TO_DATE('01-JUN-2003','DD-MON-YYYY')) TABLESPACE ORD_TS02,
  PARTITION ORD_ACT_PART03 VALUES LESS THAN (TO_DATE('01-JUL-2003','DD-MON-YYYY')) TABLESPACE ORD_TS03
)

二.列表分区
该分区的特点是某列的值只有几个,基于这样的特点我们可以采用列表分区。

--这个是我在自己电脑上测试的实例,一个sql竞赛的资料库中的数据
create table p_t2(a1 number,a2 varchar2(10),a3 varchar2(30),a4 varchar2(10),a5 number)
    partition by list(a2)
    (partition p_tcp  values('tcp') tablespace p1,
    partition p_udp  values('udp') tablespace p2,
    partition p_icmp  values('icmp') tablespace p3)

三.散列分区
这类分区是在列值上使用散列算法,以确定将行放入哪个分区中。当列的值没有合适的条件时,建议使用散列分区。
散列分区为通过指定分区编号来均匀分布数据的一种分区类型,因为通过在I/O设备上进行散列分区,使得这些分区大小一致。

CREATE TABLE HASH_TABLE
(
  COL NUMBER(8),
  INF VARCHAR2(100)
)
PARTITION BY HASH (COL)
(
  PARTITION PART01 TABLESPACE HASH_TS01,
  PARTITION PART02 TABLESPACE HASH_TS02,
  PARTITION PART03 TABLESPACE HASH_TS03
)
--简写:
CREATE TABLE emp
(
    empno NUMBER (4),
    ename VARCHAR2 (30),
    sal   NUMBER
)
PARTITION BY  HASH (empno) PARTITIONS 8
STORE IN (emp1,emp2,emp3,emp4,emp5,emp6,emp7,emp8);

四.组合范围散列分区
这种分区是基于范围分区和列表分区,表首先按某列进行范围分区,然后再按某列进行列表分区,分区之中的分区被称为子分区。

CREATE TABLE SALES
(
PRODUCT_ID VARCHAR2(5),
SALES_DATE DATE,
SALES_COST NUMBER(10),
STATUS VARCHAR2(20)
)
PARTITION BY RANGE(SALES_DATE) SUBPARTITION BY LIST (STATUS)
(
   PARTITION P1 VALUES LESS THAN(TO_DATE('2003-01-01','YYYY-MM-DD'))TABLESPACE rptfact2009
          (
              SUBPARTITION P1SUB1 VALUES ('ACTIVE') TABLESPACE rptfact2009,
              SUBPARTITION P1SUB2 VALUES ('INACTIVE') TABLESPACE rptfact2009
          ),
   PARTITION P2 VALUES LESS THAN (TO_DATE('2003-03-01','YYYY-MM-DD')) TABLESPACE rptfact2009
          (
              SUBPARTITION P2SUB1 VALUES ('ACTIVE') TABLESPACE rptfact2009,
              SUBPARTITION P2SUB2 VALUES ('INACTIVE') TABLESPACE rptfact2009
          )
)

五.复合范围散列分区
这种分区是基于范围分区和散列分区,表首先按某列进行范围分区,然后再按某列进行散列分区。

create table dinya_test
 (
 transaction_id number primary key,
 item_id number(8) not null,
 item_description varchar2(300),
 transaction_date date
 )
 partition by range(transaction_date)subpartition by hash(transaction_id)  subpartitions 3 store in (dinya_space01,dinya_space02,dinya_space03)
 (
     partition part_01 values less than(to_date(‘2006-01-01’,’yyyy-mm-dd’)),
     partition part_02 values less than(to_date(‘2010-01-01’,’yyyy-mm-dd’)),
     partition part_03 values less than(maxvalue)
 );

oracle查看object对象使用空间

1、表空间大小

Select Tablespace_Name,Sum(bytes)/1024/1024 From Dba_Segments Group By Tablespace_Name order by Sum(bytes)/1024/1024 desc;

2、表占用空间

select segment_name, sum(bytes)/1024/1024 Mbytese from user_segments where segment_type='TABLE'  group by segment_name order by segment_name;
Select Segment_Name,Sum(bytes)/1024/1024 From User_Extents Group By Segment_Name order by Sum(bytes)/1024/1024 desc;

3、索引占用空间

select segment_name, sum(bytes)/1024/1024 Mbytese from user_segments where segment_type='INDEX'  group by segment_name order by segment_name;

4、数据文件使用情况

select a.tablespace_name,
       round(a.bytes / 1024 / 1024, 0)"总空间",
       round((decode(b.bytes, null, 0, b.bytes)) / 1024 / 1024, 0)"使用空间",
       round((decode(b.bytes, null, 0, b.bytes)) / a.bytes * 100, 1)"使用率",
       c.file_name,
       c.status
  from sys.sm$ts_avail a, sys.sm$ts_free b, dba_data_files c
 where a.tablespace_name = b.tablespace_name(+)
   and a.tablespace_name = c.tablespace_name
 order by a.tablespace_name;
-----------------------------------------------------------------------
select b.file_id 文件ID,
       b.tablespace_name 表空间,
       b.file_name 物理文件名,
       b.bytes / 1024 / 1024 大小M,
       c.max_extents / 1024 / 1024 可扩展数M,
       b.bytes / 1024 / 1024 + c.max_extents / 1024 / 1024 总大小M,
       trunc((b.bytes - sum(nvl(a.bytes, 0))) / 1024 / 1024)  已使用M,
       trunc(sum(nvl(a.bytes, 0)) / 1024 / 1024)  剩余M,
       trunc(sum(nvl(a.bytes, 0)) / (b.bytes) * 100, 2)  剩余比
  from dba_free_space a, dba_data_files b, dba_tablespaces c
 where a.file_id = b.file_id
   and b.tablespace_name = c.tablespace_name
 group by b.tablespace_name,
          b.file_name,
          b.file_id,
          b.bytes,
          c.max_extents,
          b.bytes / 1024 / 1024 + c.max_extents / 1024 / 1024
 order by b.file_id;

5、表空间使用统计

select a.tablespace_name,
       a.bytes / 1024 / 1024 "Sum MB",
       (a.bytes - b.bytes) / 1024 / 1024 "used MB",
       b.bytes / 1024 / 1024 "free MB",
       round(((a.bytes - b.bytes) / a.bytes) * 100, 2) "percent_used"
  from (select tablespace_name, sum(bytes) bytes
          from dba_data_files
         group by tablespace_name) a,
       (select tablespace_name, sum(bytes) bytes, max(bytes) largest
          from dba_free_space
         group by tablespace_name) b
 where a.tablespace_name = b.tablespace_name
 order by ((a.bytes - b.bytes) / a.bytes) desc;

js考试系统时间倒计时

js实现时分倒计时、悬浮效果

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>无标题页</title>
    <meta HTTP-EQUIV="Content-Type" content="text/html; charset=gb2312" />
</head>
<body onload='ChangeTime();scall();'>
<form id="form1">
<!--模拟页面宽度高度-->
<div align="center">
<center>
<table width="770" height="3000" border="0" cellpadding="0" cellspacing="0" bgcolor="#F4F4F4">
<tr>
<td width="100%" valign="top"></td>
</tr>
</table>
</center>
</div>
<!--弹出时间提示-->
<div id="Javascript.RightDiv" style="position: absolute;z-index:1000;width:200px;height:30px;top:-1000px;word-break:break-all;display:none;">
<div id="timeshow" style="width:200px;height:20px;line-height:20px;text-align:center;font-size:12px;color:#000;background-color:#CCC;border:1px solid #333;"></div>
</div>
<SCRIPT LANGUAGE="JavaScript">
//弹出div
var showad = true;
var Toppx = 10;    //上端位置
var AdDivW = 200;   //宽度
var AdDivH = 25;   //高度
var PageWidth = 750; //页面多少宽度象素下正好不出现左右滚动条
var MinScreenW = 1000; //最小屏幕宽度象素
function scall(){
if(!showad){return;}
var Borderpx = ((window.screen.width-PageWidth)/2-AdDivW)/2;
document.getElementById("Javascript.RightDiv").style.display="";
document.getElementById("Javascript.RightDiv").style.top=document.body.scrollTop+Toppx;
document.getElementById("Javascript.RightDiv").style.left=document.body.scrollLeft+document.body.clientWidth-document.getElementById("Javascript.RightDiv").offsetWidth-Borderpx;
}
window.onscroll=scall;
window.onresize=scall;
//在线考试时间提示
var h=1; //设置考试时间(小时单位)
var m=0.1; //设置考试时间(分钟单位)
var timeShowId="timeshow"; //设置时间显示层ID
var TimeNum=h*60*60+m*60;
var timeStr;
function ChangeTime()
{
  TimeNum--;
    if(TimeNum > 0)
    {
       timeStr=setTimeout("ChangeTime()",1000);
       if(TimeNum<300)
       {
         alert('距离系统自动提交时间还剩5分钟,请尽快做好提交准备');
       }
        if(TimeNum<30)
       {
         alert('距离系统自动提交时间还剩30秒,请马上交卷');
       }
    }
    else
    {
       //系统提交  完善
    }
    document.getElementById(timeShowId).innerHTML="系统提示:你的时间还剩<span style=\"color:#FF0000;\">"+Math.floor(TimeNum/60)+"分"+TimeNum%60+"秒</span>";
}
</SCRIPT>
</form>
</body >
</html>

通过web更新网站(1)

现在维护的网站比较多,经常因为要修改一个小小的东西,要远程登录,或者ftp登录上去下载下来,然后在修改后,再上传上去,总之比较麻烦,我现在总体设想是通过web实现手工的更新网站,既实现通过web下载、上传、删除、编辑。
今天是实现了对整个站点的文件显示,下载和上传到对应目录,为该程序的第一部分
aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function select_dir() {
            var select = document.getElementById("selectType");
            document.getElementById("h_dir").value = select.options[select.selectedIndex].value; ;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <input id="h_dir" type="hidden" runat="server"/>
    <asp:Label ID="lbl_dir" runat="server" ></asp:Label>
    <asp:Button ID="btn_select" runat="server" Text="查看文件"
        onclick="btn_select_Click" />
    <div style="width:400px; height:500px; overflow:auto">
        <asp:Label ID="show_file" runat="server" ></asp:Label>
    </div>
    <asp:FileUpload ID="file_up" runat="server" />
    <asp:Button ID="btn_up" runat="server"   Text="上传文件" onclick="btn_up_Click" />
    </form>
</body>
</html>

cs代码

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Threading;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string web_file=Server.MapPath(".");
            DirectoryInfo thisOne = new DirectoryInfo(web_file);
           lbl_dir.Text="<select id='selectType' onclick='select_dir();' ><option value='" + System.Web.HttpContext.Current.Server.UrlEncode(web_file) + "'>网站目录</option>" + ListSelectShow(thisOne, 0, "") + "</select>";
           h_dir.Value = System.Web.HttpContext.Current.Server.UrlEncode(web_file);
           if (Request.QueryString["F"]!=null)
           {
                string d_file = System.Web.HttpContext.Current.Server.UrlDecode(Request.QueryString["F"].ToString());
               //求文件名
               string[] fs = d_file.Split('\\');
                string   ext = fs[fs.Length - 1];
               //下载文件
                Page.Response.Clear();
                bool success = ResponseFile(Page.Request, Page.Response, ext, d_file, 1024000);
                if (!success)
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('下载文件失败,请重试');", true);
                Page.Response.End();
           }
        }
    }
    public  string ListTreeShow(DirectoryInfo theDir, int nLevel, string Rn)//递归目录和 文件,树形结构显示
    {
        if (nLevel == 0)
        {
            FileInfo[] fileInfo = theDir.GetFiles();
            foreach (FileInfo fInfo in fileInfo)
            {
                Rn += "├";
                Rn += "<a href='Default.aspx?F=";
                Rn = Rn + System.Web.HttpContext.Current.Server.UrlEncode(fInfo.FullName);
                Rn += "'>";
                Rn += fInfo.Name.ToString() + "</a> <br />";
            }
        }
        DirectoryInfo[] subDirectories = theDir.GetDirectories();//获得目录
        foreach (DirectoryInfo dirinfo in subDirectories)
        {
            if (nLevel == 0)
            {
                Rn += "├";
            }
            else
            {
                string _s = "";
                for (int i = 1; i <= nLevel; i++)
                {
                    _s += "│&nbsp;";
                }
                Rn += _s + "├";
            }
            Rn += "<b>" + dirinfo.Name.ToString() + "</b><br />";
            FileInfo[] fileInfo = dirinfo.GetFiles();   //目录下的文件
            foreach (FileInfo fInfo in fileInfo)
            {
                if (nLevel == 0)
                {
                    Rn += "│&nbsp;├";
                }
                else
                {
                    string _f = "";
                    for (int i = 1; i <= nLevel; i++)
                    {
                        _f += "│&nbsp;";
                    }
                    Rn += _f + "│&nbsp;├";
                }
                Rn += "<a href='Default.aspx?F=";
                Rn = Rn + System.Web.HttpContext.Current.Server.UrlEncode(fInfo.FullName);
                Rn += "'>";
                Rn += fInfo.Name.ToString() + "</a><br />";
            }
            Rn = ListTreeShow(dirinfo, nLevel + 1, Rn);
        }
        return Rn;
    }
    public static string ListSelectShow(DirectoryInfo theDir, int nLevel, string Rn)//递归目录下拉框显示
    {
        DirectoryInfo[] subDirectories = theDir.GetDirectories();//获得目录
        foreach (DirectoryInfo dirinfo in subDirectories)
        {
            Rn += "<option value=\"" +System.Web.HttpContext.Current.Server.UrlEncode( dirinfo.FullName) + "\" >";
            if (nLevel == 0)
            {
                Rn += "├";
            }
            else
            {
                string _s = "";
                for (int i = 1; i <= nLevel; i++)
                {
                    _s += "│&nbsp;";
                }
                Rn += _s + "├";
            }
            Rn += "" + dirinfo.Name.ToString() + "</option>";
            Rn = ListSelectShow(dirinfo, nLevel + 1, Rn);
        }
        return Rn;
    }
    protected void btn_select_Click(object sender, EventArgs e)
    {
        string first_dir = System.Web.HttpContext.Current.Server.UrlDecode(h_dir.Value);
          DirectoryInfo thisOne = new DirectoryInfo(first_dir);
          show_file.Text = ListTreeShow(thisOne, 0, "");
    }
    public bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)//下载文件
    {
        try
        {
            FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader br = new BinaryReader(myFile);
            try
            {
                _Response.AddHeader("Accept-Ranges", "bytes");
                _Response.Buffer = false;
                long fileLength = myFile.Length;
                long startBytes = 0;
                double pack = 10240; //10K bytes
                //int sleep = 200;   //每秒5次   即5*10K bytes每秒
                int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;
                if (_Request.Headers["Range"] != null)
                {
                    _Response.StatusCode = 206;
                    string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                    startBytes = Convert.ToInt64(range[1]);
                }
                _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                if (startBytes != 0)
                {
                    //Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));
                }
                _Response.AddHeader("Connection", "Keep-Alive");
                _Response.ContentType = "application/octet-stream";
                _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                int maxCount = (int)Math.Floor((fileLength - startBytes) / pack) + 1;
                for (int i = 0; i < maxCount; i++)
                {
                    if (_Response.IsClientConnected)
                    {
                        _Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));
                        Thread.Sleep(sleep);
                    }
                    else
                    {
                        i = maxCount;
                    }
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                br.Close();
                myFile.Close();
            }
        }
        catch
        {
            return false;
        }
        return true;
    }
    protected void btn_up_Click(object sender, EventArgs e)
    {
        if (file_up.HasFile)
        {
            try
            {
                string path = System.Web.HttpContext.Current.Server.UrlDecode(h_dir.Value);
                string file = file_up.FileName;
                file_up.SaveAs(path + "/" + file);
                DirectoryInfo thisOne = new DirectoryInfo(path);
                show_file.Text = ListTreeShow(thisOne, 0, "");
            }
            catch
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('上传文件失败,请重试');", true);
            }
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('请选择文件');", true);
        }
    }
}

效果

主要难点是对站点中的文件和目录递归树形显示

Solaris10 配置网络

也许是自己对Unix的好奇,也许是Unix+C的利益驱使,我装起了几个Unix系统,想看看到底哪个比较好,比较适合我。在安装的Freebsd、OpenSolaris、Solaris10这三个可以装在32位的cpu上的系统。大概的随便的打开,使用了下shell,感觉和linux没有太大的区别(也许我还没有理解其中的精髓),从做服务器的角度来说,应该是Solaris10最合适,从个人使用的角度来说,OpenSolaris比较顺手。最后装好在VM中的是Solaris10,然后就多玩了下,配置了网络,使用ssh远程访问。现在把Solaris的网络配置给记录下来,以便以后参考
主机名关联文件(hostname.网卡,hosts)
# cat /etc/hostname.e1000g0
xifenfei
# cat /etc/hosts
127.0.0.1 localhost
192.168.1.10 xifenfei loghost
ip地址关联文件
# cat /etc/hosts
127.0.0.1 localhost
192.168.1.10 xifenfei loghost
# cat /etc/netmasks
192.168.1.0 255.255.255.0
# cat /etc/defaultrouter
192.168.1.1
域名相关文件
#cat/etc/resolv.conf
nameserver 202.96.134.133
nameserver 202.96.128.68
#cat /etc/nsswitch.conf
hosts: files dns
常用命令
ifconfig -a —>得出网卡的名字,一般第一块100M网卡名为pcn0
ifconfig pcn0 down —>先把网卡pcn0的服务暂时停止
ifconfig pcn0 up —>启动网卡pcn0的服务
ifconfig pcn0 192.168.1.10 netmask 255.255.255.0 up —>临时修改ip启动网卡(永久性修改后,使用该命令可以使修改ip生效)