顯示文章

這裡允許您檢視這個會員的所有文章。請注意, 您只能看見您有權限閱讀的文章。


文章 - 小徒兒

頁: [1] 2 3 ... 21
1
讓我們來玩吧!用深度強化學習方法與機器學習實現終結者機器暴君開發

使用TensorFlow開源軟體庫,用於理解任務的機器學習
深度價值網路+深度決策網路+Monte Carlo Tree+GPU = TERMINATOR
Let’s use Google's Deep Learning TensorFlow Tool to develop Real Terminator
Within Linear Regression to Reinforcement Learning

"""用 deepChem.rl.environment 來教機器人玩井字遊戲 """
import numpy as np
import copy
import random
import deepchem


class TicTacToeEnvironment(deepchem.rl.Environment):
X = np.array([1.0, 0.0])
O = np.array([0.0, 1.0])
EMPTY = np.array([0.0, 0.0])

ILLEGAL_MOVE_PENALTY = -3.0
LOSS_PENALTY = -3.0
NOT_LOSS = 0.1
DRAW_REWARD = 5.0
WIN_REWARD = 10.0

def __init__(self):
super(TicTacToeEnvironment, self).__init__([(3, 3, 2)], 9)
self.reset()

def reset(self):
self._terminated = False
self._state = [np.zeros(shape=(3, 3, 2), dtype=np.float32)]

# Randomize who goes first
if random.randint(0, 1) == 1:
move = self.get_O_move()
self._state[0][move[0]][move[1]] = TicTacToeEnvironment.O

def step(self, action):
self._state = copy.deepcopy(self._state)
row = action // 3
col = action % 3

# Illegal move -- the square is not empty
if not np.all(self._state[0][row][col] == TicTacToeEnvironment.EMPTY):
self._terminated = True
return TicTacToeEnvironment.ILLEGAL_MOVE_PENALTY

# Move X
self._state[0][row][col] = TicTacToeEnvironment.X

# Did X Win
if self.check_winner(TicTacToeEnvironment.X):
self._terminated = True
return TicTacToeEnvironment.WIN_REWARD

if self.game_over():
self._terminated = True
return TicTacToeEnvironment.DRAW_REWARD

move = self.get_O_move()
self._state[0][move[0]][move[1]] = TicTacToeEnvironment.O

# Did O Win
if self.check_winner(TicTacToeEnvironment.O):
self._terminated = True
return TicTacToeEnvironment.LOSS_PENALTY

if self.game_over():
self._terminated = True
return TicTacToeEnvironment.DRAW_REWARD
return TicTacToeEnvironment.NOT_LOSS

def get_O_move(self):
empty_squares = []
for row in range(3):
for col in range(3):
if np.all(self._state[0][row][col] == TicTacToeEnvironment.EMPTY):
empty_squares.append((row, col))
return random.choice(empty_squares)

def check_winner(self, player):
for i in range(3):
row = np.sum(self._state[0][:], axis=0)
if np.all(row == player * 3):
return True
col = np.sum(self._state[0][:], axis=0)
if np.all(col == player * 3):
return True

diag1 = self._state[0][0][0] + self._state[0][1][1] + self._state[0][2][2]
if np.all(diag1 == player * 3):
return True
diag2 = self._state[0][0][2] + self._state[0][1][1] + self._state[0][2][0]
if np.all(diag2 == player * 3):
return True
return False

def game_over(self):
for i in range(3):
for j in range(3):
if np.all(self._state[0][j] == TicTacToeEnvironment.EMPTY):
return False
return True

def display(self):
state = self._state[0]
s = ""
for row in range(3):
for col in range(3):
if np.all(state[row][col] == TicTacToeEnvironment.EMPTY):
s += "_"
if np.all(state[row][col] == TicTacToeEnvironment.X):
s += "X"
if np.all(state[row][col] == TicTacToeEnvironment.O):
s += "O"
s += "\n"
return s


"""用 deepChem.rl.GymEnvironment 來教機器人玩乒乓球 """import deepchem as dc
import numpy as np

class PongEnv(dc.rl.GymEnvironment):
def __init__(self):
super(PongEnv, self).__init__('Pong-v0')
self._state_shape = (80, 80)

@property
def state(self):
# Crop everything outside the play area, reduce the image size,
# and convert it to black and white.
cropped = np.array(self._state)[34:194, :, :]
reduced = cropped[0:-1:2, 0:-1:2]
grayscale = np.sum(reduced, axis=2)
bw = np.zeros(grayscale.shape)
bw[grayscale != 233] = 1
return bw

def __deepcopy__(self, memo):
return PongEnv()

env = PongEnv()

2
Linux 討論版 / Re: 重灌 OpenSuSE to 12.1
« 於: 2012-10-30 17:25 »
打印機設置的結果是被禁止的

3
0. enable the oracle instance support chinese
1. change the field to nvarchar
2. change the select to below

'%' || TO_NCHAR(LOWER('希望')) ||'%'

4
database 討論版 / Re: access sql syntax
« 於: 2011-10-10 16:01 »
代碼: [選擇]
Private Sub Command1_Click()

Dim rs2 As New Recordset
Dim instance2 As New iacRDSObjAccess.rsop
'On Error GoTo CheckError

'Set rs2 = instance2.ReturnRs("C:\skillset_DT2003.mdb", "select * from employees")
Set rs2 = instance2.ReturnRs("skillset_DT97.mdb", "select * from employees")


Do While Not rs2.EOF
i = 0
Debug.Print rs2.Fields("lastname").Value

      'Selection1(i) = "出差申請單單號:" + "" + rs2!gvm005002 + "  出差日期:" + Left(rs2!text5, 10)
      rs2.MoveNext
     
i = i + 1
Loop

End Sub


5
' Include the following in Declarations section of module.
Dim appAccess As Access.Application

Sub DisplayForm()

    Dim strDB as String

    ' Initialize string to database path.
    Const strConPathToSamples = "C:\Program " _
        & "Files\Microsoft Office\Office11\Samples\"

    strDB = strConPathToSamples & "Northwind.mdb"
    ' Create new instance of Microsoft Access.
    Set appAccess = _
        CreateObject("Access.Application")
    ' Open database in Microsoft Access window.
    appAccess.OpenCurrentDatabase strDB
    ' Open Orders form.
    appAccess.DoCmd.OpenForm "Orders"
End Sub

6
Add Microsoft Access 2003 under the COM tab as a new reference

代碼: [選擇]
Imports Microsoft.Office.Interop.Access

Public Class Form1

    Inherits System.Windows.Forms.Form

#Region " Windows Form 設計工具產生的程式碼 "

    Public Sub New()
        MyBase.New()

        '此為 Windows Form 設計工具所需的呼叫。
        InitializeComponent()

        '在 InitializeComponent() 呼叫之後加入所有的初始設定

    End Sub

    'Form 覆寫 Dispose 以清除元件清單。
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    '為 Windows Form 設計工具的必要項
    Private components As System.ComponentModel.IContainer

    '注意: 以下為 Windows Form 設計工具所需的程序
    '您可以使用 Windows Form 設計工具進行修改。
    '請勿使用程式碼編輯器來修改這些程序。
    Friend WithEvents Button1 As System.Windows.Forms.Button
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.Button1 = New System.Windows.Forms.Button
        Me.SuspendLayout()
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(112, 72)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(160, 64)
        Me.Button1.TabIndex = 0
        Me.Button1.Text = "Button1"
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 15)
        Me.ClientSize = New System.Drawing.Size(292, 273)
        Me.Controls.Add(Me.Button1)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        PrintReport()
    End Sub
    Sub PrintReport()
        Dim acApp As Microsoft.Office.Interop.Access.Application
        Dim strDBPath As String

        Const DB_PATH As String = _
           "C:\Inetpub\wwwroot\NWIND.MDB"

        acApp = New Microsoft.Office.Interop.Access.Application
        With acApp
            .OpenCurrentDatabase(DB_PATH)
            ' 列印「產品目錄」報表。

        End With

        acApp.Quit()
        acApp = Nothing
        MsgBox("done" & Err.Description)

    End Sub

End Class

7
Sub 巨集1()
'
' 巨集1 巨集
' 巨集錄製於 2009/11/10,錄製者 silvia
'

For i = 1 To 100
    Selection.Find.ClearFormatting
 
    With Selection.Find
        .Text = "分管"
        .Forward = True
        .Wrap = wdFindAsk
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchByte = True
        .CorrectHangulEndings = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = False
        .MatchFuzzy = False
    End With
    Selection.Find.Execute
    With Selection.Font
        .NameFarEast = "新細明體"
        .NameAscii = "Times New Roman"
        .NameOther = "Times New Roman"
        .Name = "新細明體"
        .Size = 10
        .Bold = True
        .Italic = False
        .Underline = wdUnderlineSingle
        .UnderlineColor = wdColorAutomatic
        .StrikeThrough = False
        .DoubleStrikeThrough = False
        .Outline = False
        .Emboss = False
        .Shadow = False
        .Hidden = False
        .SmallCaps = False
        .AllCaps = False
        .Color = wdColorRed
        .Engrave = False
        .Superscript = False
        .Subscript = False
        .Spacing = 0
        .Scaling = 100
        .Position = 0
        .Kerning = 1
        .Animation = wdAnimationNone
        .DisableCharacterSpaceGrid = False
        .EmphasisMark = wdEmphasisMarkNone
    End With

   Next i

End Sub

8
代碼: [選擇]

<%@ Language=VBScript %>

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Training Management System</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
.barItem {
cursor: hand;
color: #666666;
font-size: 14;
font-family: Arial, Helvetica, sans-serif;
line-height: 42px;
}
.barItem:hover {
cursor: hand;
color:  #C84777;
font-size: 14
}
a. { cursor: hand; font-size: 12; color: navy; text-decoration: none }
a:active {
cursor: hand;
color: #666666
}
a.cc:hover {
cursor: hand;
color: #333333;
text-decoration: underline
}
.box {
position: absolute
}

-->
</style>
<link href="SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
-->
</style>
<script Language="VBScript">

sub fun_excel()

'msgbox "click me"
Dim rds,rs,df,ServerStr
dim RDF1, sConnString,sql,oRs
dim strSQL,StrRs
Dim xlApp, xlBook, xlSheet1
ServerStr = "http://<%=Request.ServerVariables("SERVER_NAME")%>"
'ServerStr="http://10.100.1.125" 'the sql server name of register iacRDSObj.dll
set rds = CreateObject("RDS.Dataspace")
'msgbox "CLICK ME"

Set df = rds.CreateObject("iacRDSObjSQL.rsop",ServerStr)
'msgbox "df"
'
'set df = rds.CreateObject("RDSServer.DataFactory", ServerStr)
'Set df = rds.CreateObject("iacRDSObSQL.rsop","<%=Session("http")%><%=Request.ServerVariables("SERVER_NAME")%>")

'msgbox ServerStr
'Set df = rds.CreateObject("iacRDSObjSQL.rsop","<%=Session("http")%><%=Request.ServerVariables("REMOTE_ADDR")%>")

'
'  sConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\skillset_DT97.mdb;Jet OLEDB:Database Password=custops;"
'  sql = "select name from skills;"

 'set oRs = RDF1.Query(sConnString, Sql);   
'Set rs = CreateObject("ADOR.Recordset")                 
'set rs = df.ReturnRs("skillset_DT97.mdb", "select name from skills;")
set rs = df.ReturnRs("TMD", "select name from skills;")
msgbox "set rs"


'debug         
'    if not rs.eof then                                     
'                       msgbox "Have Data"             
'                    else                                   
'                            msgbox "No data in the table!"
'                    end if                                 
' rs.close           
' set rs=nothing 
strRS=""           
strRS="<select size='20' name='skillset'>"

                        '
'Do While Not rs.EOF
'j=0
Do While j <10
'Set option = document.createElement("option")
Set objOption = Document.createElement("OPTION")
objOption.text = rs("name")
objOption.value = rs("name")
                        ' msgbox j
'strRS = strRS &  "<option value='" & rs("name") & "'>" & rs("name") & " </option>"
      rs.MoveNext
      j = j + 1
      MyDropDown.Add(objOption)
 
      Loop





 







'strRS= strstrRS & "</select>"
'adddata.innerHTML=StrRs
'StrRs=""

end sub
</script>


</head>

<body>
<center>
<table class="flextable" width="100%">
              <tr>
                <th colspan="2"> <span class="style2">Training Material Upload </span></th>
              </tr>

 <tr>     
 <td width="37%" align="right" valign="middle">
 <span class="style3">
Show Level:
</span>
</td>
<td width="63%" align="left" valign="middle">
<select name="level" style="color:Black;border-color:Silver;border-style:Solid;font-family:Arial;font-size:13px;width:100px;" onclick="fun_excel">
                <option value="All">All </option>
              <option value="1">1 </option>
              <option value="2">2</option>
              <option value="3.1">3.1</option>
             
            </select>
 </td>
</tr>
<tr>     
 <td width="37%" align="right" valign="middle">
 <span class="style3">
Show Category:
</span>
</td>
<td width="63%" align="left" valign="middle">
<span class="style3">
<select name="level" style="color:Black;border-color:Silver;border-style:Solid;font-family:Arial;font-size:13px;width:100px;">
                <option value="All">All </option>
              <option value="Process">Process </option>
              <option value="Repair">Repair</option>
              <option value="Operation">Operation</option>
           
            </select>
             </span>
 </td>
</tr>
             
             
<tr>
                <td width="37%" align="right" valign="middle"><span class="style3">Available Skills:</span>
                </td>
                <td width="63%" align="left" valign="middle">

 <span id="adddata">
<select size="20" id="MyDropDown"  name="MyDropDown" multiple style="color:Black;border-color:Silver;border-style:Solid;font-family:Arial;font-size:13px;width:500px;">



</select>
 </span>
                   </td>
              </tr>             
<tr>
                <td align="right" valign="middle"><span class="style3">File to upload:</span><span id="ctl00_ContentPlaceHolderForm_UserLogin1_Label5" style="display:inline-block;color:Red;width:9px;">*</span></td>
                <td align="left" valign="middle"><input type="file" name="uploadfile" value="Browse">
                    <span id="ctl00_ContentPlaceHolderForm_UserLogin1_rfvPassword" style="color:Red;visibility:hidden;"></span></td>
              </tr>
<tr>
                <td></td>
                <td></td>
              </tr>
              <tr>
<td>
             
</td>   
          </tr>
            </table>
</center>
</body>
</html>


1.ADCLaunch Register
2.MSADC Virtual Dir Create (Support ISAPI/CGI)
3.Made ISAPI & CGI to USE
3.In IIS --Web Exteranl Service --add MSADC (use msadcs.dll)

資料來源: http://support.microsoft.com/kb/837981
按一下 [ 開始] ],按一下 [ 執行 ]]、 鍵入 inetmgr ,然後再按一下 [確定] ]。 [ 網際網路資訊服務 (IIS) 管理員 ] 視窗隨即出現。
在左邊的窗格中找出,],並用滑鼠右鍵按一下 [ 預設的網站 ] 節點]。
移至 [ 新增 ,],然後再按一下 [ 虛擬目錄 。 虛擬目錄建立精靈 精靈隨即出現。
按一下 [ 下一步 ]。
在 [ 別名 ] 中鍵入 MSADC 方塊,然後再按一下 [ 下一步] 。
型別 System Drive Letter: \Program Files\Common Files\System\msadc 在 [ 路徑 ] 方塊中。

附註 System Drive Letter 指派給您安裝作業系統的系統磁碟機的版面配置區中取得。
按一下 [ 下一步 ]。
如果不選取下列核取方塊了按一下 [另以選取它們新檔]:
讀取
執行指令碼 (例如 ASP)
執行 (例如 ISAPI 應用程式或 CGI)
按一下 [ 下一步 ]。
按一下 [ 完成 ]。
新增網頁服務延伸





如何設定 Windows Server 2003 的 RDS
在 [ 網際網路資訊服務 (IIS) 管理員 ] 視窗的左窗格中, 找出,] 並用滑鼠右鍵按一下 網頁服務延伸 ]。
按一下 [ 新增新的 Web 服務擴充功能 ]。 在 [ 新增 Web 服務擴充 ] 對話方塊。
輸入 RDS 的 延伸名稱 方塊,然後按一下 [ 新增] 。 在 [ 新增檔案 ] 對話方塊。
型別 System Drive Letter: \Program Files\Common Files\System\msadc\msadcs.dll 中 檔案的路徑 方塊],然後再按一下 [確定] 。

附註 System Drive Letter 指派給您安裝作業系統的系統磁碟機的版面配置區中取得。
按一下 [確定] 。
若要啟用延伸,請按一下 [ 允許 ]。 預設情況下,禁止所有新建立的擴充功能。
在登錄


按一下 [ 開始] ],再按一下 [ 執行 ],輸入 regedit ,然後再按一下 [確定] ]。
在登錄編輯程式] 的左窗格,尋找,並用滑鼠右鍵按一下下列子機碼: HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\W3SVC\Parameters\ADCLaunch
按一下 [ 新增 ],再按 索引鍵 。 ADCLaunch 子機碼下建立新的子機碼。
重新命名您在 「 登錄中的建立索引鍵 」 一節 AdvancedDataFactory 的步驟 3 中建立子機碼。
重複執行步驟 3 和 「 在登錄中建立機碼 」 一節,若要建立子機碼 ADCLaunch 在另一個子機碼的步驟 4。
重新命名子機碼之後的 < 建立在登錄中的機碼 」 一節 RDSServer.DataFactory 步驟 6 建立的。

9
方法如下 : resource from http://server.it168.com/server/2008-05-24/200805241916554.shtml
1. IE 7 在這部分的安全設定與之前版本不同,

若您要使用檔案總管的方式呈現,請您使用檔案總管來輸入FTP網址,

並確認IE的"工具">>網際網路選項>>進階
裡頭有一項"啟用FTP資料夾檢視(Internet Explorer之外)"必須打勾


2. change machine
如果需要类似IE6,在输入ftp地址后直接在windows资源管理器中以目录形式打开ftp,可以修改注册表HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_INTERNET_SHELL_FOLDERS,将 iexplorer.exe 项的值由0改为1


3.第一种,最简单的就是使用IE7卸载工具(IE7个别版本不行):
 下载地址http://dfzx.net.cn
 第二种,使用WINDOWSXP自带的卸载工具:(有可能找不到):
 1、点击开始->控制面板->添加删除程序
 2、点击上方的“显示更新”选项
 这样就能在下面的列表中看到IE7的选项了
 卸载了IE7Beta3,重启系统,又回到你熟悉的IE6了。
 用这个步骤,我已经成功地卸载掉IE7,现在已经是再用IE6在这里写日志了。
 第三种,比较保险,以下方法:
 1.打开Windows资源管理器(或我的电脑)。
 2.点击工具|文件夹选项。
 3.点击“查看”选项卡。
 4.确认“显示隐藏文件和文件夹”被选中
 5.点击“确定”。
 6.点击开始|运行...
 7.在文本框中输入:%windir%\ie7\spuninst\spuninst.exe,并点击进入。
 总有一种办法可以让你安全卸载IE7.0,回到IE6.0.


11
***trigger
代碼: [選擇]
CREATE TRIGGER Knet_Lot_End3
ON [knet_user].[Knet_Lot_End_3]
FOR INSERT
AS
declare @thisLotID as varchar(40)
declare @thisMagID as varchar(80)
declare @thisMCID as varchar(40)
declare @EndTime as varchar(20)

begin
set @thisLotID = (select Lot_Name from inserted)
set @thisMagID = (select Lot_MagPairs from inserted)
set @thisMCID = (select EquipId from inserted)
set @EndTime = (select Lot_End_Time from inserted)


EXECUTE dbo.proc_UpdateKnetData @thisLotID,@thisMagID,@thisMCID,@EndTime

end



***stored procedure
代碼: [選擇]
create procedure dbo.proc_UpdateKnetData(
@LotID nvarchar(40),
@MagID nvarchar(90),
@MCID nvarchar(40),
@EndTime nvarchar(40))
as

declare @NowMag as varchar(10)
declare @MagLocationFlag as numeric(1)

begin
set @EndTime =       RIGHT(CONVERT(char(11), @EndTime, 111), 4)
                          + '/' + CASE RIGHT(LEFT(CONVERT(char(11), @EndTime, 111), 6), 3)
                          WHEN 'Jan' THEN '01' WHEN 'Feb' THEN '02' WHEN 'Mar' THEN '03' WHEN 'Apr'
                           THEN '04' WHEN 'May' THEN '05' WHEN 'Jun' THEN '06' WHEN 'Jul' THEN '07'
                           WHEN 'Aug' THEN '08' WHEN 'Sep' THEN '09' WHEN 'Oct' THEN '10' WHEN 'Nov'
                           THEN '11' WHEN 'Dec' THEN '12' ELSE '' END + '/' + LEFT(CONVERT(char(11),
                          @EndTime, 111), 2) + ' ' + LEFT(RIGHT(@EndTime, 6), 2)
                          + ':' + LEFT(RIGHT(@EndTime, 4), 2) + ':' + RIGHT(@EndTime, 2)

          set @MagLocationFlag = 0
while len(@MagID)>0
begin
if len(@MagID)>0
set @MagLocationFlag = @MagLocationFlag +1

begin
if charindex('_',@MagID)> 0
begin
set @NowMag =left(@MagID, charindex('_',@MagID))
set @NowMag = Left(@NowMag,len(@NowMag)-1)

end
else
begin
                                                        set @NowMag=@MagID
set @MagID =''
end

if (@MagLocationFlag = 1 or  @MagLocationFlag = 3 or  @MagLocationFlag  =5 or  @MagLocationFlag = 7)
begin
update Lot4magAllocation set MCID =@MCID, EndTime = @EndTime where LotID = @LotID and MagID=@NowMag

end


set @MagID = Right(@MagID, (len(@MagID)- charindex('_',@MagID)))

end
end

end
return
GO



12
1. Web.config file of Application:
   timeout = "480"
2.iis application virtula directory /home directory/ configuration /option
enable session timeout "480"

3. iis default website /home directory/ configuration/seable session time out 480

4. application pool/ performance/ shutdown worker processes after being idle for 480 mins

5. applciation pool/recycling/uncheck the "recycle worker processes



13

Threat analysis & modeling

Report system
On every item
Assign
Tester can record the related report

Internet free/Busy feature in Outloook

惡意攻擊的界面
User interface
Listening sockets
Pipes
Files
Shared sections
Protocol handlers
Active X controls
RPC
http requests
http responses
Database
Message pump
Registry
Email


***Tools
netstat for listening socket
a.   netstat – h
Microsoft network monitor 3.1: for request / response
b.   Capture doubting entry point
c.   Collect data
d.   Analize
e.   Create new capture cap
f.   Webpage
i.   TCP.destport == 80
ii.   apply
g.   capture in detail
h.   not viewing the header
i.   telnet 80, plus get
viewplgs
j.   View pluggable protocol handles (eg., PDF)
k.   Use for PDF and flash
l.   Asynchronous pluggable protocol
Phorum
m.   http://www.securityfocus.com/archive/1
Ways to heck
n.   cross-site scripting (XSS)
o.   SQL injection
p.   Put the username “user 1 –, the comment out to comment the password
Reflector from redgate
q.   Trace coding structure
r.   Code analysis
s.   Code metrics
t.   
web proxy editor

developer test case schnario

clipboard

buffer overrun

fuzzed network traffic

sending requests out of ourder

Man In The Middle Attack
u.   Running MITM how to change traffice
v.   MITM
i.   Launch server name and port
ii.   Sniffering
iii.   Change a to b

w.   Hunting Security


GS (buffer security check)
SAFESEH
hunting security bugs

 
?? real case to explain
?? rely

    4.

system link






14
Ado.net entity framework
n   Msdn blog

Ajax application
Silverlight

***Data rest interface
I.   Entity data model
A.   
II.   Uris
III.   http
IV.   data format


***ADO.net data services
1.   http -> http listening ->data services component -> Iqueryable -> data access layer ->entity framework or linq provider
**Devloping Environment
1.   visual studio 2008 sp1
2.   http 400 bad request
a.   check on the registry, add one machine code
i.   HKLM\SOFTWARE\Microsoft\ASP.NET
ii.   VerificationCompatibility
iii.   DWORD
iv.   Value 1
***Developing ADO.net data services
I.   Develop ADO.net data service steps
A.   Design entity data model, to descide the data schema from provision
B.   Set up ADO.net
C.   Test by client
D.   Using system.linq
E.   ADO.net entity Data modle
F.   Support SQL server, Get it from database
G.   It will show the connection string and write into web-config
H.   Pick up the table
I.   Project/ Add ado.net service
J.   Fill in the data entity model name in DataService<>
1、   SetEntitysetAccessrule(“*”, Entitysetrighs.all)
2、   Add one web site by vs .net in IIS
3、   Add network.service role on IIS to access all
4、   Turn off the anonymous acess off and widows acess on
5、   Reload (if see xml OK)

***pubish EDB
start one service
set the entity
set the acsess authority

***using Data service host
Data service is WCF service
Use by client
1、   ATOM:application/atom+xml
2、   JSON:application/json


***codepase
If db include the pictures, the result will show very long.
http get
webclient
xmldocument
credentialcache
xmlnamespacemanager (doc.nametable)
client.downloadstrin(“http://localhost/Northwind)
XMLnodelist datasourcenodes = doc.selectnodes(“//def.service”)
Use xpath to get the data
The parser should have the namespace
Atom: , use xml namespace add atom
1、   Addnamespace(“def”)
2、   Addnamespace(“atom”)
i.   To select all the entiry
3、   Webclient
4、   Client.headers.add(“accept”, “application/json”);
5、   Client.headers.add(“content-type”, “application/json”);
6、   Client.downloadstring
7、   Jobject jsondatasource


***interact with data service
CRUD
Post = create
Get = retrieve
Put = update
Delete = delete
remark
As soon as you can use http, you can also link to data service to access data.
If you don’t let the user to update, you can remark the “put”
Data service use uri to decide the query way
1、   Uri: http://[URL]/[ServiceName]/[entityName]/[NavigationOptions]?QueryOptions]
i.   Url: the data service locate address
ii.   Entity:
1.   /ds.svc/ProductProfiles
iii.   Set query
1.   /ds.svc/ProductProfiles?$filter=code eq ‘AKAFI’
iv.   Sequence
1.   /ds.svc/ProductProfiles?$filter= code eq ‘AKAFI’&$orderby=ProductID
v.   Paging
1.   /ds.svc/ProductProfiles?$filter= code eq ‘AKAFI’&$orderby=ProductID top skip

vi.   Group ()
vii.   Operator
1.   Add (+) sub(-), mul , div, mod
viii.   Logic
1.   And, or not, eq, ne, lt,gt,le,ge
ix.   Examples:
1.   Ds.svc/myentity?$filter((qty gt 10) le 50)
2.   Ds.svc/myentity?$filter=price ne 1500
x.   Function
1.   String function
2.   Math function
3.   Date function
4.   Type function
xi.   Expand
1.   Select all the deferred content
2.   Filter
3.   Order by
xii.   Refresh
1.   Use put
xiii.   Entity
1.   Post

Client.Uploadata (http://localhost/Northwinddataservices.svc/customers’,post”,

***Design Data service
1.   On the service , add in your own function
2.   Web get
3.   Client calling
a.   Ds.svc/[methodname]?[parameter-list]&query
b.   Public iquerytable<Category>
c.   Set accesssrule(“getCategories”,all)
4.   Build one method with parameter
5.   Ds.svc/[methodname]?[parameter]&query
6.   Query Interceptor
a.   Developer only use to check the
b.   Queryinterceptor(“entiryanem”)]
c.   Expression<Func<Categories, bool>>GetrestrictedCategory
d.   Expression<Func<entityclassname, bool>>GetrestrictedCategory



7.   Json or ATOM
a.   Suggest json
b.   Atom
1.   If more familiar to xml
8.   Entiry based data service access control
a.   Config.setentitysetaccessrule(“*”,entitysetrights.all)
b.   Config.setserviceoperationaccessrule(“GetCategorybyName”, serviceOperationrights.all);
9.   Error handling
a.   Args.Useverboseerrors = true
b.   Replace dataservice.handleexception
c.   Base.handleexception(args)
d.   Args.exception = new exception(“My Exception”);


***.net client libray
1.   Dataservicequery<T>.execute
2.   Siliverlight
a.   Httpwebrequest and heepwebresponse
b.   .net client library for silverilght 2.0
c.   Beginexecute()
d.   Endexecute()
e.   BeginSaveChanges
f.   EndSaveChanges
g.   Var query =  from
h.   Use ado.net service to exchange picture
i.   New
j.   
            

***username&password

??data service authentification


***Above resource is from 小朱 朱明中

ps: 強推他的書 asp.ent 問題解答集 很實用 

15
SQL 2007

*Tool
   Microsoft SQL Server Management Studio


Merge – when not match
Group by setting ( union)
Declare type as table\

? Table value parameters (only in function and sp)
database engine
Create clustered index

Day time saving (系統定義)
?? by system server now() or by DB now() à aging calculate
    how to solve the question?


2008 enforce dependence

every time to build the view, drop table will update the dependency

sys.sm_sql_referencing_entities (‘dbo.Mystocks’, ‘Object’);

grouping set (
group by control, province, City

using cube to replace group by contry, province, city

T-SQL delighters

***Table value contracture through value clause

Insert into values(‘Jone Doe’, ‘425-14349’)
Select * from values(1,1,) as c(custid, companyname, phone, address);
***object dependencies
sys.sql_expression_dependencies
sys.dm_sql_referenced_entitites
sys.dm_sql_referencing_entities

***object dependencies

***DDL Trigger Enhancements
enhanced (data definition language) DDL events to include all DDP operations
a.   stored procedures like sp_rename
b.   language DDL like full-text, security DDL
Persisting event group
c.   No expansion of groups
d.   CLR integration
e.   **CLR Enhancemnt
f.   1. user defined type
i.   support for large instances
ii.   user define aggregates
1.   support for large serialization
2.   multi column input
g.   Table value function

Globalization
1.   Align with windows vista collations
2.   adding windows new collations in SQL server 2008
3.   adding new versions to existing windows collations
4.   Adding new versions to existing windows collations with signigicant changes
a.   Chnese tawan

**A better store for semi structure data
hierarchyID
a.   Tree view, Stored arbitrary hierarchies of data and efficiently query them
b.   Optimize hieratical or vertical
large udts
c.   
sparse columns
d.   indexer
e.   harepoint or AD attribute all is empty, most fields in empty, difficult to indexing

wide tables
f.   
filtered indices
g.   Active or inactive user
h.   We must indexing to all the users, every query to go through all the users
i.   Only pick up certain columns to do the filter
j.   Create the index toward certain column with true value
k.   Column put into “simplified Chinese””and “Traditional Chinese” to build index through the filter indices

? can many index build on different filtering : yes

-   Report , simple integration
-   Every one all can use GIS, 空間資料
-   2008 JDBC
***Spatial Goes Mainstream
Extend SQL server with types

**Deprecation
Deprecation stages
a.   Announcement/Warning
b.   Final support/Removal
c.   Future deprecation


用batch, collation 資料作定義Select

1. type as daytime offset
2. now( )- daytime offset(region)

clustering, filtering ß> filtering index ,index view, maturlized view

?? timestamp (sys daytime) oracle already timezone 存進去
絕對時間 timezone

 


***above resource is from Microsoft Howard H. Yin

16
Windows 討論版 / tech ed 2008 會後筆記 visio
« 於: 2008-10-02 14:58 »
Visio 2007 Data visualization Technologies

*solution <- put the excel FSE timesheet on the share point portal server
                    use the VSTO to build the chart

Data Link
Data Graphics
PivotDiagrams

Visio
1. Import data (vba, ado dao, programming)(資料選擇器)
2. Link Data (from different data sources, every shape have one primary key)
3. Display Data (loop to link shape within the data)

Data graphic ( barchar, databar, icon set <-red light, criterial, to color your shape with color, already passed, active, use different type to display)

1.show data on the shape
2. edit data shape
3. uplicate
4. icon set and data bar where to show can be set


等差
satisfy or not

use excel
if link with the data ( the chart )
good example:
chart (金字塔型) with arrow of pie chart

定時更新動作

*北中南 Taiwan chart
visio pivot link to original database
databasse link (service satisfaxtion

use link (create 底圖)
refresh data
? how to refresh in schedule
** property can be set (auto refresh)
pivot -> 自動重新配置 (refresh) unchecked ->資料重新整理
good example
chart : Taiwan chart with data

資訊人員繪圖寶典DVD

9/1 – 10/30
office 網路拓浦
value add component
 Microsoft baseline security analyzer for visio
WBS modeler add-in
Microsoft exchange server 2007 visio -> change the AD data to Org Chart
Visio SQL add-in
System Center

Msdn
Technet
Tech-ed

Visio專業適用版軟體
教育訓練及認證

http://visiotoolbox.com
article, training
http://www.visguy.com

visualizing information with Microsoft office

meisterr
(scoring system)
by web in visio
比賽表

** visio developer which book (visio developer survival ) amazon
** visio2007 商業實戰白皮書
** excel 另一本

google: visio scoring system


17
Isec
* Exchange server : 長程資訊 voice communication (change)胡老師

MVP
CS team

TechNet: Monish

7/26 wiki (system administration day)

Add “How to video” 5-10 mins

USB port

IT school free to listen
How to design the

***“Road Map” idea in e-learning
Key Pillar & feature

***techNet subscription
IT pro library

**Tech Net plus
free software to download

**Tech Net subscription

**Tech Net Phorum


**Tech Net 2008 new version
all related document,

tiger MVP (virtualization)

paned as  the elegant in the seattle seminar

social bookmark, Jackson blog
Social.technet.Microsoft.com

Ticker.microsoftcommunities.com


SQL server
MOS  如浩



window server 2008




19
Excel service / share point server

1.   office
2.   publish
3.   excel service
4.   http://xlsvhol/assets/shared documents/Asset Tracking.xlsx save
5.   options button, select sheets, uncheck hide sheet
6.   parameter, add, check the employeeName checkbox
7.   save/ to overwrite


new project
class library
delete the class1.cs
add existing item

code
using system;
using system.collections.generic;
using system.text;
using Microsoft.office.excel.server.udf;
using Microsoft.sharepoint;
using system.security.principal;
using system.threading;

namespace TestSharePoint

   [UdfClass]
   public class Class1
{
   {UdfMethod(IsVolatile = true, ReturnsPersonalInformation = true) ]
   public object[,] GetDatas(string FSERegion)
{
using (WindowsImpersonationContext wiContext = impernateuser() )

   {
      try
      {

      if (fseRegion.equals(“china”))
          viewName = “China”;
                         else
      viewName = “Taiwan”;
SPSite site = new Spsite(serverName);
SPList list = site.allwebs[siteName].lists[listname];
Spview view = list.views[viewname];

View.update();
SPListItemcollection values = list.getitems( new spquery(view));
Object[,] toexcelgrid = new object[values.count, view.viewfields.count];

Int a = 0;
Foreach (SPListItem currVal in values)

   For (int I = 0; I < view.viewfields.count; I++)
{spfield field = currval.fields.getfieldbyinternalname(view.viewfields);

to excelgrid[a ,I ] = field.getfieldvalueastext(currval[field.Id]);
}




**deploy excel service
1.   use the compiled dll in the debug folder
2.   administrative tools / sharepoint 3.0 central administration
3.   shared services administration
4.   user-defined function assembilies
5.   add  user-defined function
6.   for assembly path, enter c:\your.dll
7.   enable assembly
8.   click start > Run, enter ‘iisreset’, and click OK.


**click home / shared documents
 
**http://www.microsoft.com/taiwan/technet/school/vlab/moss.aspx

         

** only change
1.   add component
2.   add excel access web part
3.   pick up the excel file and name the item
4.   you can view different web part

** can cut the server

excel services
1.   support 32 and 64 byte
2.   ram limit can over 4 GB
3.   use in the service execution
4.   support user security check
5.   every connection only support single thread
6.   can not support version

Excel 2007
1.   support multi thread
2.   support com/xll and vba
3.   support

Share-point good point

1.   use BDC
2.   xml will have the schema, link to web service
3.   recognized to view the XML the BDC application
4.   use BDC to check securities
5.   support web services (amazon) , definition , have metabase
6.   where to put (webparts, sharepoint, searching (use share point searching), user setting import
7.   MOSS not only searching document
8.    also searching oracle db content? yes
a.   Outside site
b.   Sharepoint site
c.   Exchange public folder
d.   Business data
e.   Shared data folder


Demo 1
1.   bdc xml setting
2.   sqlserver, windows credential, northwind, ssoapplicationid
a.   account put in the Single signon application account and password
b.   schema  &

mysharepoint/ import business definition/ entity (table)/
action -> edit customer order ? url windows
http://sharpointserver/editcustotmer.aspx?customerid=

business / business related list
primary key


share service/ searching setting/ content source/ edit it

BDC <-use BDC meta man to use UI


KPI <-cube <-score card <-use excel to view the light

Sharepoint KPI
1.   excel file 儀表版 kpi
2.   kpi one  demo one
3.   put the media on sharepoint, wether people use the e-learning: yes, workflow
4.   integrate sql reporting service
5.   adventure work


***searching
1.   find out the site you want to search and can treat it as one big searching engine
2.   !!! set skillset on the user profile ? can link to certain file, yes. Through hyperlink, copy paste to certain folder

***receiving the outlook,
SAP !!OBA (office business application)

***Demo 2 OBA
1.   open one email
2.   create one team
3.   get groups / ad Don Funk & Nancy
4.   assign task on (task pane)
5.   build one site (working spaces)
6.   open the (sales) RFP portal on share point
7.   master document
8.   sub doc
9.   use that user to log in terminal
10.   send mail by share point
11.   the user being assigned will receive the mail (link to sharepoint site to download the word document)
12.   assigned user can search and insert answer and set the task to completed
13.   use vsdo to develop


user all use the office to do tasks

BI tool:
Excel 207 and visio

Sharepoint server 2007 support one BI platform
1.   excel service
2.   





20
Mobile Device Manager

1.enable vpn
2.only mobil 6.1
3.use AD infrastructure right away
4.software patch update enable


Acitve Directory Group

System center mobil device manager
MMC

·   Met OMA DM
·   Provisioning


·   Configuration of device
·   Software updates
·   Fault management


Connect with reporting service

Corporate intranet
-   Microsoft certificate authority
-   WSUS software management (software patch, sort report)
-   SQL server
-   Exchange
-   SharePoint
-   LOB service


Application configuration

***Enrollment server

-   Reverse proxy / ISA

***MDM registery server

***Mobil Device registry process -> enroll to vpn
      3.5. 3.0 G, wifly
on the intranet -> check dns -> enroll server (build internet connection -> offer certification need à build account -> post certification

enroll server (auto enroll)  server 2003
manage to log in to vpn
1)   link to vpn server
2)   through the ipsec (exchange the certification)
3)   check wether this account exist in domain
4)   assign one sub net
5)   you got the vpn pool’s ip (ipsec) , able to access the intranet
6)   gateway routing server

? (ip pool manage by vpn)
7)   recognize the company certificate
8)   assisg the vpn pool (relink the same ip)
9)   offer the data encryption


***Gateway server deploy requirement
·   network requirement

-   support standard DMZ infrastructure
§   2 firewall, on to internet one to intranet
-   when the mobile
§   vpn ip pool can link
§   mobile support proxy server (setting the group policy for proxy server)
§   not supporting nat
§   need 2 network cards
§   only support one IP

·   network link requirement


***VPN link

***MDM 08 Deployment topology
Device management server (sub title)

IPSEC MOBIL VPN

***MDB device management server
-   location
i.   intranet
-   utility   
i.   use to manage all controlled device
ii.   offer mobil device group policy, software patch, remote hard reset
iii.   CA and domain controller integration
iv.   Coordinate the communication between AD and CA

*** The benefit of Security Management
-   SCMDM enhance the management the active directory group policy
-   Disable other functions

***Group policy process
-   set up the policy of group (Windows active directory, SYS VOL)
-   Mobile Device Management server (group policy service) use OMA Proxy engine ->windows mobile device à DB

-   GPMC -> view the modeling, and results

***Reporting / Software
-   Windows Software Update Service (WSUS) 3.0
-   Offer convenient and handy deployment


***Create Package Wizard – software patch
-   Create to package software
-   Approve to certain group
-   Progress engine

***Software and HD list
-   Enroll devices information
-   device report
-   installed (policy)



***link to vpn (ddn)
??only 6.0 can use the MDM
?? if no enroll, how to manage that device
? auto-install, msg to install

***MDM Resource Kit
Auto loging  portal website
- Mobil device
·   Connect now
·   Vpn diagnostics
·   Device status viewer

- Server side tool
·   MDM Bulk Pre-Enrollment Tool
·   MDM applications Hash Code Tool

***requirement
-must
·   need server 2003 enterprise 64 bit
·   powershell 1.0
·   windows mobil 6.1

- option
·   exchange server

***resouce from 劉一寬經理

21

Tech Ed Opening seminar Notes

Dynamic it
Enabling it pros and development teams across the IT Lifecycle

Manage complexity
Achieve agility
Protect information,
Control access
Advance the business with it solutions
Amplify the impact of your people

(business productivity
application platform
core infrastructure
infrastructure optimization

Dynamic IT

***virtualization
desktop
server
application
presentation

conclude by system center (management)

12%
virtualized

**Microsoft environment
111,451 vista client
167,000 sharepoint

hyper-v
save money
virtual server 2005 & hyper v
virtual machine

sql 2005

virtual machine work exactly the same from 20 days to one days

sql, sharepoint, print adctive directory name,

Microsoft system virtual machine management center

Hyper-v


Deliver in less 24 hours by virtualization. Excel virtual infrastructure


System center virtual machine center

MSDN site and tech-net are all on virtual servers.

VMwre virtual center


***demo virtual machine manager
view the servers
View by host
Build the virtual pc
In this unified interface ß schedule and the tasks can view

- different operation role can have different view
-   use the web to see the desktop of different virtual pc
-   hyper v and vmware servers
-   to see the task and component running status and log
-   use the different application role
-   in the virtual diagram to view the network card and ports
-   to do the on line backup by snapshot– backing snapshot
-   vm ware - plication


Interoperability – microsoft’s principles
Enable dynamic it operations

Ensuring open connections
Data portability
Enhanced support for standards
Open engagement

(by vista, .net, sql server, server, exchange server, office share point server)



***next-generation applications
services
model-driven
visual studio team system à self-healing infrastructure, (role-based analysis & design tools), applications designed for operations, next generation declrative languages

integrated & repositories

(service)
integrated data

***sql server 2008 (big title)  (your data any place, any time) (subtile) intelligent data platform (down title)
-   trusted ( reliable, trusted platform)
o   protect your information
o   ensure business continuity
o   predicatable response


-   productive
o   reduce time & cost
§   manage by policies
§   simplify application development
§   store any information

-   intelligent
o   drive actionable insight
§   integrate any data
§   deliver relevant information
§   drive actionable insights
§   

customer demo Kingston
-   CFO
-   Deduct the server number, the delivery data should be all stored in Taiwan
-   Data impress to shrink the data data
-   Back buck the data with 1/5 time
-   Back up storage deduct 50%
-   Deduct the server number, the delivery data should be all stored in Taiwan
-   Data impress to shrink the data data
-   Back buck the data with 1/5 time
-   Back up storage deduct 50%
-   Server policy management
o   To old Data
o   In the virtual server and change link
     -



***demo

-   policy management
o   set up in evaluation – to scan all the sql server performance
-   resource management
o   view all the resource
o   can allocate the percentage of cpu usage
-   file stream can stored in the db server
-   link the video with the point on the map route can stored
-   I can view the upload the video
-   Embedded api can support the programming




***demo 2
-   now through the add-in we can do the data mining in excel
-   report viewer (double y axis) (big amount and low amount)
-   temperature
-   report component – pacifics ( selling amount and selling value can show in the same table)




user-focused experiences (title)

-   BI + portal applications (oofice, office sharepoint )
-   rich client application (WPF and .net compact framework)
-   rich internet applications (silverlight)

-------------------------------------------------------------------------------------------------------
IE 8
***demo 1

-   right click to translate
-   right click to view the yahoo kimo dictionary
-   right click to view wiki
-   to buy to by right click on amazon.com
-   click the address and right click to use live map

***demo2
-   mega v
      
-   silverlight can view different view
-   deep live
-   view the magazine on mix


高階戰情室系統

-------------------------------------------------------------------------------------------------------Moving to software + service
-   Saving
o   Turn capital cost into operational expense
o   Consisten, familiar S+S technoldeveloper ogy
o   Lower tco of hardware and IT operations

Software + Services strategy

-   Lve services
o   Windows Live   
o   Xbox LIVE
o   Office Live Workspace
o   Office live small business

-   online services
o   
-   , 3rd party apps and solutions
Building block &



 ***Working Together
-   launch Wave Momentum ( subtitle)
o   sql server
o   silverlight
o   essential business server
o   hyper v server
o   home server
o   small business server 2008

-   infrastructure optimization (subtitle)


*** Share Ideas & information
- tech net and msdn (subtitle)





--resource from Steve Guggenheimer speech

22
程式討論版 / vs 2008 好用的
« 於: 2008-09-22 12:11 »
**linklabel (text)

linklabel1.linkvisited = true

** system.diagnostics.process.start

system.diagnostics.process.start ("IExplore.exe" , "http://www.microsoft.com/taiwan/learning/books/defaults.mspx")

system.diagnostics.process.start( "Winword.exe", "c:\myletter.doc")


**timer


**debugging

代碼: [選擇]
try
  picturebox1.image = system.drawing.bitmap.fromfile ("d:\fileopen.bmp")

catch when err.number = 53 'can not find file
 msgbox ("please put cd in the cd rom reader")
     
     try
         picturebox1.image = system.drawing.bitmap.fromfile("d:\fileopen.bmp")
     catch
         msgbox ("can not use, please check the cd rom function!")
         button1.enabled = false
     end try
catch when err.number = 7 'out of memory
 msgbox ("is this really jpeg",, err.description)
catch
  msgbox ("system loading file error", , err.description)



***dynamic array

dim temperature() as single

dim days as short
days = inputbox ("how many days", "build array")
redim temperatures (Days -1)


for i = 0 to ubound (temperatures)
   temperatures(i) = inputbox (prompt, title)
next



finally
end try


代碼: [選擇]

try
    err.raise(61)
catch when err.number = 61
   msgbox ('error: disk is full")
end try



***controls
dim ctrl as control
for each ctrl in controls
    ctrl.left = ctrl.left + 25

next


***file writer
savefiledialog1.filter = "text files (*.txt)|*.txt"
savefiledialog1.showdialog()
if savefiledialog1.filename <> "" then
 fileopen(1, savefiledialog1.filename, openmode.output)
 printline(1, txtnote.text) ' copy text to disk
 fileclose(1)
end if


***CLASS
Public Class Person
    Private Name1 As String
    Private Name2 As String


    Public Property FirstName() As String

        Get
            Return Name1
        End Get

        Set(ByVal value As String)

            Name1 = value
        End Set

    End Property

    Public Property Lastname() As String
        Get
            Return Name2

        End Get

        Set(ByVal value As String)
            Name2 = value

        End Set
    End Property

    Public Function Age(ByVal Birthday As Date) As Integer
        Return Int(Now.Subtract(Birthday).Days / 365.25)

    End Function

End Class

**USE CLASS
Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim Employee As New Person
        Dim DOB As Date

        Employee.FirstName = TextBox1.Text
        Employee.Lastname = TextBox2.Text
        DOB = DateTimePicker1.Value.Date

        MsgBox(Employee.FirstName & " " & Employee.Lastname _
               & "is " & Employee.Age(DOB) & "years old")
    End Sub
End Class


***PRINT
Imports System.Drawing.Printing

Public Class Form1

    'Sub for printing text
    Private Sub PrintText(ByVal sender As Object, _
      ByVal ev As PrintPageEventArgs)
        'Use DrawString to create text in a Graphics object
        ev.Graphics.DrawString(TextBox1.Text, New Font("Arial", _
          11, FontStyle.Regular), Brushes.Black, 120, 120)
        ' Specify that this is the last page to print
        ev.HasMorePages = False
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' Print using an error handler to catch problems
        Try
            ' Declare PrintDoc variable of type PrintDocument
            Dim PrintDoc As New PrintDocument
            AddHandler PrintDoc.PrintPage, AddressOf Me.PrintText
            PrintDoc.Print()   'print text
        Catch ex As Exception  'catch printing exception
            MessageBox.Show("Sorry--there is a problem printing", ex.ToString())
        End Try
    End Sub
End Class





23
請問如何改善asp .net 的效能 到 跟asp 一樣快?

以前同事用asp連資料庫(透過撥接都可以上),現在說透過撥接 asp.net慢到不能用,請問各位前輩先進有無改善asp.net效能的寶貴經驗?

先謝謝囉~~
代碼: [選擇]

Tool:
Visual studio team edition for tester or visual studio team suite
Support recording the operation webpage
Support webpage unt test
Support web function test
Support loading test

Visual Studio 2008 Team Load Test Agent
Support big scale
Msdn web performance


Analyzer web page performance Tool
Microsoft log parser
1、 The most slow response web page
2、 The most being viewed web page
SQL Server Report Pack for IIS Log
3、 2004 good to view
4、 Core Pase

Microsoft SQL Server Analysis Service + Microsoft Excel
5、 Advanced performance analysis
6、 Tivot analyzing Table, Pivot Chart
7、 Import IIS log to import to SQL server by Log parser


***Demo
Visual studio
Add one website project
Default.aspx

 Login.aspx
Log in control
Align center
Add “Log in” control, use the format
Web.config
1、 Project asp.net 組態
2、 Security/ authenfication/from web/ anonymous deny
3、 Forms name=”website1” loginurl=”login.url”
4、 Copy the connection string to replace on connect string
Web.config
In the norwind add user table
ID(int) identity reconization format, PK
username, password
named users


*. Tem database version
. add one project
. import database instructure
l Pick up northwind
l Database project
l

Database
1. Data generation plan
2. Add data generation plan
3. Unchecked the others
4. Left users,  regular expression, generate pattern (   user [0-9]
5. Password, regular expression, generate pattern (     password[0-9]  )
6. 50 records
7. Generate records
8. Pick up DB
9. Clear then insert
10. To simulate the real loading
Use team database toward LoginCheck to do the Unit test
Go to login.aspx
5、 Add name space within “解析”
6、 Run SP “login check”
7、 Write SP
8、 Build and run


Test again
表單張貼參數,加入資料來源,northwind , user table
Sequential/random
User pick up DB/users/username
Password pick up DB/users/password
Plus loading test, user view 總測試數, 測1分鐘
Sql tracking start / sql tracking 都選擇
測試清單編輯器

Tool
Visual Studio 2008 Team Load Test Agent
Controller
1、 Write data into SQL
Agent
2、 Sending request
One agent 2000 users simulation

***Report
Codeplex.com/loadtestreports
Download load_test_report
Unzip
1、 Loadtestreport
2、 Summary report
3、 Counter values per time

***Visual studio 2008 report
Controller and agent
Checking result
Log-in check
1、 Exec logincheck

***Reporting Service
Log Parser
1、 Start IIS as default web site
2、 W3C/進階 checked all item

3、 Overlay context
4、 Load Test Statistics
5、 View State and Loadview state
6、 Counter (平均的頁面時間)
Log Parser
7、 View most viewing webpage
8、 Build your self DB Schema and pull in the log data
9、 The ten web pages top 10 slow
SQL Server Report Pack for IIS
10、 Pages summary
i. 2008 pick up what page take how many connection and percentage
ii. The top 1 web should be picked up as the top 1 tunning page
iii. Spent how many hours,

*** write sql query and post in the excel


***List the basic Tunning statistic
Find out the bottle neck of the efficiency
Cahe and no cache
1、 In memory always wins
2、 If your page need to get the web service or file content , ro db record to put into memory
3、 Use webpage and outputCache
4、 <%@ OutputCache Duration=”60”
VarybyParam=”none”
VarybyCustomer=”browser” %>
5、 Use substitution control
i. Methodname = “GetuserName”
ii. <asp:substitution
Micro Caching idea
6、 Put in the caching in the very short time
7、 <%@ OutputCache Duration=”2”
VarybyParam=”none”
VarybyCustomer=”browser” %>
8、 Pre-request Caching
i. User request data in cache
ii. http.context.current.item
1. put all data in the http.context.current.item

State Bag Access Pattern
9、 If (Cache[“customers”] == null
10、 List<Cusomer> my list = Cache
11、 Race condition
12、 Stale Data
i. Clear the memory content after data updating
ii. Use SQL Cache Dependency
1. http://msdn.mic/en-us/library/ms178604.aspx
13、 Microsoft Velocity support In many server support memory cache
Write Cache (緩存計術)
14、 Lower the times to write to DB and file
15、 Accompany log function
16、 How to :
i. Cache
ii. Microsoft Message Queue

DataSource control cache
17、 Sqldatasource, accessdatasource
18、 Objectdatasource, xmldatasource
19、 enableCaching = true


Databound control efficiency (Grid View or Repeater)
20、 Repeater light better
21、 Grid View 3.61
Data Source and UI Paging (no paging result system loading), UI paging -> result the in-efficiency
22、 Linq: one time for 10 pages
23、 Server side paging (grid view allow paging)
24、 Objectdatasource
i. Maximurowsparametername=”maxrows”
ii. Startrowindexparametername=”startrows”
iii. Selectmethod=”select cusomter”
iv. Linq : startrows, max rows
v. UI: 8.03 , datasource : 5.01

View state and no view state
25、 Turn off the viewstate : Enableviewstate to false
26、 3.97 ->2.25

Sync or not sync
27、 Async = true
28、 Asp.net ajax
i. Clientscriptcallback
29、 Compliation debug = false
Ajax or not ajax



和IIS效能有關的設定   

-------------------

1) Use IIS 6 Kernel Caching

   <httpRunTime enableKernelOutputCache="true" . . ./>

2) Use IIS GZIP compression function

   編輯\Windows\System32\inetsrv\Metabase.xml, 找到gzip的<IIsCompressionScheme>, 將HcScriptFileExtensions屬性修改成="aspx asp dll exe"

 

source from  王寧疆

0. sense if the source is from slow connection, use html contrl instead of web control

to be done, log parser search

How to improve IIS performance
1.   change the asp.net
   enable compression

to be done and search

2.   enable cache in the asp.net page

2.1   Cahe and no cache (efficency a lot of different)
代碼: [選擇]

<%@ OutputCache Duration=”60”
                 VarybyParam=”none”
VarybyCustomer=”browser” %>

to be done and search


2.2.   Micro Caching idea
i   Put in the caching in the very short time
ii   <%@ OutputCache Duration=”2”
VarybyParam=”none”
VarybyCustomer=”browser” %>


3.   turn off the view state (efficiency a lot of different)
can not done

3.1   Turn off the viewstate : Enableviewstate to false
3.2   3.97 ->2.25

4.         turn debug to false
   Compliation debug = false
done

***List the basic Tunning statistic
1.   Find out the bottle neck of the efficiency
         
  1.1   tinyget
i.   tinyget -srv:www.YourServer.com -uri:
ii.   tinyget -srv:localhost -uri:/BuggyBits/Links.aspx -loop:4000
b.   to view the status code match expected one

1.2.   log parser

1.2.1 以滑鼠右鍵按一下以開啟記錄, 為您要網站, 然後按一下 [ 內容 ] 。
在 [ 網站 ] 索引標籤, 選取 的 [ 啟用記錄 ] 核取方塊 。

請注意 [ 網站 ] 索引標籤上 的 [ 啟用記錄 ] 核取方塊 及 造訪記錄 在 [ 主目錄 ] 索引標籤必須先檢查是否記錄到會啟用。
在 [ 當前日誌格式 ] 清單選取格式。
按一下 內容 ] , 按一下 [ 進階 ] 索引標籤, 然後再選取項目, 您要監視記錄檔中

請注意 : 按一下 [ 內容 ] 如果您選取 [ ODBC 記錄 , 提供 ODBC 資料來源名稱 (DSN)、 資料表、, 使用者名稱和密碼, 然後按一下 [ 確定 ]

1.2.2
a.   in command window, type
i.   logparser “select count(*) from u_ex*.log”
ii.   logparser “select sc-status, count(*) from u_ex*.log gourp by sc-status”
iii.   logparser -o:IIS "select * into merged.log from ex*.log"

1.3.   wcat


1.4   performance counter

1.5 sql server profiler

1.6 sql server management studio
1.6.1 activity manager
1.6.2 dynamic management views
1.6.3 table scan
1.6.4 clustered index scan

1.7 CLR profiler
1.7.1 processor time
1.7.2 disk time
1.7.3 page/sec


3.   Use substitution control
i.   Methodname = “GetuserName”
ii.   <asp:substitution

need to search

5.   Pre-request Caching
i.   User request data in cache
ii.   http.context.current.item
1.   put all data in the http.context.current.item

4.   State Bag Access Pattern
甲、   If (Cache[“customers”] == null
乙、   List<Cusomer> my list = Cache
丙、   Race condition
丁、   Stale Data
i.   Clear the memory content after data updating
ii.   Use SQL Cache Dependency
1.   http://msdn.mic/en-us/library/ms178604.aspx
戊、   Microsoft Velocity support In many server support memory cache
5.   Write Cache (緩存計術)
甲、   Lower the times to write to DB and file
乙、   Accompany log function
丙、   How to :
i.   Cache
ii.   Microsoft Message Queue

6.   DataSource control cache
甲、   Sqldatasource, accessdatasource
乙、   Objectdatasource, xmldatasource
丙、   enableCaching = true


7.   Databound control efficiency (Grid View or Repeater)
甲、   Repeater light better
乙、   Grid View 3.61
8.   Data Source and UI Paging (no paging result system loading), UI paging -> result the in-efficiency
甲、   Linq: one time for 10 pages
乙、   Server side paging (grid view allow paging)
丙、   Objectdatasource
i.   Maximurowsparametername=”maxrows”
ii.   Startrowindexparametername=”startrows”
iii.   Selectmethod=”select cusomter”
iv.   Linq : startrows, max rows
v.   UI: 8.03 , datasource : 5.01

9.   View state and no view state
甲、   Turn off the viewstate : Enableviewstate to false
乙、   3.97 ->2.25

10.   Sync or not sync
甲、   Async = true
乙、   Asp.net ajax
i.   Clientscriptcallback
丙、   Compliation debug = false
11.   Ajax or not ajax
12.   



代碼: [選擇]

IIS 7.0
Server 2008 plus

? How to improve IIS performance
change the asp.net
enable compression
enable cache in the asp.net page
turn off the view state



**debug
use firefox debugging tool


***IIS 6.0 to IIS 7.0
buy upgrade kit

600 vroots
350 iss web applications
11 application pools
windows server 2008 enterprise x64
early adoption of  MS OS

? efficency comparision
? real statistic to approve it


lab testing
single productin servr (offline)
single production server (live load)
single server cluster (20)
preproduction and staging
full production deployment


***build base image, on the test server

Intergrated lights-out
install 2008
use servermanagercmd.exe
a. servermanagercmd.exe –I web-server web-common-http  WAS
sysprep
b. server name set up (mini setup)
use imagex to build image file (OS partitions only)
waik
imagex /config c:\imaging\<configuration_list>.ini /capture d:d:\imaging\data.wim "Drive D"


***Deploy to other servers
***setup the server role
www.microsoft.com include
a. iis
b. distributed file system replication (DFSR)
IIS role service
c. Only install the service you want. IIS 6 WMI compatibility provide Windows management instrumentation (WMI)


***IIS migration tool kit
use the scipts to upgrade IIS 6.0 to IIS 7.0

test and pressure test tool use TinyGet and Web Capacity Analysis Tool (WCAT)
what’s the differences between TinyGet and WCAT?

you can find them in IIS resource Tool Kit

Integrated mode for big 5 will error, classic mode




Tools
sysprep
imagex
web deployment tool
appcmd
servermanagercmd.exe
legacy scripts

***test & pressure test

 
4. 以滑鼠右鍵按一下以開啟記錄, 為您要網站, 然後按一下 [ 內容 ] 。    
5. 在 [ 網站 ] 索引標籤, 選取 的 [ 啟用記錄 ] 核取方塊 。

請注意 [ 網站 ] 索引標籤上 的 [ 啟用記錄 ] 核取方塊 及 造訪記錄 在 [ 主目錄 ] 索引標籤必須先檢查是否記錄到會啟用。    
6. 在 [ 當前日誌格式 ] 清單選取格式。    
7. 按一下 內容 ] , 按一下 [ 進階 ] 索引標籤, 然後再選取項目, 您要監視記錄檔中

請注意 : 按一下 [ 內容 ] 如果您選取 [ ODBC 記錄 , 提供 ODBC 資料來源名稱 (DSN)、 資料表、, 使用者名稱和密碼, 然後按一下 [ 確定 ]

tinyget
i. tinyget -srv:www.YourServer.com -uri:
ii. tinyget -srv:localhost -uri:/BuggyBits/Links.aspx -loop:4000
b. to view the status code match expected one

log parser
c. in command window, type
i. logparser “select count(*) from u_ex*.log”
ii. logparser “select sc-status, count(*) from u_ex*.log gourp by sc-status”
iii. logparser -o:IIS "select * into merged.log from ex*.log"

wcat
d.


***Tinyget
need tinyget and log file
log file (sql server

***experiences sharing
one time do one big amendment
a. 32 bit and 64 bit app pools can exist at the same time
cooperate as early as possible
use Web deployment tool
use tinyget and wcat to do the log playback

*** IIS set
not need to do the metadata
machine config (.net) -> web.config (asp.net)

***delegated configuration
applicationhost.config seeting  allow certain program in the web.config
default document
directorybrowse
validation
httperros
modules
in web.config

***shared configuration
setting up the configfile on the unc share
use domain or local account

***experience
direct replicate applicaitonhost.config
app pool setting change will result recycle (eg application pool restart , pipeline mode)
back up the system
%windir%\system32\inetsrv\appcmd add backup “My Backup”
default value in schema

**efficiency
dynamic and static impression  (1/10) download
10 % Requests/Sec






Resource from胡士亮


24
請問如何解決proxy中 cache到error page的問題?

Now we encountered certain pages returns from Singapore proxy are cached in "error page" , not the newest correct page.

 To add http://*.cits.com in the "proxy Bypass" (proxy Exceptions) list solved this problem, but every time after user restarted his pc, his proxy bypass setting is reset as the default.

公司架構,各個區域都有各自的proxy,當server移植upgrade時,proxy cache到error pages.
 
solutions:
1)
We request to add http://*.cits.kns.com in the "proxy Bypass" (proxy Exceptions) list of Singapore domain server (SMS server, login script) to help user overcome that proxy error page caching situation.

2)set up the proxy acess control list (ACL) to go direct within http://*.cits.com

3)set up the live time for web pages in proxy

以上為想得到的solutions, 還有更好的辦法嗎?


25
***outlook object
Application object
NameSpace object
==============
代碼: [選擇]
'列出信箱所有信
Set oInbox = Application.GetNameSpace("MAPI").GetDefaultFolder(6)
Set oItems = oInbox.Items
'Notice how you can get the count
For i = 1 to 3
Msgbox oItems(i).Subject
Next



MAPIFolder object
代碼: [選擇]
Dim WithEvents oApp As Outlook.Application
Dim WithEvents oNS As Outlook.NameSpace
Dim WithEvents oItems As Outlook.Items
Dim oFolders As Outlook.Folders
Dim oFolder As Outlook.MAPIFolder
Dim WithEvents oExplorer As Outlook.Explorer

'get the folder by specific name
Set oNS = oApplication.GetNamespace("MAPI")
Set oFolder = oNS.Folders("Public Folders").Folders("All Public Folders").Folders("CITS")

'list all folders
Set oFolders = oNS.Folders("Public Folders").Folders( _
         "All Public Folders").Folders

If Not (oFolders Is Nothing) Then
        Set oFolder = oFolders.GetFirst
        Do While Not (oFolder Is Nothing)
           'ListFolderscontent oFolder
           If oFolder Is Nothing Then
              Set oFolder = oFolders.GetNext
           Else
              Exit Do
           End If
        Loop

end if




代碼: [選擇]
'find out folder by link
strURL = "file://.//companydomain/myfolder/Events/"

strSQL = "SELECT ""urn:schemas:httpmail:subject"" " & _
   "FROM """ & strURL & """"


Explorer object
代碼: [選擇]

Set myPane = myExplorer.Panes("OutlookBar")
Set myPanecontent = myPane.Contents


Items collection
Inspector object
PostItem object
Pages collection

MailItem object


代碼: [選擇]
Set conn = New ADODB.Connection
With conn
   .Provider = "exoledb.datasource"
   .Open strURL
End With
'Create a new Recordset object
Set rst = New Recordset
With rst
   'Open Recordset based on the SQL string
   .Open strSQL, conn
End With

If rst.BOF And rst.EOF Then
   Msgbox "No values found!"
   End
End If

iCount = 0
rst.MoveFirst
Do Until rst.EOF
   iCount = iCount + 1
   strFrom = rst.Fields("urn:schemas:mailheader:from").Value
   Debug.Print "From: " & strFrom
   rst.MoveNext
Loop
Debug.Print "There are " & iCount & _
   " distinct FROM addresses in your inbox."


代碼: [選擇]
'get mails by .net
 using   System.Reflection;   
  private   void   ReadMail()   
  {   
        ADODB.RecordsetClass   aRS   =   new   ADODB.RecordsetClass();   
        ADODB.ConnectionClass   aConn   =   new   ADODB.ConnectionClass();   
        string   strurl   =     @"file://./backofficestorage/"+GetDomainName+"/mbx/"+strchanged+"/收件箱/";   
      //GetDomainName = exchange server domain
      //strchanged = mail receipt name

          aConn   .provider="exoledb.datasource";   
          aConn   .Open(strurl,String.Empty,String.Empty,0);   


          string   strQ="";   
          strQ   =   "select   ";   
          strQ   =   strQ   +   "   \""urn:schemas:mailheader:thread-topic"\"";   //topic       
          strQ   =   strQ   +   ",   \""urn:schemas:httpmail:displayto"\"";   //receipt name   
          strQ   =   strQ   +   ",   \""urn:schemas:httpmail:displaycc"\"";   //cc name 
          strQ   =   strQ   +   ",   \""urn:schemas:httpmail:thread-topic"\"";   
          strQ   =   strQ   +   ",   \""urn:schemas:httpmail:priority"\""   ;//priority
          strQ   =   strQ   +   ",   \""urn:schemas:httpmail:importance"\""   ;   //importance   
            strQ   =   strQ   +   ",   \""urn:schemas:mailheader:message-id"\"";   
          strQ   =   strQ   +   ",   \""urn:schemas:httpmail:htmldescription"\"";//mail content   
          strQ   =   strQ   +   ",   \""urn:schemas:httpmail:subject"\"";   
          strQ   =   strQ   +   ",   \""urn:schemas:httpmail:sendername"\"";   
          strQ   =   strQ   +   ",   \""urn:schemas:mailheader:received"\"";   //receive date
          strQ   =   strQ   +   ",   \""DAV:contentclass"\"";     //content class 
          strQ   =   strQ   +   ",   \""DAV:displayname"\"";     //displayname
          strQ   =   strQ   +   ",   \""DAV:id"\"";     //mail primary key id
          strQ   =   strQ   +   ",   \""DAV:href"\"";     
          strQ   =   strQ   +   "   from   scope   ('shallow   traversal   of   "   ;//what kind of search
          strQ   =   strQ   +   "\""   strurl     +   "\"')   ";   
          strQ   =   strQ   +   "where   \""urn:schemas:mailheader:message-id"\"='"+itemtypes+"'and   \""DAV:contentclass"\"<>'urn:content-classes:document'";   

        aRS.Open(strQ   ,aConn,ADODB.CursorTypeEnum.adOpenForwardOnly,ADODB.LockTypeEnum.adLockReadOnly,0);   
        while(!aRS.EOF)   
        {   
                    Response.Write("mailconten"+aRS.Fields("urn:schemas:httpmail:htmldescription").Value.ToString());   
                    string   strmsgurl=strurl+aRS.Fields("DAV:displayname").Value.ToString();   
                    CDO.MessageClass   cMsg=new   CDO.MessageClass();   
                    cMsg.DataSource.Open(strmsgurl,o,ADODB.ConnectModeEnum.adModeRead,ADODB.RecordCreateOptionsEnum.adOpenIfExists,ADODB.RecordOpenOptionsEnum.adOpenSource,String.Empty,String.Empty);     
                      if(cMsg.Attachments.Count>0)   
  {   
          foreach(CDO.IBodyPart   ibd1   in   cMsg.Attachments)   
          {   
                              }   
  }   
                  Rs.MoveNext   
        }   
  }




Page object
ContactItem object
Controls collection
AppointmentItem object
Control object
MeetingItem object


TaskItem object
AddressLists collection
Recipients collection
AddressList object
Recipient object
AddressEntries collection
UserProperties collection
AddressEntry object
UserProperty object
Folders collection
FormDescription object

 
***regedit
[HKEY_CURRENT_USER\Software\Policies\Microsoft\Office\9.0\Outlook\Webview\mailbox]
"url"="http://YOURLOCATION/default.htm"
"navigation"="yes"





建立表單和控制項
1. 開啟您的 [ 收件匣 ], 然後開啟新郵件表單。 
2. 表單, [ 工具 ] 功能表上按一下 [ 「 設計表單 Outlook ] 」 進入設計模式。 
3. " 顯示此頁面 」 在表單 ] 功能表, 按一下 [ 按一下 [ (P.2) ] 索引標籤, 並。 
4. 在 [ 表單 ] 功能表, 按一下 [ 工具箱 」 控制項 ] 」 以顯示 [ 控制工具箱 ]。 
5. 拖曳至頁面的表單 P.2 ComboBox 控制項。 
6. 拖曳至頁面的表單 P.2 TextBox 控制項。 

回此頁最上方

ComboBox 控制項繫結至欄位
名為 Field 1, 至 ComboBox 控制項欄位, 繫結執行下列步驟。 這個欄位是 Red、 Blue 和 Green, 的可能值。 1. 在 P.2 表單頁面, 使用您的下拉式方塊按一下滑鼠右鍵並在快速鍵功能表, 按一下 [ 內容 ]。 
2. 按一下 [ 數值 ] 索引標籤及 [, 新增 ] 以建立新的使用者定義欄位。 
3. 在 [ 名稱 ] 方塊, 再鍵入 Field 1 及確定 ], 以返回到 [ 內容 ] 對話方塊。 Field 1 是任意使用者定義欄位名稱。 
4. 在越慢越好 「 值 」 方塊, 紅色; 綠色; 藍色輸入然後按一下 [ 確定 ] 

回此頁最上方

TextBox 控制項繫結至同一個欄位
執行下列步驟也控制 TextBox 項繫結至 Field 1 欄位。 1. 以滑鼠右鍵按一下文字方塊控制項然後在快速鍵功能表, 按一下 [ 內容 ]。 
2. 按一下 [ 數值 ] 索引標籤, 按一下 [ 選擇欄位 ], 按一下 [ User - defined, 收件匣 ] 中的欄位然後按一下 Field 1 欄位。 
3. 按一下 [ 確定 ] 以關閉 [ 內容 ] 對話方塊。 
4. 在 [ 工具 ] 功能表, 按一下 [ 「 設計表單 Outlook ] 」 以結束設計模式。 
當您按一下可供選取 Red、 Blue 或綠色下拉式方塊, 您選擇自動填入 TextBox。

26
vb ide can coding on the break mode, but vb .net can not.

dubug run key
-------------
- run/start (F5)
- run step (F11)
- run setp not enter in the sub (F10)
- 中斷點 (Ctrol +B)
- stop run ( Ctrol+Alt+Break)

windows
--------
* command (命令)
  -one samll vb commnad line
  - ? variableabc (use ? in vb.net instead of print in vb)

* call stack ( 呼叫堆疊)

*Watch window (監看視窗)
  -add new watch

*breakpoint
   - Breakpoint/ filter/ condition, edit by right click
   
   
*output
   - Debug.writeline("print every msg in line")
   - Debug.write("all the msg will connect in one line")
   - Debug.writelineif (Variable >0 , "this variable is bigger than 0")
   - debug.assert (true, "assert means if the condition is true, it will not show")
   - debug.assert (false, "so this line will be shown by the dialog box")


*auto window(自動變數)
   - view all now automatically variable

*local window(區域變數)
   - view all local variable


代碼: [選擇]
Try
            Debug.WriteLine("Codes Area....")
            Dim intOverflow As Integer = 1234567890
            Dim intA As Integer = 0
            Dim intB As Integer = 0
            intA = intA / intB

        Catch eh As DivideByZeroException
            Debug.WriteLine("Catch Area: Divide By Zero Error")
        Catch eh As OverflowException
            Debug.WriteLine("Catch Area:Overflow Error")

        Finally
            Debug.WriteLine("Finally Area")

        End Try



代碼: [選擇]

[Private|public] [sub|function] Example() [as VarialbeType]
[b]On error Goto [/b] [i]Label[/i]

'your codes

Exit [Sub|Function]

Label:

   'exception handeling

    [Resume|Resume Next|Resume LineNubmer|Err.Raise]
   
End [Sub|Function]



 -resume means resume to the error happening codes and keep running
 - resume next runs from the next code line
 - resume label run from the label
 - err.raise number:=number using code to the upper level error handling


27
Public cmdNewBar As CommandBar
Public WithEvents ctlBtn As CommandBarButton
Public WithEvents ctlBtn2 As CommandBarButton


Private Sub ctlBtn_Click(ByVal Ctrl As Office.CommandBarButton, CancelDefault As Boolean)

' Worksheets("Sheet1").Range("A2").Value = 3.14159

'Worksheets("¤W¥«").Range("A2").Value = 3.14159

If Ctrl.Caption = "Colorize Issues And Actions" Then
ColorizeIssuesAndActions
End If

If Ctrl.Caption = "Set Issue Status Colours" Then
SetStatusColours
End If



End Sub


Private Sub Workbook_BeforeClose(Cancel As Boolean)
 On Error Resume Next

Application.CommandBars("ColorizeIssue").Delete


End Sub

Private Sub Workbook_Open()

 On Error Resume Next

Application.CommandBars("ColorizeIssue").Delete

Set cmdNewBar = Application.CommandBars.Add

cmdNewBar.Name = "ColorizeIssue"
With cmdNewBar

        Set ctlBtn = .Controls.Add(msoControlButton)
       
            With ctlBtn
            .Style = msoButtonIconAndCaption
            .BeginGroup = True
            .Caption = "Colorize Issues And Actions"
            .TooltipText = "Colorize Issues And Actions"
            .FaceId = 59
            .Tag = "MyCustomTag"
            End With

        Set ctlBtn2 = .Controls.Add(msoControlButton)
       
            With ctlBtn2
            .Style = msoButtonIconAndCaption
            .BeginGroup = True
            .Caption = "Set Issue Status Colours"
            .TooltipText = "Set Issue Status Colours"
            .FaceId = 629
            .Tag = "MyCustomTag"
            End With


 .Protection = msoBarNoCustomize
 .Position = msoBarTop
 .Visible = True

  End With




'ColorizeIssuesAndActions
'SetStatusColours

End Sub


28
樓上各位大大的意見真的是彌足珍貴,orz 後來 公司的解決方式是:

通知user 裝firefox,或 IE 7.0,前兩個瀏覽器都有自動將網頁縮到列印紙張大小。

後來發現
http://smartwebprinting.com/ 的solution


29
網頁瀏覽和列印分別用不同的 CSS 去處理排版問題,
CSS 在這方面已經有很不錯的解決方案了。

感謝3秒的回應,你是說當user按下友善列印時,網頁套用到其他的css 嗎? 那個是否解決了PDF不認紙張的問題呢??


有天在 sourceforge 上 search pdf 找到了
http://sourceforge.net/projects/pdf-factory/

http://pdfapi2.sourceforge.net/
不知有沒有人用過 ;D
逛了http://sourceforge.net/projects/pdf-factory/ <---這個是與php  配套的,
http://pdfapi2.sourceforge.net/  <---這個是與perl  配套的,

那.net呢? 有人有經驗可以分享嗎?



30
Good Idea!

可以說仔細一點嗎?

頁: [1] 2 3 ... 21