Posted
Filed under asp,asp.net
[원문] -  http://support.microsoft.com/kb/q195951/

문서에서는 쿼리 및 ADO (ActiveX 데이터 개체) 에서 ASP (Active Server Pages) 페이지를 사용하는 Excel 스프레드시트의 정보를 업데이트하는 방법을 보여 줍니다. 이 문서에서는 또한 이러한 유형의 응용 프로그램에 관련된 제한 사항을 설명합니다.

중요: 다중 사용자 액세스 ASP/ADO 응용 프로그램을 지원하지 않지만 Excel 스프레드시트를 않습니다. 따라서 쿼리 및 정보를 업데이트하는 이 방법은 다중 사용자 동시 액세스가 지원하지 않습니다.

추가 정보
이 샘플의 Excel 스프레드시트의 데이터를 액세스하려면 Excel Microsoft ODBC 드라이버를 사용하십시오. Excel 스프레드시트에...

이 샘플의 Excel 스프레드시트의 데이터를 액세스하려면 Excel Microsoft ODBC 드라이버를 사용하십시오. Excel 스프레드시트에서 명명된 범위를 만들어 데이터에 액세스할 수 있는 테이블을 만듭니다.

샘플 응용 프로그램 만드는 단계

  • Excel 파일을 ADOtest.xls sheet1 다음 데이터에 만들기:

    표 축소표 확대
    column1 column2 column3
    rr 15
    bb Test 20
    ee 작동 25

    참고 Excel 스프레드시트의 열을 텍스트와 숫자를 모두 포함되어 있으면 Excel ODBC 드라이버 열이어야 합니다 데이터 형식을 올바르게 해석할 수 없습니다. 열의 모든 셀에 같은 데이터 형식의 있는지 확인하십시오. 열의 각 셀 형식이 없거나 형식 혼합 사이에 "텍스트" 및 "일반" 권한이 다음과 같은 세 가지 오류가 발생할 수 있습니다.
    1. Microsoft OLE DB 공급자에 대한 ODBC 드라이버 오류 '80040e21'
      요청 속성은 이 ODBC 드라이버에서 지원되지 않을 수 있습니다.
    2. Microsoft OLE DB 공급자와 ODBC 드라이버 오류는 '80004005'
      즐겁고 키로 사용할 검색 가능한 열이 포함되어 있기 때문에 쿼리를 업데이트할 수 없습니다.
    3. Microsoft OLE DB 공급자와 ODBC 드라이버 오류는 '80004005'
      쿼리 기반 업데이트하지가 못했습니다. 업데이트할 행을 찾을 수 없습니다.
  • 명명된 범위, myRange1을 사용하여 스프레드시트를 만듭니다.

    1. 데이터가 상주하는 행 및 열을 영역을 강조 표시하십시오.
    2. 삽입 메뉴에서 이름을 가리킨 다음 정의를 클릭하십시오.
    3. 해당 이름 범위 이름을 myRange1 입력하십시오 이름.
    4. 확인을 클릭하십시오.
    명명된 범위 myRange1 다음 데이터가 포함되어 있습니다.

    표 축소표 확대
    column1 column2 column3
    rr 15
    bb Test 20
    ee 작동 25


    참고 ADO Excel 쿼리의 첫 번째 행에 열 머리글이 들어 있다고 가정합니다. 따라서, 명명된 범위 열 머리글이 포함되어야 합니다. DAO에서 동작이 있습니다.

    참고 열 머리글을 숫자를 사용할 수 없습니다. Excel 드라이버는 해석할 수 및 대신 셀 참조를 반환합니다. 예를 들어, "F1" 열 머리글 해석될 것입니다.
  • ODBC 시스템 데이터 원본 이름 (ADOTest.xls 파일을 가리키는 DSN)을 만듭니다.
    1. 제어판에서 ODBC 열 관리자.
    2. 시스템 DSN 탭에서 추가 클릭하십시오.
    3. Microsoft Excel 드라이버 (*.xls) 선택하고 마침 을 클릭하십시오. 이 옵션은 존재하지 않을 경우 Excel 설정에서 Excel Microsoft ODBC 드라이버를 설치해야 합니다.
    4. ADOExcel에 대한 데이터 원본 이름을 선택하십시오.
    5. 올바른 버전의 Excel 버전 설정되어 있는지 확인하십시오.
    6. 선택 통합... 를 클릭하고 해당 ADOTest.xls 찾은 파일과 확인을 클릭합니다.
    7. 사용하여 "옵션 >>" 단추 및 "읽기 전용" 확인란의 선택을 취소합니다.
    8. 확인을 클릭한 다음 다시 확인을 클릭하십시오.
  • ADOTest.xls 파일에 대한 사용 권한을 설정하십시오.
Active Server Page 익명으로 액세스할 경우 익명 계정 (IUSR_ <machinename>) 이상이 확인해야 할 스프레드시트 RW (읽기/쓰기 액세스를. 스프레드시트에서 정보를 삭제할 경우 그에 따라 사용 권한을 부여해야 합니다.

사용자의 Active Server Page 액세스를 인증하는 경우 응용 프로그램이 액세스하는 모든 사용자에게 적절한 권한이 있는지 확인해야 합니다.

참고 스프레드시트의 적절한 사용 권한을 설정한 경우 사용자가 오류 다음과 유사한 메시지가:

Microsoft OLE DB 공급자와 ODBC 드라이버 오류는 '80004005'

[Microsoft][ODBC Excel 드라이버] Microsoft Jet 데이터베이스 엔진이 '(알 수)' 파일을 열 수 없습니다. 이미 다른 사용자가 독점적으로 열려 또는 해당 데이터를 볼 수 있는 권한이 있어야 합니다.
  1. 새 ASP 페이지를 만들고 다음 코드를 붙여 넣습니다.
          <!-- Begin ASP Source Code -->
          <%@ LANGUAGE="VBSCRIPT" %>
          <%
            Set objConn = Server.CreateObject("ADODB.Connection")
            objConn.Open "ADOExcel"
    
            Set objRS = Server.CreateObject("ADODB.Recordset")
            objRS.ActiveConnection = objConn
            objRS.CursorType = 3                    'Static cursor.
            objRS.LockType = 2                      'Pessimistic Lock.
            objRS.Source = "Select * from myRange1"
            objRS.Open
       %>
       <br>
       <%
          Response.Write("Original Data")
    
          'Printing out original spreadsheet headings and values.
    
          'Note that the first recordset does not have a "value" property
          'just a "name" property.  This will spit out the column headings.
    
          Response.Write("<TABLE><TR>")
          For X = 0 To objRS.Fields.Count - 1
             Response.Write("<TD>" & objRS.Fields.Item(X).Name & "</TD>")
          Next
          Response.Write("</TR>")
          objRS.MoveFirst
    
          While Not objRS.EOF
             Response.Write("<TR>")
             For X = 0 To objRS.Fields.Count - 1
                Response.write("<TD>" & objRS.Fields.Item(X).Value)
             Next
             objRS.MoveNext
             Response.Write("</TR>")
          Wend
          Response.Write("</TABLE>")
    
          'The update is made here
    
          objRS.MoveFirst
          objRS.Fields(0).Value = "change"
          objRS.Fields(1).Value = "look"
          objRS.Fields(2).Value = "30"
          objRS.Update
    
          'Printing out spreadsheet headings and values after update.
    
          Response.Write("<br>Data after the update")
          Response.Write("<TABLE><TR>")
          For X = 0 To objRS.Fields.Count - 1
             Response.Write("<TD>" & objRS.Fields.Item(X).Name & "</TD>")
          Next
          Response.Write("</TR>")
          objRS.MoveFirst
    
          While Not objRS.EOF
             Response.Write("<TR>")
             For X = 0 To objRS.Fields.Count - 1
                Response.write("<TD>" & objRS.Fields.Item(X).Value)
             Next
             objRS.MoveNext
             Response.Write("</TR>")
          Wend
          Response.Write("</TABLE>")
    
          'ADO Object clean up.
    
          objRS.Close
          Set objRS = Nothing
    
          objConn.Close
          Set objConn = Nothing
       %>
       <!-- End ASP Source Code -->
    					
  2. 및 Active Server Page 이름을 저장하고 브라우저에서 봅니다. 다음 표시됩니다:
          Original Data:
    
          column1    column2    column3
          -----------------------------
    
          rr         this       30
          bb         test       20
          tt         works      25
    
    
          Data after the update:
    
          column1    column2    column3
          -----------------------------
    
          change     look       30
          bb         test       20
          tt         works      25
    					
참고 업데이트 이름 범위 첫 번째 행에 머리글이 후 수행되었습니다.

참조
자세한 내용은 Microsoft 기술 자료의 다음 문서를 참조하십시오. 190195  (http://support.microsoft.com/kb...

자세한 내용은 Microsoft 기술 자료의 다음 문서를 참조하십시오.
190195  (http://support.microsoft.com/kb/190195/ ) ExtractInformation DAO 사용하여 Excel 시트 시작 방법

본 문서의 정보는 다음의 제품에 적용됩니다.
  • Microsoft ActiveX Data Objects 1.0
  • Microsoft ActiveX Data Objects 1.5
  • Microsoft ActiveX Data Objects 2.0
  • Microsoft ActiveX Data Objects 2.1 서비스 팩 2
  • Microsoft ActiveX Data Objects 2.5
  • Microsoft Active Server Pages 4.0
  • Microsoft Data Access Components 2.5
키워드: 
kbmt kbcode kbhowto kbmdacnosweep KB195951 KbMtko
2010/10/19 17:29 2010/10/19 17:29
Posted
Filed under asp,asp.net
[원문 ] http://www.freeaspupload.net/freeaspupload/download.asp [다운로드 페이지]

To learn how to use this class in your site, read the instructions in the documentation page or download the example form that comes with the code.

Do not copy the code from this page, use the Download option. If you copy and paste, some lines of text may be broken by the browser because of their length.

Contents of freeASPUpload.asp:

<%
' For examples, documentation, and your own free copy, go to:
' http://www.freeaspupload.net
' Note: You can copy and use this script for free and you can make changes
' to the code, but you cannot remove the above comment.

'Changes:
'Aug 2, 2005: Add support for checkboxes and other input elements with multiple values
'Jan 6, 2009: Lars added ASP_CHUNK_SIZE
'Sep 3, 2010: Enforce UTF-8 everywhere; new function to convert byte array to unicode string

const DEFAULT_ASP_CHUNK_SIZE = 200000

const adModeReadWrite = 3
const adTypeBinary = 1
const adTypeText = 2
const adSaveCreateOverWrite = 2

Class FreeASPUpload
  Public UploadedFiles
  Public FormElements

  Private VarArrayBinRequest
  Private StreamRequest
  Private uploadedYet
  Private internalChunkSize

  Private Sub Class_Initialize()
    Set UploadedFiles = Server.CreateObject("Scripting.Dictionary")
    Set FormElements = Server.CreateObject("Scripting.Dictionary")
    Set StreamRequest = Server.CreateObject("ADODB.Stream")
    StreamRequest.Type = adTypeText
    StreamRequest.Open
    uploadedYet = false
    internalChunkSize = DEFAULT_ASP_CHUNK_SIZE
  End Sub
 
  Private Sub Class_Terminate()
    If IsObject(UploadedFiles) Then
      UploadedFiles.RemoveAll()
      Set UploadedFiles = Nothing
    End If
    If IsObject(FormElements) Then
      FormElements.RemoveAll()
      Set FormElements = Nothing
    End If
    StreamRequest.Close
    Set StreamRequest = Nothing
  End Sub

  Public Property Get Form(sIndex)
    Form = ""
    If FormElements.Exists(LCase(sIndex)) Then Form = FormElements.Item(LCase(sIndex))
  End Property

  Public Property Get Files()
    Files = UploadedFiles.Items
  End Property
 
Public Property Get Exists(sIndex)
Exists = false
If FormElements.Exists(LCase(sIndex)) Then Exists = true
End Property

Public Property Get FileExists(sIndex)
FileExists = false
if UploadedFiles.Exists(LCase(sIndex)) then FileExists = true
End Property

Public Property Get chunkSize()
    chunkSize = internalChunkSize
  End Property

  Public Property Let chunkSize(sz)
    internalChunkSize = sz
  End Property

  'Calls Upload to extract the data from the binary request and then saves the uploaded files
  Public Sub Save(path)
    Dim streamFile, fileItem, filePath

    if Right(path, 1) <> "\" then path = path & "\"

    if not uploadedYet then Upload

    For Each fileItem In UploadedFiles.Items
      filePath = path & fileItem.FileName
      Set streamFile = Server.CreateObject("ADODB.Stream")
      streamFile.Type = adTypeBinary
      streamFile.Open
      StreamRequest.Position=fileItem.Start
      StreamRequest.CopyTo streamFile, fileItem.Length
      streamFile.SaveToFile filePath, adSaveCreateOverWrite
      streamFile.close
      Set streamFile = Nothing
      fileItem.Path = filePath
     Next
  End Sub
 
  public sub SaveOne(path, num, byref outFileName, byref outLocalFileName)
    Dim streamFile, fileItems, fileItem, fs

set fs = Server.CreateObject("Scripting.FileSystemObject")
    if Right(path, 1) <> "\" then path = path & "\"

    if not uploadedYet then Upload
    if UploadedFiles.Count > 0 then
      fileItems = UploadedFiles.Items
      set fileItem = fileItems(num)
   
      outFileName = fileItem.FileName
      outLocalFileName = GetFileName(path, outFileName)
   
      Set streamFile = Server.CreateObject("ADODB.Stream")
      streamFile.Type = adTypeBinary
      streamFile.Open
      StreamRequest.Position = fileItem.Start
      StreamRequest.CopyTo streamFile, fileItem.Length
      streamFile.SaveToFile path & outLocalFileName, adSaveCreateOverWrite
      streamFile.close
      Set streamFile = Nothing
      fileItem.Path = path & filename
    end if
  end sub

  Public Function SaveBinRequest(path) ' For debugging purposes
    StreamRequest.SaveToFile path & "\debugStream.bin", 2
  End Function

  Public Sub DumpData() 'only works if files are plain text
    Dim i, aKeys, f
    response.write "Form Items:<br>"
    aKeys = FormElements.Keys
    For i = 0 To FormElements.Count -1 ' Iterate the array
      response.write aKeys(i) & " = " & FormElements.Item(aKeys(i)) & "<BR>"
    Next
    response.write "Uploaded Files:<br>"
    For Each f In UploadedFiles.Items
      response.write "Name: " & f.FileName & "<br>"
      response.write "Type: " & f.ContentType & "<br>"
      response.write "Start: " & f.Start & "<br>"
      response.write "Size: " & f.Length & "<br>"
     Next
  End Sub

  Public Sub Upload()
    Dim nCurPos, nDataBoundPos, nLastSepPos
    Dim nPosFile, nPosBound
    Dim sFieldName, osPathSep, auxStr
    Dim readBytes, readLoop, tmpBinRequest
   
    'RFC1867 Tokens
    Dim vDataSep
    Dim tNewLine, tDoubleQuotes, tTerm, tFilename, tName, tContentDisp, tContentType
    tNewLine = String2Byte(Chr(13))
    tDoubleQuotes = String2Byte(Chr(34))
    tTerm = String2Byte("--")
    tFilename = String2Byte("filename=""")
    tName = String2Byte("name=""")
    tContentDisp = String2Byte("Content-Disposition")
    tContentType = String2Byte("Content-Type:")

    uploadedYet = true

    on error resume next
      ' Copy binary request to a byte array, on which functions like InstrB and others can be used to search for separation tokens
      readBytes = internalChunkSize
      VarArrayBinRequest = Request.BinaryRead(readBytes)
      VarArrayBinRequest = midb(VarArrayBinRequest, 1, lenb(VarArrayBinRequest))
      Do Until readBytes < 1
        tmpBinRequest = Request.BinaryRead(readBytes)
        if readBytes > 0 then
          VarArrayBinRequest = VarArrayBinRequest & midb(tmpBinRequest, 1, lenb(tmpBinRequest))
        end if
      Loop
      StreamRequest.WriteText(VarArrayBinRequest)
      StreamRequest.Flush()
      if Err.Number <> 0 then
        response.write "<br><br><B>System reported this error:</B><p>"
        response.write Err.Description & "<p>"
        response.write "The most likely cause for this error is the incorrect setup of AspMaxRequestEntityAllowed in IIS MetaBase. Please see instructions in the <A HREF='http://www.freeaspupload.net/freeaspupload/requirements.asp'>requirements page of freeaspupload.net</A>.<p>"
        Exit Sub
      end if
    on error goto 0 'reset error handling

    nCurPos = FindToken(tNewLine,1) 'Note: nCurPos is 1-based (and so is InstrB, MidB, etc)

    If nCurPos <= 1 Then Exit Sub
    
    'vDataSep is a separator like -----------------------------21763138716045
    vDataSep = MidB(VarArrayBinRequest, 1, nCurPos-1)

    'Start of current separator
    nDataBoundPos = 1

    'Beginning of last line
    nLastSepPos = FindToken(vDataSep & tTerm, 1)

    Do Until nDataBoundPos = nLastSepPos
     
      nCurPos = SkipToken(tContentDisp, nDataBoundPos)
      nCurPos = SkipToken(tName, nCurPos)
      sFieldName = ExtractField(tDoubleQuotes, nCurPos)

      nPosFile = FindToken(tFilename, nCurPos)
      nPosBound = FindToken(vDataSep, nCurPos)
     
      If nPosFile <> 0 And nPosFile < nPosBound Then
        Dim oUploadFile
        Set oUploadFile = New UploadedFile
       
        nCurPos = SkipToken(tFilename, nCurPos)
        auxStr = ExtractField(tDoubleQuotes, nCurPos)
' We are interested only in the name of the file, not the whole path
' Path separator is \ in windows, / in UNIX
' While IE seems to put the whole pathname in the stream, Mozilla seem to
' only put the actual file name, so UNIX paths may be rare. But not impossible.
osPathSep = "\"
if InStr(auxStr, osPathSep) = 0 then osPathSep = "/"
        oUploadFile.FileName = Right(auxStr, Len(auxStr)-InStrRev(auxStr, osPathSep))

        if (Len(oUploadFile.FileName) > 0) then 'File field not left empty
          nCurPos = SkipToken(tContentType, nCurPos)
         
auxStr = ExtractField(tNewLine, nCurPos)
' NN on UNIX puts things like this in the stream:
' ?? python py type=?? python application/x-python
          oUploadFile.ContentType = Right(auxStr, Len(auxStr)-InStrRev(auxStr, " "))
          nCurPos = FindToken(tNewLine, nCurPos) + 4 'skip empty line
         
          oUploadFile.Start = nCurPos+1
          oUploadFile.Length = FindToken(vDataSep, nCurPos) - 2 - nCurPos
         
          If oUploadFile.Length > 0 Then UploadedFiles.Add LCase(sFieldName), oUploadFile
        End If
      Else
        Dim nEndOfData, fieldValueUniStr
        nCurPos = FindToken(tNewLine, nCurPos) + 4 'skip empty line
        nEndOfData = FindToken(vDataSep, nCurPos) - 2
        fieldValueuniStr = ConvertUtf8BytesToString(nCurPos, nEndOfData-nCurPos)
        If Not FormElements.Exists(LCase(sFieldName)) Then
          FormElements.Add LCase(sFieldName), fieldValueuniStr
        else
FormElements.Item(LCase(sFieldName))= FormElements.Item(LCase(sFieldName)) & ", " & fieldValueuniStr
end if

      End If

      'Advance to next separator
      nDataBoundPos = FindToken(vDataSep, nCurPos)
    Loop
  End Sub

  Private Function SkipToken(sToken, nStart)
    SkipToken = InstrB(nStart, VarArrayBinRequest, sToken)
    If SkipToken = 0 then
      Response.write "Error in parsing uploaded binary request. The most likely cause for this error is the incorrect setup of AspMaxRequestEntityAllowed in IIS MetaBase. Please see instructions in the <A HREF='http://www.freeaspupload.net/freeaspupload/requirements.asp'>requirements page of freeaspupload.net</A>.<p>"
      Response.End
    end if
    SkipToken = SkipToken + LenB(sToken)
  End Function

  Private Function FindToken(sToken, nStart)
    FindToken = InstrB(nStart, VarArrayBinRequest, sToken)
  End Function

  Private Function ExtractField(sToken, nStart)
    Dim nEnd
    nEnd = InstrB(nStart, VarArrayBinRequest, sToken)
    If nEnd = 0 then
      Response.write "Error in parsing uploaded binary request."
      Response.End
    end if
    ExtractField = ConvertUtf8BytesToString(nStart, nEnd-nStart)
  End Function

  'String to byte string conversion
  Private Function String2Byte(sString)
    Dim i
    For i = 1 to Len(sString)
     String2Byte = String2Byte & ChrB(AscB(Mid(sString,i,1)))
    Next
  End Function

  Private Function ConvertUtf8BytesToString(start, length)  
    StreamRequest.Position = 0
 
   Dim objStream
   Dim strTmp
  
   ' init stream
   Set objStream = Server.CreateObject("ADODB.Stream")
   objStream.Charset = "utf-8"
   objStream.Mode = adModeReadWrite
   objStream.Type = adTypeBinary
   objStream.Open
  
   ' write bytes into stream
   StreamRequest.Position = start+1
   StreamRequest.CopyTo objStream, length
   objStream.Flush
  
   ' rewind stream and read text
   objStream.Position = 0
   objStream.Type = adTypeText
   strTmp = objStream.ReadText
  
   ' close up and return
   objStream.Close
   Set objStream = Nothing
   ConvertUtf8BytesToString = strTmp  
  End Function
End Class

Class UploadedFile
  Public ContentType
  Public Start
  Public Length
  Public Path
  Private nameOfFile

' Need to remove characters that are valid in UNIX, but not in Windows
Public Property Let FileName(fN)
nameOfFile = fN
nameOfFile = SubstNoReg(nameOfFile, "\", "_")
nameOfFile = SubstNoReg(nameOfFile, "/", "_")
nameOfFile = SubstNoReg(nameOfFile, ":", "_")
nameOfFile = SubstNoReg(nameOfFile, "*", "_")
nameOfFile = SubstNoReg(nameOfFile, "?", "_")
nameOfFile = SubstNoReg(nameOfFile, """", "_")
nameOfFile = SubstNoReg(nameOfFile, "<", "_")
nameOfFile = SubstNoReg(nameOfFile, ">", "_")
nameOfFile = SubstNoReg(nameOfFile, "|", "_")
End Property

Public Property Get FileName()
FileName = nameOfFile
End Property

'Public Property Get FileN()ame
End Class


' Does not depend on RegEx, which is not available on older VBScript
' Is not recursive, which means it will not run out of stack space
Function SubstNoReg(initialStr, oldStr, newStr)
Dim currentPos, oldStrPos, skip
If IsNull(initialStr) Or Len(initialStr) = 0 Then
SubstNoReg = ""
ElseIf IsNull(oldStr) Or Len(oldStr) = 0 Then
SubstNoReg = initialStr
Else
If IsNull(newStr) Then newStr = ""
currentPos = 1
oldStrPos = 0
SubstNoReg = ""
skip = Len(oldStr)
Do While currentPos <= Len(initialStr)
oldStrPos = InStr(currentPos, initialStr, oldStr)
If oldStrPos = 0 Then
SubstNoReg = SubstNoReg & Mid(initialStr, currentPos, Len(initialStr) - currentPos + 1)
currentPos = Len(initialStr) + 1
Else
SubstNoReg = SubstNoReg & Mid(initialStr, currentPos, oldStrPos - currentPos) & newStr
currentPos = oldStrPos + skip
End If
Loop
End If
End Function

Function GetFileName(strSaveToPath, FileName)
'This function is used when saving a file to check there is not already a file with the same name so that you don't overwrite it.
'It adds numbers to the filename e.g. file.gif becomes file1.gif becomes file2.gif and so on.
'It keeps going until it returns a filename that does not exist.
'You could just create a filename from the ID field but that means writing the record - and it still might exist!
'N.B. Requires strSaveToPath variable to be available - and containing the path to save to
Dim Counter
Dim Flag
Dim strTempFileName
Dim FileExt
Dim NewFullPath
dim objFSO, p
Set objFSO = CreateObject("Scripting.FileSystemObject")
Counter = 0
p = instrrev(FileName, ".")
FileExt = mid(FileName, p+1)
strTempFileName = left(FileName, p-1)
NewFullPath = strSaveToPath & "\" & FileName
Flag = False

Do Until Flag = True
If objFSO.FileExists(NewFullPath) = False Then
Flag = True
GetFileName = Mid(NewFullPath, InstrRev(NewFullPath, "\") + 1)
Else
Counter = Counter + 1
NewFullPath = strSaveToPath & "\" & strTempFileName & Counter & "." & FileExt
End If
Loop
End Function

%>

2010/10/19 17:21 2010/10/19 17:21
Posted
Filed under asp,asp.net
Function UploadClearVar(sVar)
  Dim str
  str = Trim(Upload(sVar))
 
  If str <> "" Then
   str = Replace(str,"'","''")
   str = Replace(str,";","")
   'str = Replace(str, "(", "&#40;")
      'str = Replace(str, ")", "&#41;")
      'str = Replace(str, "#", "&#35;")
      str = Replace(str, "&", "&#38;")
   str = Replace(str,">","&gt;")
   str = Replace(str,"<","&lt;")
   str = Replace(str, "%", "")
   str = Replace(str, "--", "")
   str = Replace(str, "/*", "")
   str = Replace(str, "*/", "")  
   str = Replace(LCase(str), "cookie", "cook1e")
   str = Replace(LCase(str), "document", "d0cument")
   str = Replace(LCase(str), "script", "scr1pt")
   str = replace(LCase(str), "iframe", "ifr@me")
   str = Replace(LCase(str), "@variable", "")
      str = Replace(LCase(str), "@@variable", "")
      str = Replace(LCase(str), "print", "")
      str = Replace(LCase(str), "set", "")       
      str = Replace(LCase(str), "or", "")
      str = Replace(LCase(str), "union", "")
      str = Replace(LCase(str), "and", "")
   str = Replace(LCase(str), "select", "")
      str = Replace(LCase(str), "insert", "")
   str = Replace(LCase(str), "update", "")
   str = Replace(LCase(str), "delete", "")
      str = Replace(LCase(str), "openrowset", "")
   str = Replace(LCase(str), "declare", "")
   str = Replace(LCase(str), "shutdown", "")
      str = Replace(LCase(str), "drop", "")
   str = Replace(LCase(str), "xp_", "")
  End IF
 
  UploadClearVar = str
 End Function

Function UploadClearVar(sVar)
  Dim str
  str = Trim(Upload(sVar))
 
  If str <> "" Then
   str = Replace(str,"'","''")
   str = Replace(str,";","")
   'str = Replace(str, "(", "&#40;")
      'str = Replace(str, ")", "&#41;")
      'str = Replace(str, "#", "&#35;")
      str = Replace(str, "&", "&#38;")
   str = Replace(str,">","&gt;")
   str = Replace(str,"<","&lt;")
   str = Replace(str, "%", "")
   str = Replace(str, "--", "")
   str = Replace(str, "/*", "")
   str = Replace(str, "*/", "")  
   str = Replace(LCase(str), "cookie", "cook1e")
   str = Replace(LCase(str), "document", "d0cument")
   str = Replace(LCase(str), "script", "scr1pt")
   str = replace(LCase(str), "iframe", "ifr@me")
   str = Replace(LCase(str), "@variable", "")
      str = Replace(LCase(str), "@@variable", "")
      str = Replace(LCase(str), "print", "")
      str = Replace(LCase(str), "set", "")       
      str = Replace(LCase(str), "or", "")
      str = Replace(LCase(str), "union", "")
      str = Replace(LCase(str), "and", "")
   str = Replace(LCase(str), "select", "")
      str = Replace(LCase(str), "insert", "")
   str = Replace(LCase(str), "update", "")
   str = Replace(LCase(str), "delete", "")
      str = Replace(LCase(str), "openrowset", "")
   str = Replace(LCase(str), "declare", "")
   str = Replace(LCase(str), "shutdown", "")
      str = Replace(LCase(str), "drop", "")
   str = Replace(LCase(str), "xp_", "")
  End IF
 
  UploadClearVar = str
 End Function
2010/08/01 16:03 2010/08/01 16:03
Posted
Filed under asp,asp.net

[원문] : http://wiz.pe.kr/80

책을 보면서 ASP.NET page의 이벤트 순서를 간단하게 정리를 해봤습니다.
이벤트의 순서를 알면 ASP.NET을 이용해 개발하는 패턴을 이해 할 수 있습니다.

이벤트의 큰 흐름은 아래와 같이 간단합니다.

가. 요청 페이지의 이전 상태값을 읽는다.
나. 요청 페이지의 변화된 값을 읽는다.
다. 변화된 값에 대한 처리를 한다. (사용자의 구현부분)
라. 변화된 값을 저장 한다.


asp.net page의 이벤트 발생 순서

사용자 삽입 이미지

1. 클라이언트의 페이지 요청
클라이언트는 함은 IE뿐 아니라 모바일 기기와 같이 asp.net페이지에 접근하는 모든 장비를 말합니다.

2. Initialize :  ASP.NET Framework 에서 클라이언트 요청을 처리하기 위해 Init 이벤트를 보내서 OnInit() 메소드를 호출 합니다. 대부분 이 단계에서 객체를 생성합니다.

3. Load View State
: 컨트롤의 Viewstate 값을 읽어들일때 발생합니다. 포스트백 되는 경우 PostBack된 ViewState 값을 읽어드립니다. LoadViewState()를 사용해 사용자 코드를 추가 할 수 있습니다.

4. Process PostBack Data
: System.Web.UI.IPostBackDataHandler 인터페이스를 구현하는 컨트롤에서 PostBack 데이터를 해석할 때 발생하게 됩니다. LoadPostData() 메서드를 통해 오버라이딩을 할 수 있습니다.

5. Load
: 컨트롤 트리에서 컨트롤에 접근 할 수 있는 최초의 이벤트라고 할 수 있습니다. 컨트롤들의 초기화가 이루어진다. 컨트롤에 대한 설정을 여기에서 구현하시면 됩니다.

6. Send PostBack Change Notifications
: 포스트백 된 데이터가 변경되었을 경우 발생하는 이벤트로 System.Web.UI.IPostBackDataHandler 인터페이스에서 상속 받았고, RaisePostDataChangedEvent() 메소드를 이용해 오버라이딩 가능합니다.

7. Handle PostBack Events
: 클라이언트에서 PostBack 이벤트를 발생시킨 컨트롤에 대응하는 메소드 호출 하는 단계 입니다. 각 이벤트에 대한 처리를 구현하면 됩니다.

8. Prerender
: 런더링 하기전에 발생하는 이벤트입니다. 컨트롤에 대한 접근할 수 있는 마지막 단계로 결과를 출력을 하기전에 최종적으로 처리해야 할 내용을 구현하면 됩니다.

9. Save State
: 컨트롤들의 상태와 설정값을 ViewState에 저장 할 때 발생 합니다. SaveViewState() 메서드를 오버라이드해서 사용자의 처리내용을 구현할 수 있습니다.

10. Render
: 클라이언트에 출력할 내용으로 변경 할 때 발생 합니다. 여기에서 만들어진 데이터가 클라이언트로 보내집니다. Render() 메소드를 통해 오버라이딩 할 수 있습니다.

11. Dispose
: 사용했던 모든 리소스를 제거 할때 발생 합니다. Dispose() 메소드를 오버라이딩 해서 추가로 제거 할 리소스를 제거하면 됩니다.


저장한 값과 변경된 값을 비교해 사용자의 액션을 처리 하는 단순한 로직을 반복함으로서 구성이 됩니다.

2010/07/04 02:58 2010/07/04 02:58
Posted
Filed under asp,asp.net
<%
	filename = "화일명"
	response.buffer=true
	response.contenttype="application/vnd.ms-excel" 
	Response.AddHeader "Content-Disposition","attachment;filename=" & filename
%>
2010/06/05 12:57 2010/06/05 12:57
Posted
Filed under asp,asp.net
다운받기]
MySQL Connector/ODBC 3.51
http://dev.mysql.com/downloads/connector/odbc/3.51.html

MySQL Query Browser
http://dev.mysql.com/downloads/gui-tools/5.0.html

[설치]
MySQL과 MyODBC, Query Brower를 설치합니다.

create database memberdb;
use memberdb;
create table memberinfo
(
  contactId int auto_increment not null,
  Name varchar(50),
  phone varchar(20),
  primary key(contactId),
  unique id(contactId)
);

[connect_test.asp]
생성한 DB에 접근할 수 있는지 확인하기 위해 아래와 같이 작성합니다.
<%
  dim adoConn
  set adoConn = Server.CreateObject("ADODB.Connection")
  adoConn.Open "Driver={MySQL ODBC 3.51 driver}; Server=localhost; Database=memberdb; Uid=root;Pwd=1111;"
  if adoConn.errors.count = 0 then
      response.write "Connected Successfully!"
  end if

  adoConn.close
  set adoConn = nothing
%>

인터넷 창에 주소 http://localhost/connect_test.asp 를 넣어 Connected Successfully 라는 글이 나타난다면 ASP+MySQL를 사용할 정상적으로 된것입니다.

[중요]
adoConn.Open "Driver={MySQL ODBC 3.51 driver}; Server=localhost; Database=memberdb; Uid=root;Pwd=1111;"
중요>>> Driver를 MySQL ODBC 3.51 driver로 지정해주었다는 꼭 알아두세요.
2009/07/17 20:41 2009/07/17 20:41
Posted
Filed under asp,asp.net
다운받기]
MySQL Connector/ODBC 3.51
http://dev.mysql.com/downloads/connector/odbc/3.51.html

MySQL Query Browser
http://dev.mysql.com/downloads/gui-tools/5.0.html

[설치]
MySQL과 MyODBC, Query Brower를 설치합니다.

create database memberdb;
use memberdb;
create table memberinfo
(
  contactId int auto_increment not null,
  Name varchar(50),
  phone varchar(20),
  primary key(contactId),
  unique id(contactId)
);

[connect_test.asp]
생성한 DB에 접근할 수 있는지 확인하기 위해 아래와 같이 작성합니다.
<%
  dim adoConn
  set adoConn = Server.CreateObject("ADODB.Connection")
  adoConn.Open "Driver={MySQL ODBC 3.51 driver}; Server=localhost; Database=memberdb; Uid=root;Pwd=1111;"
  if adoConn.errors.count = 0 then
      response.write "Connected Successfully!"
  end if

  adoConn.close
  set adoConn = nothing
%>

인터넷 창에 주소 http://localhost/connect_test.asp 를 넣어 Connected Successfully 라는 글이 나타난다면 ASP+MySQL를 사용할 정상적으로 된것입니다.

[중요]
adoConn.Open "Driver={MySQL ODBC 3.51 driver}; Server=localhost; Database=memberdb; Uid=root;Pwd=1111;"
중요>>> Driver를 MySQL ODBC 3.51 driver로 지정해주었다는 꼭 알아두세요.
2009/07/17 20:41 2009/07/17 20:41