Added the contents of the archive.

Moved the original file to the archive subfolder.
This commit is contained in:
yallie
2017-11-20 16:11:42 +03:00
parent 0289c2fe43
commit 9fa3874800
10809 changed files with 3620963 additions and 0 deletions
+136
View File
@@ -0,0 +1,136 @@
#!/bin/sh
# ==++==
#
#
# Copyright (c) 2002 Microsoft Corporation. All rights reserved.
#
# The use and distribution terms for this software are contained in the file
# named license.txt, which can be found in the root of this distribution.
# By using this software in any fashion, you are agreeing to be bound by the
# terms of this license.
#
# You must not remove this notice, or any other, from this software.
#
#
# ==--==
if test X"${TARGETCOMPLUS}" = "X"
then
echo "ERROR: The TARGETCOMPLUS environment variable isn't set."
echo "Please source the appropriate env.sh or env.csh file."
exit 1
fi
CLEANOPTION=$1
BUILDOPTIONS=$*
if test -r ${ROTOR_DIR}/buildall.out; then rm -f ${ROTOR_DIR}/buildall.out;fi
ReportError()
{
echo \*\*\* Error while building ${BUILDALL_BUILDING}
echo Open ${BUILDALL_ERRORLOG} to see the error log.
if test X"${BUILDITALL}" != "X"
then
echo setenv BUILDALL_BUILDING ${BUILDALL_BUILDING} > ${ROTOR_DIR}/buildall.out
echo setenv BUILDALL_ERRORLOG ${BUILDALL_ERRORLOG} >>${ROTOR_DIR}/buildall.out
echo setenv BUILDALL_WARNINGLOG ${BUILDALL_WARNINGLOG} >>${ROTOR_DIR}/buildall.out
fi
exit 1
}
ReportBuildError()
{
BUILDALL_ERRORLOG=${BUILDALL_BUILDING}/build${BUILD_ALT_DIR}.err
BUILDALL_WARNINGLOG=${BUILDALL_BUILDING}/build${BUILD_ALT_DIR}.wrn
ReportError
}
RunMake()
{
BUILDALL_BUILDING=$1
shift
echo Building $*...
BUILDALL_ERRORLOG=${BUILDALL_BUILDING}/build${BUILD_ALT_DIR}.log
if test -r ${BUILDALL_ERRORLOG}; then rm -f ${BUILDALL_ERRORLOG};fi
cd ${BUILDALL_BUILDING}
if test X"${CLEANOPTION}" = "X-c"
then
echo $MAKE clean:>>${BUILDALL_ERRORLOG}
$MAKE clean >>${BUILDALL_ERRORLOG} 2>&1
if test $? != 0 ; then ReportError; fi
fi
echo $MAKE: >>${BUILDALL_ERRORLOG}
$MAKE >${BUILDALL_ERRORLOG} 2>&1
if test $? != 0 ; then ReportError; fi
return 0
}
RunBuild()
{
BUILDALL_BUILDING=$1
shift
echo Building $*...
cd ${BUILDALL_BUILDING}
build $BUILDOPTIONS
if test $? != 0 ; then ReportBuildError; fi
}
mkdir -p ${TARGETCOMPLUS}
# Run ./configure if this is a clean build or if we don't think
# ./configure has run to completion successfully yet.
if [ X"$1" = "X-c" ] || [ ! -f ${ROTOR_DIR}/pal/unix/obj${BUILD_ALT_DIR}/makefile.common ]
then
echo Running configure...
BUILDALL_BUILDING=${ROTOR_DIR}/configure
BUILDALL_ERRORLOG=${ROTOR_DIR}/build${BUILD_ALT_DIR}.log
if test "$NTDEBUG" = "ntsdnodbg"
then
./configure -disable-debug > ${BUILDALL_ERRORLOG} 2>&1
else
./configure > ${BUILDALL_ERRORLOG} 2>&1
fi
if test $? != 0 ; then ReportError; fi
fi
# Allow custom makes. We can use bsdmake on Mac OS X, for example.
if test X"$MAKE" = "X"
then
MAKE=make
export MAKE
fi
BUILDALL_BUILDING=${ROTOR_DIR}/pal/unix
echo Building the PAL...
BUILDALL_ERRORLOG=${BUILDALL_BUILDING}/build${BUILD_ALT_DIR}.log
if test -r ${BUILDALL_ERRORLOG}; then rm -f ${BUILDALL_ERRORLOG};fi
cd ${BUILDALL_BUILDING}
if test X"${CLEANOPTION}" = "X-c"
then
echo $MAKE clean:>>${BUILDALL_ERRORLOG}
$MAKE clean >>${BUILDALL_ERRORLOG} 2>&1
if test $? != 0 ; then ReportError; fi
echo $MAKE depend: >>${BUILDALL_ERRORLOG}
$MAKE depend >>${BUILDALL_ERRORLOG} 2>&1
if test $? != 0 ; then ReportError; fi
fi
echo $MAKE: >>${BUILDALL_ERRORLOG}
$MAKE >>${BUILDALL_ERRORLOG} 2>&1
if test $? != 0 ; then ReportError; fi
RunMake ${ROTOR_DIR}/tools/nmake nmake tool
RunMake ${ROTOR_DIR}/tools/cppmunge cppmunge tool
RunMake ${ROTOR_DIR}/tools/binplace binplace tool
RunMake ${ROTOR_DIR}/tools/build build tool
RunBuild ${ROTOR_DIR}/tools/resourcecompiler the Resource Compiler
RunBuild ${ROTOR_DIR}/palrt/src the PAL RT
RunBuild ${CORBASE}/src the CLR
RunBuild ${ROTOR_DIR}/fx/src FX
RunBuild ${ROTOR_DIR}/managedlibraries ManagedLibraries
RunBuild ${ROTOR_DIR}/jscript JScript
RunBuild ${ROTOR_DIR}/samples the samples
exit 0
+159
View File
@@ -0,0 +1,159 @@
@if "%_echo%"=="" echo off
REM ==++==
REM
REM
REM Copyright (c) 2002 Microsoft Corporation. All rights reserved.
REM
REM The use and distribution terms for this software are contained in the file
REM named license.txt, which can be found in the root of this distribution.
REM By using this software in any fashion, you are agreeing to be bound by the
REM terms of this license.
REM
REM You must not remove this notice, or any other, from this software.
REM
REM
REM ==--==
if "%TARGETCOMPLUS%" == "" goto TargetComplusNotSet
REM Note:
REM The BUILDALL_BUILDING, BUILDALL_ERRORLOG and BUILDALL_WARNINGLOG variables are
REM used by other scripts to report errors so setlocal/endlocal may not be used.
REM
echo.
echo --- Building the PAL ---
echo.
set BUILDALL_BUILDING=%ROTOR_DIR%\pal\win32
set BUILDALL_ERRORLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.log
pushd %ROTOR_DIR%\pal\win32
call make.cmd %*
popd
if ERRORLEVEL 1 goto DisplayError
echo.
echo --- Building the binplace tool ---
echo.
set BUILDALL_BUILDING=%ROTOR_DIR%\tools\binplace
set BUILDALL_ERRORLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.log
pushd %ROTOR_DIR%\tools\binplace
call make.cmd %*
popd
if ERRORLEVEL 1 goto DisplayError
echo.
echo --- Building the build tool
echo.
set BUILDALL_BUILDING=%ROTOR_DIR%\tools\build
set BUILDALL_ERRORLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.log
pushd %ROTOR_DIR%\tools\build
call make.cmd %*
popd
if ERRORLEVEL 1 goto DisplayError
echo.
echo --- Building the Resource Compiler ---
echo.
set BUILDALL_BUILDING=%ROTOR_DIR%\tools\resourcecompiler
set BUILDALL_ERRORLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.err
set BUILDALL_WARNINGLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.wrn
pushd %ROTOR_DIR%\tools\resourcecompiler
build %*
popd
if ERRORLEVEL 1 goto DisplayError
echo.
echo --- Building the PAL RT ---
echo.
set BUILDALL_BUILDING=%ROTOR_DIR%\palrt\src
set BUILDALL_ERRORLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.err
set BUILDALL_WARNINGLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.wrn
pushd %ROTOR_DIR%\palrt\src
build %*
popd
if ERRORLEVEL 1 goto DisplayError
echo.
echo --- Building the CLR ---
echo.
set BUILDALL_BUILDING=%CORBASE%\src
set BUILDALL_ERRORLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.err
set BUILDALL_WARNINGLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.wrn
pushd %CORBASE%\src
build %*
popd
if ERRORLEVEL 1 goto DisplayError
echo.
echo --- Building FX ---
echo.
set BUILDALL_BUILDING=%ROTOR_DIR%\fx\src
set BUILDALL_ERRORLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.err
set BUILDALL_WARNINGLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.wrn
pushd %ROTOR_DIR%\fx\src
build %*
popd
if ERRORLEVEL 1 goto DisplayError
echo.
echo --- Building ManagedLibraries ---
echo.
set BUILDALL_BUILDING=%ROTOR_DIR%\ManagedLibraries
set BUILDALL_ERRORLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.err
set BUILDALL_WARNINGLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.wrn
pushd %ROTOR_DIR%\ManagedLibraries
build %*
popd
if ERRORLEVEL 1 goto DisplayError
echo.
echo --- Building JScript ---
echo.
set BUILDALL_BUILDING=%ROTOR_DIR%\jscript
set BUILDALL_ERRORLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.err
set BUILDALL_WARNINGLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.wrn
pushd %ROTOR_DIR%\jscript
build %*
popd
if ERRORLEVEL 1 goto DisplayError
echo.
echo --- Building the pdb to ildb Tool ---
echo.
set BUILDALL_BUILDING=%ROTOR_DIR%\tools\ildbconv
set BUILDALL_ERRORLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.err
set BUILDALL_WARNINGLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.wrn
pushd %ROTOR_DIR%\tools\ildbconv
build %*
popd
if ERRORLEVEL 1 goto DisplayError
echo.
echo --- Building the samples ---
echo.
set BUILDALL_BUILDING=%ROTOR_DIR%\samples
set BUILDALL_ERRORLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.err
set BUILDALL_WARNINGLOG=%BUILDALL_BUILDING%\build%BUILD_ALT_DIR%.wrn
pushd %ROTOR_DIR%\samples
build %*
popd
if ERRORLEVEL 1 goto DisplayError
goto Done
:DisplayError
echo *** Error while building %BUILDALL_BUILDING%
echo Open %BUILDALL_ERRORLOG% to see the error log.
echo Open %BUILDALL_WARNINGLOG% to see any warnings.
exit /B 1
:TargetComplusNotSet
echo ERROR: The build environment variable isn't set.
echo Please run env.bat [fastchecked^|free^|checked]
exit /B 1
:Done
set BUILDALL_BUILDING=
set BUILDALL_ERRORLOG=
set BUILDALL_WARNINGLOG=
Binary file not shown.
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
#define PUBLIC_KEY_TOKEN "b03f5f7f11d50a3a"
#define PUBLIC_KEY "002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293"
+125
View File
@@ -0,0 +1,125 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2002 Microsoft Corporation. All rights reserved.
The use and distribution terms for this software are contained in the file
named license.txt, which can be found in the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by the
terms of this license.
You must not remove this notice, or any other, from this software.
-->
<configuration>
<configSections>
<!-- tell .NET Framework to ignore CLR sections -->
<section name="runtime" type="System.Configuration.IgnoreSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowLocation="false"/>
<section name="mscorlib" type="System.Configuration.IgnoreSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowLocation="false"/>
<section name="startup" type="System.Configuration.IgnoreSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowLocation="false"/>
<section name="system.runtime.remoting" type="System.Configuration.IgnoreSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowLocation="false"/>
<section name="system.diagnostics" type="System.Diagnostics.DiagnosticsConfigurationHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<section name="appSettings" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<sectionGroup name="system.net">
<section name="authenticationModules" type="System.Net.Configuration.NetAuthenticationModuleHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<section name="defaultProxy" type="System.Net.Configuration.DefaultProxyHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<section name="connectionManagement" type="System.Net.Configuration.ConnectionManagementHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<section name="webRequestModules" type="System.Net.Configuration.WebRequestModuleHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</sectionGroup>
</configSections>
<!-- use this section to add application specific configuration
example:
<appSettings>
<add key="XML File Name" value="myXmlFileName.xml" />
</appSettings>
-->
<system.diagnostics>
<switches>
<!-- <add name="SwitchName" value="4"/> -->
</switches>
<trace autoflush="false" indentsize="4"/>
<!-- <assert assertuienabled="true" logfilename=".\TraceLog.txt"/> -->
</system.diagnostics>
<system.net>
<defaultProxy>
<!--
The following entry enables reading of the per user (LAN) Internet settings.
Adding additional proxy settings, without first setting to "false",
will individually override. Note that "Automatic configuration" and
"automatic configuration scripts" cannot be read.
<proxy> settings:
usesystemdefault="[true|false]" - Read settings from Internet Options (see above)
proxyaddress="[string]" - A Uri string of the proxy server to use.
bypassonlocal="[true|false]" - Enables bypassing of the proxy for local resources.
-->
<proxy usesystemdefault="true"/>
<!-- use this section to disable proxy use for matching servers
example:
<bypasslist>
<add address="bypassRegexString" />
</bypasslist>
-->
<!-- use this section to override proxy settings with your own IWebProxy implementation
example:
<module
type="System.Net.WebProxy, System.Net, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
/>
-->
</defaultProxy>
<webRequestModules>
<add prefix="http" type="System.Net.HttpRequestCreator"/>
<add prefix="https" type="System.Net.HttpRequestCreator"/>
<add prefix="file" type="System.Net.FileWebRequestCreator"/>
</webRequestModules>
<authenticationModules>
<add type="System.Net.DigestClient"/>
<add type="System.Net.NegotiateClient"/>
<add type="System.Net.KerberosClient"/>
<add type="System.Net.NtlmClient"/>
<add type="System.Net.BasicClient"/>
</authenticationModules>
<connectionManagement>
<add address="*" maxconnection="2"/>
</connectionManagement>
</system.net>
<system.runtime.remoting>
<application>
<channels>
<channel ref="http client" displayName="http client (delay loaded)" delayLoadAsClientChannel="true"/>
<channel ref="tcp client" displayName="tcp client (delay loaded)" delayLoadAsClientChannel="true"/>
</channels>
</application>
<channels>
<channel id="http" type="System.Runtime.Remoting.Channels.Http.HttpChannel, System.Runtime.Remoting, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<channel id="http client" type="System.Runtime.Remoting.Channels.Http.HttpClientChannel, System.Runtime.Remoting, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<channel id="http server" type="System.Runtime.Remoting.Channels.Http.HttpServerChannel, System.Runtime.Remoting, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<channel id="tcp" type="System.Runtime.Remoting.Channels.Tcp.TcpChannel, System.Runtime.Remoting, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<channel id="tcp client" type="System.Runtime.Remoting.Channels.Tcp.TcpClientChannel, System.Runtime.Remoting, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<channel id="tcp server" type="System.Runtime.Remoting.Channels.Tcp.TcpServerChannel, System.Runtime.Remoting, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</channels>
<channelSinkProviders>
<clientProviders>
<formatter id="soap" type="System.Runtime.Remoting.Channels.SoapClientFormatterSinkProvider, System.Runtime.Remoting, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<formatter id="binary" type="System.Runtime.Remoting.Channels.BinaryClientFormatterSinkProvider, System.Runtime.Remoting, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</clientProviders>
<serverProviders>
<formatter id="soap" type="System.Runtime.Remoting.Channels.SoapServerFormatterSinkProvider, System.Runtime.Remoting, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<formatter id="binary" type="System.Runtime.Remoting.Channels.BinaryServerFormatterSinkProvider, System.Runtime.Remoting, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<provider id="wsdl" type="System.Runtime.Remoting.MetadataServices.SdlChannelSinkProvider, System.Runtime.Remoting, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</serverProviders>
</channelSinkProviders>
</system.runtime.remoting>
</configuration>
+46
View File
@@ -0,0 +1,46 @@
; ==++==
;
;
; Copyright (c) 2002 Microsoft Corporation. All rights reserved.
;
; The use and distribution terms for this software are contained in the file
; named license.txt, which can be found in the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by the
; terms of this license.
;
; You must not remove this notice, or any other, from this software.
;
;
; ==--==
; Forced base address for Windows exe's.
usermode 0x00400000 0x00100000 ; generic EXE (default link module name)
; Symbols
ildbsymbols 0x51820000 0x00070000 ; same base as diasymreader
; Profiler
dnprofiler 0x51890000 0x00010000
; CSharp
cscomp 0x53140000 0x0010C000
alink 0x56080000 0x000CB000
;module base length
sos 0x60280000 0x0008B000
;module base length ; headroom left
fusion 0x79030000 0x00086000 ; 0x0004A000
mscordbc 0x79100000 0x0004D000 ; 0x00003000
mscordbi 0x79150000 0x000EC000 ; 0x00004000
sscoree 0x79240000 0x007D0000 ; 0x00010000
mscorejt 0X79A20000 0x0024F000 ; 0X00001000
rotor_pal 0x79C70000 0x00050000 ; 0x00010000
rotor_palrt 0x79CD0000 0x00030000 ; 0x00020000
mscorpe 0x79D20000 0x00061000 ; 0x0000F000
mscorrc 0x79D90000 0x00039000 ; 0x00057000
mscorsn 0x79E20000 0x0004A000 ; 0x00016000
system.runtime.serialization.formatters.soap 0x79E80000 0x00028000 ; 0x000B8000
system.runtime.remoting 0x79F60000 0x0005E000 ; 0x00142000
mscorlib 0x7A100000 0x00212000
;total address space used 0x01312000 (19,996,6720 x 79000000-> 0x7A312000)
@@ -0,0 +1,49 @@
; ==++==
;
;
; Copyright (c) 2002 Microsoft Corporation. All rights reserved.
;
; The use and distribution terms for this software are contained in the file
; named license.txt, which can be found in the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by the
; terms of this license.
;
; You must not remove this notice, or any other, from this software.
;
;
; ==--==
; Forced base address for Windows exe's.
usermode 0x00400000 0x00100000 ; generic EXE (default link module name)
; Symbols
ildbsymbols 0x51820000 0x00070000 ; same base as diasymreader
; Profiler
dnprofiler 0x51890000 0x00010000
; CSharp
cscomp 0x53140000 0x000A0000
ALink 0x56080000 0x00020000
;module base length
sos 0x60270000 0x0004E000
;module base length ; headroom left
fusion 0x79030000 0x0004D000 ; 0x00043000
mscordbc 0x790C0000 0x00036000 ; 0x0000A000
mscordbi 0x79100000 0x0009E000 ; 0x000A2000
sscoree 0x79240000 0x0048F000 ; 0x00041000
mscorejt 0x79710000 0x00064000 ; 0x0000C000
rotor_pal 0x79780000 0x00040000 ; 0x00010000
rotor_palrt 0x797D0000 0x00020000 ; 0x00060000
mscorpe 0x79850000 0x0003E000 ; 0x00002000
mscorrc 0x79890000 0x00035000 ; 0x0003B000
mscorsn 0x79900000 0x00032000 ; 0x0001E000
system.runtime.serialization.formatters.soap 0x79950000 0x00028000 ; 0x000B8000
system.runtime.remoting 0x79A30000 0x0005E000 ; 0x000F2000
mscorlib 0x79B80000 0x001F8000
;total address space used 0x00D78000 (14,123,008.00 Bytes, 0x79000000-> 79D78000)
+50
View File
@@ -0,0 +1,50 @@
; ==++==
;
;
; Copyright (c) 2002 Microsoft Corporation. All rights reserved.
;
; The use and distribution terms for this software are contained in the file
; named license.txt, which can be found in the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by the
; terms of this license.
;
; You must not remove this notice, or any other, from this software.
;
;
; ==--==
; Forced base address for Windows exe's.
usermode 0x00400000 0x00100000 ; generic EXE (default link module name)
; Symbols
ildbsymbols 0x51820000 0x00070000 ; same base as diasymreader
; Profiler
dnprofiler 0x51890000 0x00010000
; CSharp
cscomp 0x53140000 0x000BD000
ALink 0x56080000 0x00020000
;module base length
sos 0x60260000 0x0004B000
;module base length ; headroom left
fusion 0x79030000 0x0003F000 ; 0x00041000
mscordbc 0x790B0000 0x00024000 ; 0x0000C000
mscordbi 0x790E0000 0x00055000 ; 0x0008B000
sscoree 0x791C0000 0x002E8000 ; 0x00038000
mscorejt 0x794E0000 0x0002D000 ; 0x00003000
rotor_pal 0x79510000 0x00030000 ; 0x00010000
rotor_palrt 0x79550000 0x00020000 ; 0x00010000
mscorpe 0x79580000 0x00030000 ; 0x00000000
mscorrc 0x795B0000 0x00035000 ; 0x0003B000
mscorsn 0x79620000 0x00023000 ; 0x0005D000
system.runtime.serialization.formatters.soap 0x79660000 0x00028000 ; 0x000B8000
system.runtime.remoting 0x79740000 0x0004E000 ; 0x000E2000
mscorlib 0x79870000 0x001DA000
;total address space used 0x00A4A000 (10,788,864.00 Bytes, 0x79000000-> 0x79A4A000)
+438
View File
@@ -0,0 +1,438 @@
@if "%_echo%"=="" echo off
REM ==++==
REM
REM
REM Copyright (c) 2002 Microsoft Corporation. All rights reserved.
REM
REM The use and distribution terms for this software are contained in the file
REM named license.txt, which can be found in the root of this distribution.
REM By using this software in any fashion, you are agreeing to be bound by the
REM terms of this license.
REM
REM You must not remove this notice, or any other, from this software.
REM
REM
REM ==--==
echo CLR environment (%~f0)
REM
REM RotorEnv.Cmd
REM
REM Driver to set checked, fastchecked or free CLR build environment
REM for use with the NT build tools.
REM
REM Clear out variables to make sure we don't conflict
set LIB=
set INCLUDE=
set _NTROOT=
set _NTTREE=
set _NTDRIVE=
set DDKBUILDENV=
set BUILD_OPTIONS=
set BUILD_ALT_DIR=
set BUILD_DEFAULT_TARGETS=
set C_DEFINES=
set DEBUGGING_SUPPORTED_BUILD=
set PROFILING_SUPPORTED_BUILD=
REM ------------------------------------------
REM Figure out what the root of the world is.
REM This is computed as the parent of the
REM directory in which we are found.
REM ------------------------------------------
call :ComputeCorBase %~f0
if "%CORBASE%" NEQ "%RESULT%" if "%CORBASE%" NEQ "" echo Changing CORBASE from %CORBASE% to %RESULT%
set CORBASE=%RESULT%
REM ------------------------------------------
REM If the environment isn't somewhere else,
REM ------------------------------------------
if not "%CORENV%" == "" goto CorEnvSet
call :ComputeCorEnv %~f0
set CORENV=%RESULT%
:CorEnvSet
REM --------------------------------------------
REM Allow per machine customization (pre loop)
REM --------------------------------------------
REM ------------------------------------------
REM See what options were specified.
REM ------------------------------------------
set _TGTOS=NT32
set _TGTCPUTYPE=x86
set _TGTCPU=i386
if not defined _ENV set _ENV=ConfigFastChecked
for %%i in (%*) do call :Parse %%i
set COMPlus_BuildFlavor=wks
set SVR_WKS_DIRS=wks
REM ------------------------------------------
REM BUILD.EXE insists on having some particular
REM environment variables pointing to our root
REM ------------------------------------------
Call :DrivePart %CORBASE%
Set _NTDRIVE=%RESULT%
Call :AfterDrivePart %CORBASE%
Set _NTROOT=%RESULT%
echo Building for Operating System - %_TGTOS%
echo Processor Family - %_TGTCPUTYPE%
echo Processor - %_TGTCPU%
echo Build Environment = %CORENV%
goto %_ENV%
REM Any spaces before the ampersand are part of the environment value.
:Parse
if /I "%1" == "free" set _ENV=ConfigFree&goto :EOF
if /I "%1" == "checked" set _ENV=ConfigChecked&goto :EOF
if /I "%1" == "fastchecked" set _ENV=ConfigFastChecked&goto :EOF
if /I "%1" == "nobrowse" (
set BROWSER_INFO=
set NO_BROWSER_INFO=1
set NO_BROWSER_FILE=1
goto :EOF
)
set _ENV=usage
goto :EOF
REM ---------------------
REM Fast Checked Build
REM ---------------------
:ConfigFastChecked
set DUMP_CRT_LEAKS=
set DDKBUILDLIB=checked
set DDKBUILDENV=fastchecked
set URTBUILDENV=fstchk
call :SetDebug %DEBUG_TYPE%
set C_DEFINES=-DNTMAKEENV -D_DEBUG
set NTDBGFILES=
set FPO_OPT=1
set MSC_OPTIMIZATION=/O1
set BUILD_ALT_DIR=df
if "%NO_BROWSER_INFO%" NEQ "1" set BROWSER_INFO=1
set DEBUG_CRTS=1
if "%COLOR_FASTCHECKED%" NEQ "" color %COLOR_FASTCHECKED%
goto ConfigEnd
REM ---------------------
REM Free Build
REM ---------------------
:ConfigFree
set DDKBUILDLIB=free
set DDKBUILDENV=free
set URTBUILDENV=fre
set C_DEFINES=-DNTMAKEENV -DNDEBUG -DPERF_TRACKING
REM These settings give us PDB files in release build
set NTDBGFILES=
set NTDEBUG=ntsdnodbg
set NTDEBUGTYPE=windbg
set MSC_OPTIMIZATION=/O1
set BUILD_ALT_DIR=
set BROWSER_INFO=
set DEBUG_CRTS=
if "%COLOR_FREE%" NEQ "" color %COLOR_FREE%
goto ConfigEnd
REM ---------------------
REM Checked Build
REM ---------------------
:ConfigChecked
set DUMP_CRT_LEAKS=
set DDKBUILDLIB=checked
set DDKBUILDENV=checked
set URTBUILDENV=chk
set C_DEFINES=-DNTMAKEENV -D_DEBUG
call :SetDebug %DEBUG_TYPE%
set FPO_OPT=
set NTDBGFILES=
set MSC_OPTIMIZATION=/Od /Oi /GZ
set BUILD_ALT_DIR=d
if "%NO_BROWSER_INFO%" NEQ "1" set BROWSER_INFO=1
set DEBUG_CRTS=1
if "%COLOR_CHECKED%" NEQ "" color %COLOR_CHECKED%
goto ConfigEnd
:ConfigEnd
REM ------------------------------------------
REM Set Common Build & Environment options
REM ------------------------------------------
set BUILD_DEFAULT=-mwe -nmake -i -a
call :ComputeNtMakeEnv %~f0
set NTMAKEENV=%RESULT%
if "%tmp%" EQU "" set tmp=\
set COPYCMD=/Y
call :SetTitle %CORBASE%
set MSC_OPTIMIZATION=%MSC_OPTIMIZATION% /G6
REM --------------------------------------------
REM Set values of URTTARGET variables.
REM --------------------------------------------
if not "%URTTARGET%" == "" goto URTTargetSet
if not "%_URTTARGET%" == "" goto URTTargetSet
set _URTTARGET=%windir%\complus
:URTTargetSet
REM Set derived URT variables.
if not "%_URTTARGET%" == "" set URTTARGET=%_URTTARGET%\v1.%_TGTCPUTYPE%%URTBUILDENV%
REM ------------------------------------------
REM Set up our include paths. These environment variables are the four that are specially
REM understood by BUILD.EXE.
REM
REM Set up the lib paths too.
REM
REM Finally, set the version file and the file used for specifying the base address
REM of each of our various DLLs.
REM ------------------------------------------
set NTDEBUGTYPE=vc6
set FUSION_LIB_PATH=%CORBASE%\bin\*\%DDKBUILDENV%
set COFFBASE_TXT_FILE=%CORBASE%\bin\*\%DDKBUILDENV%\coffbase.txt
REM ------------------------------------------
:SetEnvI386
REM ------------------------------------------
set TARGETCOMPLUS=%URTTARGET%.rotor
set TARGETCOMPLUSSDK=%TARGETCOMPLUS%\sdk
if not exist %TARGETCOMPLUS% mkdir %TARGETCOMPLUS%
if not exist %TARGETCOMPLUSSDK% mkdir %TARGETCOMPLUSSDK%
REM ----> turn on debugging support
set DEBUGGING_SUPPORTED_BUILD=1
set C_DEFINES=%C_DEFINES% -DDEBUGGING_SUPPORTED
REM <----
REM ----> turn on profiling support
set PROFILING_SUPPORTED_BUILD=1
set C_DEFINES=%C_DEFINES% -DPROFILING_SUPPORTED
REM <----
REM ----> general I386 variables. These MUST be set after the above variables
REM set BATCH_NMAKE=1
set C_DEFINES=%C_DEFINES% -DFUSION_SUPPORTED -DPLATFORM_WIN32
REM <----
if "%PREVIOUSPATHSET%" NEQ "" goto SetEnvI386PreviousDone
set PREVIOUSCORPATH=%PATH%
set PREVIOUSPATHSET=1
:SetEnvI386PreviousDone
rem ... ;%CORBASE%\bin\i386\cor ... omitted
set PATH=%CORBASE%\bin;%CORENV%\bin;%PREVIOUSCORPATH%
set FEATURE_PAL=1
set C_DEFINES=%C_DEFINES% -DFEATURE_PAL -DUSE_CDECL_HELPERS -DPAL_PORTABLE_SEH
set CSC_COMPILE_FLAGS=%CSC_COMPILE_FLAGS% /d:FEATURE_PAL
set SDK_INC_PATH=%ROTOR_DIR%\pal
set CRT_INC_PATH=%ROTOR_DIR%\palrt\inc
set BUILD_DEFAULT_TARGETS=%BUILD_DEFAULT_TARGETS% -dynamic rotor_x86
set BUILD_DEFAULT=%BUILD_DEFAULT:-m=-i%
set URTSDKTARGET=%TARGETCOMPLUS%\sdk
set INTTOOLSTARGET=%TARGETCOMPLUS%\int_tools
REM Make sure MSVCDIR is using the short names
Call :ShortName "%MSVCDIR%"
set MSVCDIR=%RESULT%
if "%MSVCDIR%"=="" goto MSVCDirNotSet
set SDK_LIB_PATH=%MSVCDIR%\PlatformSDK\lib
set CRT_LIB_PATH=%MSVCDIR%\lib
set SDK_INC_PATH=%SDK_INC_PATH%;
rem Make sure the PAL and PALRT are on the path
set PATH=%TARGETCOMPLUS%;%TARGETCOMPLUS%\sdk\bin;%TARGETCOMPLUS%\int_tools;%PATH%
REM --------------------------------------------
REM Allow perl scripts to be run as commands (for vssGet vssCheckOut ...)
REM --------------------------------------------
(ASSOC .PL=Perl.Script) > NUL:
(FTYPE Perl.Script=perl.exe "%%1" %%*) > NUL:
REM --------------------------------------------
REM add TARGETCOMPLUS to _NT_SYMBOL_PATH so that NTSD works
if "%PREVIOUS_NT_SYMBOL_PATH_SET%" NEQ "" goto _NT_SYMBOL_PATH_SET
set PREVIOUS_NT_SYMBOL_PATH_SET=1
set PREVIOUS_NT_SYMBOL_PATH=%_NT_SYMBOL_PATH%
:_NT_SYMBOL_PATH_SET
set _NT_SYMBOL_PATH=%TARGETCOMPLUS%\Symbols;%TARGETCOMPLUS%;%PREVIOUS_NT_SYMBOL_PATH%
REM --------------------------------------------
REM add TARGETCOMPLUS to _NT_DEBUGGER_EXTENSION_PATH so that NTSD works
if "%PREVIOUS_NT_DEBUGGER_EXTENSION_PATH_SET%" NEQ "" goto _NT_DEBUGGER_EXTENSION_PATH_SET
set PREVIOUS_NT_DEBUGGER_EXTENSION_PATH_SET=1
set PREVIOUS_NT_DEBUGGER_EXTENSION_PATH=%_NT_DEBUGGER_EXTENSION_PATH%
:_NT_DEBUGGER_EXTENSION_PATH_SET
set _NT_DEBUGGER_EXTENSION_PATH=%TARGETCOMPLUS%\int_tools;%PREVIOUS_NT_DEBUGGER_EXTENSION_PATH%
REM ------------------------------------------
REM All done
REM ------------------------------------------
set RESULT=
goto Done
REM ============================================================================
REM Subroutines
REM
REM ------------------------------------------
REM Extract the drive letter from a path
REM ------------------------------------------
:DrivePart
set RESULT=%~d1
goto :EOF
REM ------------------------------------------
REM Extract everything after the driver letter
REM from a path
REM ------------------------------------------
:AfterDrivePart
set RESULT=%~pnx1
goto :EOF
REM ------------------------------------------
REM Expand a string to a full path
REM ------------------------------------------
:FullPath
set RESULT=%~f1
goto :EOF
REM ------------------------------------------
REM Expand a string to a full path using a Short Name
REM ------------------------------------------
:ShortName
set RESULT=%~sf1
goto :EOF
REM ------------------------------------------
REM Compute the CORBASE environment variable
REM given a path to this batch script.
REM ------------------------------------------
:ComputeCorBase
set RESULT=%~dp1..
Call :FullPath %RESULT%
goto :EOF
REM ------------------------------------------
REM Compute the CORENV environment variable
REM given a path to this batch script.
REM If we're building rotor assume it's ..\..\rotorenv
REM ------------------------------------------
:ComputeCorEnv
if "%ROTOR%"=="1" goto SetRotorCorEnv
set RESULT=%~dp1..
Call :FullPath %RESULT%
goto :EOF
:SetRotorCorEnv
set RESULT=%~dp1..\..\rotorenv
Call :FullPath %RESULT%
goto :EOF
REM ------------------------------------------
REM Compute the NTMAKEENV environment variable
REM given a path to this batch script.
REM ------------------------------------------
:ComputeNTMakeEnv
if defined FEATURE_PAL_VC7 (
set RESULT=%CORBASE%\..\rotorenv\bin
) else (
set RESULT=%CORENV%\bin
)
Call :FullPath %RESULT%
goto :EOF
REM ------------------------------------------
REM Configure the debug file type output.
REM ------------------------------------------
:SetDebug
if "%1" == "PDB_ONLY" goto PdbOnly
set NTDEBUG=ntsd
set NTDEBUGTYPE=both
set USE_PDB=1
goto DebugExitTag
:PdbOnly
set NTDEBUG=ntsd
set NTDEBUGTYPE=windbg
:DebugExitTag
goto :EOF
REM ============================================================================
REM Error handling routines
REM
:SetTitle
setlocal
set _Execute=%COMPlus_BuildFlavor%
title CLR %t% %DDKBUILDENV% - Build - %ROTOR_DIR%
echo Build Type - %DDKBUILDENV%
endlocal
goto :EOF
:MSVCDirNotSet
echo.
echo *** Error ***
echo MSVCDIR not set, make sure 8.3 support is enabled and VC is installed correctly
echo
exit /B 1
:usage
echo.
echo usage: CorEnv [free^|^checked^|^fastchecked^]
echo [nobrowse]
echo.
echo If there is an environment variable named "COLOR_FREE", "CorEnv free"
echo will run "color %%COLOR_FREE%%" to set screen colors.
echo Likewise, "COLOR_CHECKED"
echo correspond to the other build environments.
echo.
echo Example: CorEnv free set free environment and build for NT32,x86,i386
echo Example: set COLOR_CHECKED=70 use black on gray for checked env.
echo CorEnv defaults to fastchecked environment
echo.
echo "color -?" for usage and color codes.
echo.
REM ============================================================================
:Done
exit /B 0
+24
View File
@@ -0,0 +1,24 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
#ifdef _DEBUG
#define VER_FILEFLAGS VS_FF_DEBUG
#else
#define VER_FILEFLAGS VS_FF_SPECIALBUILD
#endif
#define VER_FILETYPE VFT_DLL
#define VER_INTERNALNAME_STR "MSCORLIB.DLL"
#define VER_FILEDESCRIPTION_STR "Microsoft Common Language Runtime Class Library\0"
#define VER_ORIGFILENAME_STR "mscorlib.dll\0"
+122
View File
@@ -0,0 +1,122 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/**
* Version strings for BCL
*
*/
//
// Insert just the #defines in winver.h, so that the
// C# compiler can include this file after macro preprocessing.
//
#ifdef __cplusplus
#pragma once
#else
#define RC_INVOKED 1
#endif
#include <winver.h>
//
// Include the definitions for rmj, rmm, rup, rpt
//
#include <product_version.h>
/*
* Product version and name.
*/
#define VER_PRODUCTNAME_STR "Microsoft (R) .NET Comment Language Runtime Library"
/*
* File version, names, description.
*/
// COMPONENT_VER_INTERNALNAME_STR is passed in by the build environment.
#ifndef COMPONENT_VER_INTERNALNAME_STR
#define COMPONENT_VER_INTERNALNAME_STR UNKNOWN_FILE
#endif
#define VER_INTERNALNAME_STR QUOTE_MACRO(COMPONENT_VER_INTERNALNAME_STR)
#define VER_ORIGINALFILENAME_STR QUOTE_MACRO(COMPONENT_VER_INTERNALNAME_STR)
#define VER_FILEDESCRIPTION_STR "Common Language Runtime Library"
//URTVFT passed in by the build environment.
#ifndef URTVFT
#define URTVFT VFT_UNKNOWN
#endif
#define VER_FILETYPE URTVFT
#define VER_FILESUBTYPE VFT2_UNKNOWN
/* default is nodebug */
#if DBG
#define VER_DEBUG VS_FF_DEBUG
#else
#define VER_DEBUG 0
#endif
#define VER_PRERELEASE 0
#define VER_PRIVATE VS_FF_PRIVATEBUILD
#define VER_FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
#define VER_FILEFLAGS (VER_PRERELEASE|VER_DEBUG|VER_PRIVATE)
#define VER_FILEOS VOS__WINDOWS32
#define VER_COMPANYNAME_STR "Microsoft Corporation"
#ifndef VER_LEGALCOPYRIGHT_YEARS
#define VER_LEGALCOPYRIGHT_YEARS "1998-2002"
#endif
#ifndef VER_LEGALCOPYRIGHT_STR
#if CSC_INVOKED
#define VER_LEGALCOPYRIGHT_STR "Copyright (C) Microsoft Corporation " + VER_LEGALCOPYRIGHT_YEARS + ". All rights reserved."
#else
#define VER_LEGALCOPYRIGHT_STR "Copyright (C) Microsoft Corporation " VER_LEGALCOPYRIGHT_YEARS ". All rights reserved."
#endif
#endif
#ifndef VER_LEGALTRADEMARKS_STR
#define VER_LEGALTRADEMARKS_STR "Microsoft and Windows are either registered trademarks or trademarks of Microsoft Corporation in the U.S. and/or other countries."
#endif
#define EXPORT_TAG
#ifdef VER_LANGNEUTRAL
#define VER_VERSION_UNICODE_LANG "000004B0" /* LANG_NEUTRAL/SUBLANG_NEUTRAL, Unicode CP */
#define VER_VERSION_ANSI_LANG "000004E4" /* LANG_NEUTRAL/SUBLANG_NEUTRAL, Ansi CP */
#define VER_VERSION_TRANSLATION 0x0000, 0x04B0
#else
#define VER_VERSION_UNICODE_LANG "040904B0" /* LANG_ENGLISH/SUBLANG_ENGLISH_US, Unicode CP */
#define VER_VERSION_ANSI_LANG "040904E4" /* LANG_ENGLISH/SUBLANG_ENGLISH_US, Ansi CP */
#define VER_VERSION_TRANSLATION 0x0409, 0x04B0
#endif
#if CSC_INVOKED
#define VER_COMMENTS_STR "Build environement is " + QUOTE_MACRO(URTBLDENV_FRIENDLY)
#else
#define VER_COMMENTS_STR "Build environement is " QUOTE_MACRO(URTBLDENV_FRIENDLY) VALUE)
#endif
+38
View File
@@ -0,0 +1,38 @@
#!/bin/sh
# ==++==
#
#
# Copyright (c) 2002 Microsoft Corporation. All rights reserved.
#
# The use and distribution terms for this software are contained in the file
# named license.txt, which can be found in the root of this distribution.
# By using this software in any fashion, you are agreeing to be bound by the
# terms of this license.
#
# You must not remove this notice, or any other, from this software.
#
#
# ==--==
# Drives csc while it's building mscorlib. This is needed so
# we can set __SECURITY_BOOTSTRAP_DB for csc's environment.
#
# Parameters should be as follows:
# $1: $(CSC_SOURCE_DIR)
# $2: $(CSC_COMPILER)
# $3: $(DDKBUILDENV)
# $4: $(0)
#
# This script does not do parameter validation. It is only
# called from makefile.inc, so it should never break unless
# the call to csc changes and this script is not updated.
echo __SECURITY_BOOTSTRAP_DB=$1
__SECURITY_BOOTSTRAP_DB=$1
echo export __SECURITY_BOOTSTRAP_DB
export __SECURITY_BOOTSTRAP_DB
echo $2 @BclFiles.$3 /noconfig $4/Version.cs $4/AppDomainSetup.cs
$2 @BclFiles.$3 /noconfig $4/Version.cs $4/AppDomainSetup.cs
# Unlike makefile.inc, we don't need to unset the environment
# variable. It goes away when the shell running this script
# exits, which happens when the script itself exits.
+19
View File
@@ -0,0 +1,19 @@
#
#
# Copyright (c) 2002 Microsoft Corporation. All rights reserved.
#
# The use and distribution terms for this software are contained in the file
# named license.txt, which can be found in the root of this distribution.
# By using this software in any fashion, you are agreeing to be bound by the
# terms of this license.
#
# You must not remove this notice, or any other, from this software.
#
#
#
# DO NOT EDIT THIS FILE!!! Edit .\sources. if you want to add a new source
# file to this component. This file merely indirects to the real make file.
#
!INCLUDE $(NTMAKEENV)\makefile.def
+231
View File
@@ -0,0 +1,231 @@
# ==++==
#
#
# Copyright (c) 2002 Microsoft Corporation. All rights reserved.
#
# The use and distribution terms for this software are contained in the file
# named license.txt, which can be found in the root of this distribution.
# By using this software in any fashion, you are agreeing to be bound by the
# terms of this license.
#
# You must not remove this notice, or any other, from this software.
#
#
# ==--==
!INCLUDE $(NTMAKEENV)\makefile.csc
!if "$(PLATFORM_UNIX)" != "1"
MSCOREE_TARGET=$(TARGETPATH)\sscoree.dll
!else
MSCOREE_TARGET=$(TARGETPATH)\libsscoree.$(DYNLIB_SUFFIX)
!endif
!ifndef _TGTCPUTYPE
_TGTCPUTYPE=$(PROCESSOR_ARCHITECTURE)
!endif
####################################################################################
# Include extra source files specifying the assembly version and strong name as
# custom attributes.
$(O)\Version.cs: version.pp $(CORBASE)\src\inc\version\__file__.ver
perl $(NTMAKEENV)\keylocationex.pl $(ASSEMBLY_KEY_FILE) > $(O)\KeyDefine.h
!if "$(PLATFORM_UNIX)" != "1"
cl /EP /C /FI $(ROTOR_DIR)\palrt\inc\sscli_version.h /FI ..\inc\version\__file__.ver /FI $(O)\KeyDefine.h $(C_DEFINES) /DCSC_INCLUDE Version.pp > $(O)\Version.cs
!else
$(CC_NAME) -x c++ -E -C -P -nostdinc -include $(ROTOR_DIR)/palrt/inc/sscli_version.h -include ../inc/version/__file__.ver -include $(O)\KeyDefine.h $(C_DEFINES) -DCSC_INCLUDE version.pp > $(O)/Version.cs
!endif
$(TARGETCOMPLUS)\config\machine.config: $(CORBASE)\bin\machine.rotor.config
-$(MD) $(TARGETCOMPLUS)\config
$(COPY_NAME) $(CORBASE)\bin\machine.rotor.config $(TARGETCOMPLUS)\config\machine.config
####################################################################################
# Include extra source files specifying the assembly version and strong name as
$(O)\AppDomainSetup.cs: system\appdomainsetup.cs
perl $(NTMAKEENV)\finddefines.pl ..\inc\fusion.h > $(O)\FDefines.h
perl $(NTMAKEENV)\finddefines.pl ..\inc\fusionpriv.h > $(O)\FPrivDefines.h
perl $(NTMAKEENV)\finddefines.pl ..\inc\fusionsetup.h > $(O)\FusionSetup.h
!if "$(PLATFORM_UNIX)" != "1"
cl /EP /C /I. /FI $(O)\FPrivDefines.h /FI $(O)\FDefines.h /FI $(O)\FusionSetup.h $(C_DEFINES) system\AppDomainSetup.cs > $(O)\AppDomainSetup.cs
!else
$(CC_NAME) -x c++ -E -C -P -nostdinc -I. -include $(O)\FPrivDefines.h -include $(O)\FDefines.h -include $(O)\FusionSetup.h $(C_DEFINES) system\appdomainsetup.cs > $(O)\AppDomainSetup.cs
perl -p -i -e "s/^# /#line /;" $(O)/AppDomainSetup.cs
!endif
####################################################################################
#
# Tools Stuff.
#
####################################################################################
RESGEN_PATH = $(CORBASE)\src\tools\internalresgen
RESGEN_SRC = $(RESGEN_PATH)\internalresgen.cpp
!ifdef PLATFORM_UNIX
RESGEN_TARGET = $(TARGETPATH)\internalresgen
!else
RESGEN_TARGET = $(TARGETPATH)\internalresgen.exe
!endif
$(RESGEN_TARGET): $(RESGEN_SRC) $(MSCOREE_TARGET)
-$(DELETER) $(RESGEN_TARGET)
cd $(RESGEN_PATH)
build -c
cd $(CSC_SOURCE_DIR)
SN_PATH = $(CORBASE)\src\tools\strongname
SN_SRC = $(SN_PATH)\main.cpp
!if "$(PLATFORM_UNIX)" != "1"
SN_TARGET = $(TARGETPATH)\sn.exe
!else
SN_TARGET = $(TARGETPATH)\sn
!endif
$(SN_TARGET): $(SN_SRC) $(MSCOREE_TARGET)
-$(DELETER) $(SN_TARGET)
cd $(SN_PATH)
build -c
cd $(CSC_SOURCE_DIR)
####################################################################################
#
# This rule is always run and it is run before $(COMPLUSTARGET):: is run.
#
####################################################################################
SETUP: \
$(RESGEN_TARGET) \
$(O)\AppDomainSetup.cs \
$(O)\Version.cs
-$(DELETER) $(CSC_SECURITY_DB).raw
!if "$(_TGTCPUTYPE)" == "x86"
$(TARGETPATH)\internalresgen $(CSC_SOURCE_DIR)\resources.txt $(TARGETPATH)\mscorlib.resources
!else
$(INTTOOLSTARGET)\internalresgen $(CSC_SOURCE_DIR)\resources.txt $(TARGETPATH)\mscorlib.resources
!endif
####################################################################################
# PHASE 1 pass.
# - Create a C# file containing the version that will be added in during the link
# - Create a C# file containing defines used in the runtime
# - Copy the machine.config file
# - create a config file for the compilers
####################################################################################
prep_target: \
$(TARGETCOMPLUS)\config\machine.config \
####################################################################################
SECDBEDIT=clix $(TARGETCOMPLUS)/dump/secdbedit.exe
!if "$(BIGENDIAN)" == "1"
NLPSUFFIX=be.nlp
!else
NLPSUFFIX=.nlp
!endif
NLPDIR=$(CSC_SOURCE_DIR)\system\globalization\tables
####################################################################################
#
# This rule generates mscorlib.dll. It is important to add the source files that
# make up the dependents such as ResGen and CustomMarshalers so that they can be
# built if their source files change.
#
####################################################################################
!if "$(COMPLUSTARGET)" != ""
$(COMPLUSTARGET): $(CSC_SOURCES) $(CSC_SOURCE_DIR)\resources.txt $(SN_TARGET) $(O)\holder.foo $(O)\$(WIN32_RESOURCE_FILE:.rc=.res)
####################################################################################
# Ensure strong name delay signed assemblies are treated properly.
####################################################################################
sn -Vr *,b03f5f7f11d50a3a
sn -Vr *,b77a5c561934e089
####################################################################################
# Copy all the nlp's to the current path to be able to run csc on them.
####################################################################################
$(COPY_NAME) $(NLPDIR)\ctype$(NLPSUFFIX) $(TARGETPATH)\ctype.nlp
$(COPY_NAME) $(NLPDIR)\l_intl$(NLPSUFFIX) $(TARGETPATH)\l_intl.nlp
$(COPY_NAME) $(NLPDIR)\l_except$(NLPSUFFIX) $(TARGETPATH)\l_except.nlp
$(COPY_NAME) $(NLPDIR)\culture$(NLPSUFFIX) $(TARGETPATH)\culture.nlp
$(COPY_NAME) $(NLPDIR)\region$(NLPSUFFIX) $(TARGETPATH)\region.nlp
$(COPY_NAME) $(NLPDIR)\sortkey$(NLPSUFFIX) $(TARGETPATH)\sortkey.nlp
$(COPY_NAME) $(NLPDIR)\sorttbls$(NLPSUFFIX) $(TARGETPATH)\sorttbls.nlp
$(COPY_NAME) $(NLPDIR)\charinfo$(NLPSUFFIX) $(TARGETPATH)\charinfo.nlp
$(COPY_NAME) $(NLPDIR)\big5$(NLPSUFFIX) $(TARGETPATH)\big5.nlp
$(COPY_NAME) $(NLPDIR)\bopomofo$(NLPSUFFIX) $(TARGETPATH)\bopomofo.nlp
$(COPY_NAME) $(NLPDIR)\ksc$(NLPSUFFIX) $(TARGETPATH)\ksc.nlp
$(COPY_NAME) $(NLPDIR)\prc$(NLPSUFFIX) $(TARGETPATH)\prc.nlp
$(COPY_NAME) $(NLPDIR)\prcp$(NLPSUFFIX) $(TARGETPATH)\prcp.nlp
$(COPY_NAME) $(NLPDIR)\xjis$(NLPSUFFIX) $(TARGETPATH)\xjis.nlp
-$(DELETER) $(TARGETPATH)\$(TARGETNAME).$(TARGETEXT)
-$(DELETER) $(O)\$(TARGETNAME).$(TARGETEXT)
!if "$(TARGETCOMPLUS)" != ""
-$(DELETER) $(TARGETCOMPLUS)\$(TARGETNAME).$(TARGETEXT)
!endif
# Generate a response file for the CSC compiler flags.
echo <<BclFiles.$(DDKBUILDENV)
/out:$@
$(CSC_COMPILE_FLAGS: =
)
$(CSC_RESOURCE_FLAGS)
/nostdlib
$(CSC_SOURCES: =
)
<<keep
!if "$(PLATFORM_UNIX)" != "1"
set __SECURITY_BOOTSTRAP_DB=$(CSC_SOURCE_DIR)
$(CSC_COMPILER) @BclFiles.$(DDKBUILDENV) /noconfig $(O)\Version.cs $(O)\AppDomainSetup.cs
set __SECURITY_BOOTSTRAP_DB=
perl $(NTMAKEENV)\getbaseaddress.pl $(TARGETPATH)\mscorlib.dll $(CSC_BASE)
!else
$(CSC_SOURCE_DIR)/buildmscorlib $(CSC_SOURCE_DIR) $(CSC_COMPILER) $(DDKBUILDENV) $(O)
!endif
!if "$(DELAY_SIGN)" != "1"
sn -R $@ $(MICROSOFT_KEY_FILE)
!endif
####################################################################################
# Copy all the files to the deployed CLR installation. (Part 1)
####################################################################################
!if "$(TARGETCOMPLUS)" != ""
$(COPY_NAME) $(TARGETPATH)\mscorlib.dll $(TARGETCOMPLUS)
$(COPY_NAME) $(TARGETPATH)\*.nlp $(TARGETCOMPLUS)
!endif
####################################################################################
# Check whether mscorlib.dll is using security permissions that it wasn't before.
# This will result in null declarative security blobs being placed into the metadata
# (since we need a working mscorlib to do the permission set translation) and a
# $(CSC_SECURITY_DB).raw file being generated (during the compile of mscorlib.dll)
# to indicate that we need to update the mapping database used to locate the correct
# metadata blobs. Once the security mapping database has been updated we rebuild
# mscorlib from scratch, and this time all the permissions should be mapped into
# metadata correctly.
####################################################################################
!if "$(PLATFORM_UNIX)" != "1"
cmd /C "if exist $(CSC_SECURITY_DB).raw pushd ..\ToolBox\SecDBEdit && build -cC && popd"
cmd /C "if exist $(CSC_SECURITY_DB).raw $(SECDBEDIT) -regen $(CSC_SECURITY_DB) xml"
cmd /C "if exist $(CSC_SECURITY_DB).raw build -c"
!else
if [ -f $(CSC_SECURITY_DB).raw ]; then cd ../toolbox/secdbedit && build -cC; fi
if [ -f $(CSC_SECURITY_DB).raw ]; then $(SECDBEDIT) -regen $(CSC_SECURITY_DB) xml; fi
if [ -f $(CSC_SECURITY_DB).raw ]; then build -c; fi
!endif
!endif # $(COMPLUSTARGET)
TARGET_EXTENSION_ = dll
TARGET_MANAGED_PDB = $(TARGETPATH)\mscorlib.pdb
TARGET_MANAGED_PDB = $(TARGETPATH)\mscorlib.ildb
!INCLUDE $(NTMAKEENV)\mk_mngpdb.inc
+154
View File
@@ -0,0 +1,154 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
//-------------------------------------------------------------
// FusionInterfaces.cs
//
// This implements wrappers to Fusion interfaces
//-------------------------------------------------------------
namespace Microsoft.Win32
{
using System;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Globalization;
using StringBuilder = System.Text.StringBuilder;
internal struct AssemblyInformation
{
public String FullName;
public String Name;
public String Version;
public String Locale;
public String PublicKeyToken;
}
internal class ASM_CACHE
{
public const uint ZAP = 0x1;
public const uint GAC = 0x2;
public const uint DOWNLOAD = 0x4;
}
internal class CANOF
{
public const uint PARSE_DISPLAY_NAME = 0x1;
public const uint SET_DEFAULT_VALUES = 0x2;
}
internal class ASM_NAME
{
public const uint PUBLIC_KEY = 0;
public const uint PUBLIC_KEY_TOKEN = PUBLIC_KEY + 1;
public const uint HASH_VALUE = PUBLIC_KEY_TOKEN + 1;
public const uint NAME = HASH_VALUE + 1;
public const uint MAJOR_VERSION = NAME + 1;
public const uint MINOR_VERSION = MAJOR_VERSION + 1;
public const uint BUILD_NUMBER = MINOR_VERSION + 1;
public const uint REVISION_NUMBER = BUILD_NUMBER + 1;
public const uint CULTURE = REVISION_NUMBER + 1;
public const uint PROCESSOR_ID_ARRAY = CULTURE + 1;
public const uint OSINFO_ARRAY = PROCESSOR_ID_ARRAY + 1;
public const uint HASH_ALGID = OSINFO_ARRAY + 1;
public const uint ALIAS = HASH_ALGID + 1;
public const uint CODEBASE_URL = ALIAS + 1;
public const uint CODEBASE_LASTMOD = CODEBASE_URL + 1;
public const uint NULL_PUBLIC_KEY = CODEBASE_LASTMOD + 1;
public const uint NULL_PUBLIC_KEY_TOKEN = NULL_PUBLIC_KEY + 1;
public const uint CUSTOM = NULL_PUBLIC_KEY_TOKEN + 1;
public const uint NULL_CUSTOM = CUSTOM + 1;
public const uint MVID = NULL_CUSTOM + 1;
public const uint _32_BIT_ONLY = MVID + 1;
public const uint MAX_PARAMS = _32_BIT_ONLY + 1;
}
internal class Fusion
{
public static void ReadCache(ArrayList alAssems, String name, uint nFlag)
{
IntPtr aEnum = IntPtr.Zero;
IntPtr aName = IntPtr.Zero;
IntPtr aNameEnum = IntPtr.Zero;
IntPtr AppCtx = IntPtr.Zero;
int hr;
try
{
if (name != null) {
hr = CreateAssemblyNameObject(out aNameEnum, name, CANOF.PARSE_DISPLAY_NAME, IntPtr.Zero);
if (hr != 0)
return;
}
hr = CreateAssemblyEnum(out aEnum, AppCtx, aNameEnum, nFlag, IntPtr.Zero);
while (hr == 0)
{
hr = GetNextAssembly(aEnum, ref AppCtx, ref aName, 0);
if (hr != 0)
break;
String sDisplayName = GetDisplayName(aName, 0);
if (sDisplayName == null)
continue;
// Our info is in a comma seperated list. Let's pull it out
String[] sFields = sDisplayName.Split(new char[] {','});
AssemblyInformation newguy = new AssemblyInformation();
newguy.FullName = sDisplayName;
newguy.Name = sFields[0];
// The version string is represented as Version=######
// Let's take out the 'Version='
newguy.Version = sFields[1].Substring(sFields[1].IndexOf('=')+1);
// Same goes for the locale
newguy.Locale = sFields[2].Substring(sFields[2].IndexOf('=')+1);
// And the key token
sFields[3]=sFields[3].Substring(sFields[3].IndexOf('=')+1);
if (sFields[3].Equals("null"))
sFields[3] = "null";
newguy.PublicKeyToken = sFields[3];
alAssems.Add(newguy);
}
}
finally
{
ReleaseFusionHandle(ref aEnum);
ReleaseFusionHandle(ref aName);
ReleaseFusionHandle(ref aNameEnum);
ReleaseFusionHandle(ref AppCtx);
}
}
[DllImport(Win32Native.FUSION, CharSet=CharSet.Auto)]
static extern int CreateAssemblyNameObject(out IntPtr ppEnum, [MarshalAs(UnmanagedType.LPWStr)]String szAssemblyName, uint dwFlags, IntPtr pvReserved);
[DllImport(Win32Native.FUSION, CharSet=CharSet.Auto)]
static extern int CreateAssemblyEnum(out IntPtr ppEnum, IntPtr pAppCtx, IntPtr pName, uint dwFlags, IntPtr pvReserved);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern int GetNextAssembly(IntPtr pEnum, ref IntPtr ppAppCtx, ref IntPtr ppName, uint dwFlags);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern String GetDisplayName(IntPtr pName, uint dwDisplayFlags);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern void ReleaseFusionHandle(ref IntPtr pp);
}
}
+491
View File
@@ -0,0 +1,491 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: Microsoft.Win32.Native
**
**
**
** Purpose: The CLR wrapper for all Win32 (Win2000, NT4, Win9x, Wince, etc.)
** native operations.
**
** Date: September 28, 1999
**
===========================================================*/
/**
* Notes to PInvoke users: Getting the syntax exactly correct is crucial, and
* more than a little confusing. Here's some guidelines.
*
* Use IntPtr for all OS handles and pointers. IntPtr will do the right thing
* when porting to 64 bit platforms, and MUST be used in all of our public
* APIs (and therefore in our private APIs too, once we get 64 bit builds working).
*
* If you have a method that takes a native struct, you have two options for
* declaring that struct. You can make it a value class ('struct' in CSharp), or
* a normal class. This choice doesn't seem very interesting, but your function
* prototype must use different syntax depending on your choice. For example,
* if your native method is prototyped as such:
*
* bool GetVersionEx(OSVERSIONINFO & lposvi);
*
*
* you must EITHER THIS OR THE NEXT syntax:
*
* [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
* internal struct OSVERSIONINFO { ... }
*
* [DllImport(KERNEL32, CharSet=CharSet.Auto)]
* internal static extern bool GetVersionEx(ref OSVERSIONINFO lposvi);
*
* OR:
*
* [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
* internal class OSVERSIONINFO { ... }
*
* [DllImport(KERNEL32, CharSet=CharSet.Auto)]
* internal static extern bool GetVersionEx([In, Out] OSVERSIONINFO lposvi);
*
* Note that classes require being marked as [In, Out] while value classes must
* be passed as ref parameters.
*
* Also note the CharSet.Auto on GetVersionEx - while it does not take a String
* as a parameter, the OSVERSIONINFO contains an embedded array of TCHARs, so
* the size of the struct varies on different platforms, and there's a
* GetVersionExA & a GetVersionExW. Also, the OSVERSIONINFO struct has a sizeof
* field so the OS can ensure you've passed in the correctly-sized copy of an
* OSVERSIONINFO. You must explicitly set this using Marshal.SizeOf(Object);
*/
namespace Microsoft.Win32 {
using System;
using System.Security;
using System.Text;
using System.Configuration.Assemblies;
using System.Runtime.Remoting;
using System.Runtime.InteropServices;
/**
* Win32 encapsulation for MSCORLIB.
*/
// Remove the default demands for all N/Direct methods with this
// global declaration on the class.
//
[SuppressUnmanagedCodeSecurityAttribute()]
internal sealed class Win32Native {
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
internal class OSVERSIONINFO {
public OSVERSIONINFO() {
OSVersionInfoSize = (int)Marshal.SizeOf(this);
}
// The OSVersionInfoSize field must be set to Marshal.SizeOf(this)
internal int OSVersionInfoSize = 0;
internal int MajorVersion = 0;
internal int MinorVersion = 0;
internal int BuildNumber = 0;
internal int PlatformId = 0;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)]
internal String CSDVersion = null;
}
[StructLayout(LayoutKind.Sequential)]
internal class SECURITY_ATTRIBUTES {
internal int nLength = 0;
internal int lpSecurityDescriptor = 0;
internal int bInheritHandle = 0;
}
[StructLayout(LayoutKind.Sequential), Serializable]
internal struct WIN32_FILE_ATTRIBUTE_DATA {
internal int fileAttributes;
internal uint ftCreationTimeLow;
internal uint ftCreationTimeHigh;
internal uint ftLastAccessTimeLow;
internal uint ftLastAccessTimeHigh;
internal uint ftLastWriteTimeLow;
internal uint ftLastWriteTimeHigh;
internal int fileSizeHigh;
internal int fileSizeLow;
}
[StructLayout(LayoutKind.Sequential)]
internal struct FILE_TIME {
public FILE_TIME(long fileTime) {
lowDateTime = (int) fileTime;
highDateTime = (int) (fileTime >> 32);
}
internal int lowDateTime;
internal int highDateTime;
}
#if !PLATFORM_UNIX
internal const String DLLPREFIX = "";
internal const String DLLSUFFIX = ".dll";
#else // !PLATFORM_UNIX
#if __APPLE__
internal const String DLLPREFIX = "lib";
internal const String DLLSUFFIX = ".dylib";
#else
internal const String DLLPREFIX = "lib";
internal const String DLLSUFFIX = ".so";
#endif
#endif // !PLATFORM_UNIX
internal const String KERNEL32 = DLLPREFIX + "rotor_pal" + DLLSUFFIX;
internal const String USER32 = DLLPREFIX + "rotor_pal" + DLLSUFFIX;
internal const String ADVAPI32 = DLLPREFIX + "rotor_pal" + DLLSUFFIX;
internal const String OLE32 = DLLPREFIX + "rotor_pal" + DLLSUFFIX;
internal const String OLEAUT32 = DLLPREFIX + "rotor_palrt" + DLLSUFFIX;
internal const String SHIM = DLLPREFIX + "sscoree" + DLLSUFFIX;
internal const String FUSION = DLLPREFIX + "fusion" + DLLSUFFIX;
internal const String LSTRCPY = "lstrcpy";
internal const String LSTRCPYN = "lstrcpyn";
internal const String LSTRLEN = "lstrlen";
internal const String LSTRLENA = "lstrlenA";
internal const String LSTRLENW = "lstrlenW";
internal const String MOVEMEMORY = "RtlMoveMemory";
// From WinBase.h
internal const int SEM_FAILCRITICALERRORS = 1;
[DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
internal static extern bool GetVersionEx([In, Out] OSVERSIONINFO ver);
[DllImport(KERNEL32, CharSet=CharSet.Auto)]
internal static extern int FormatMessage(int dwFlags, IntPtr lpSource,
int dwMessageId, int dwLanguageId, StringBuilder lpBuffer,
int nSize, IntPtr va_list_arguments);
[DllImport(KERNEL32)]
internal static extern IntPtr LocalAlloc(int uFlags, IntPtr sizetdwBytes);
[DllImport(KERNEL32, SetLastError=true)]
internal static extern IntPtr LocalFree(IntPtr handle);
[DllImport(KERNEL32, CharSet=CharSet.Auto)]
internal static extern uint GetTempPath(int bufferLen, StringBuilder buffer);
[DllImport(KERNEL32, CharSet=CharSet.Auto, EntryPoint=LSTRCPY)]
internal static extern IntPtr lstrcpy(IntPtr dst, String src);
[DllImport(KERNEL32, CharSet=CharSet.Auto, EntryPoint=LSTRCPY)]
internal static extern IntPtr lstrcpy(StringBuilder dst, IntPtr src);
[DllImport(KERNEL32, CharSet=CharSet.Auto, EntryPoint=LSTRCPYN)]
internal static extern IntPtr lstrcpyn(Delegate d1, Delegate d2, int cb);
[DllImport(KERNEL32, CharSet=CharSet.Auto, EntryPoint=LSTRLEN)]
internal static extern int lstrlen(sbyte [] ptr);
[DllImport(KERNEL32, CharSet=CharSet.Auto, EntryPoint=LSTRLEN)]
internal static extern int lstrlen(IntPtr ptr);
[DllImport(KERNEL32, CharSet=CharSet.Ansi, EntryPoint=LSTRLENA)]
internal static extern int lstrlenA(IntPtr ptr);
[DllImport(KERNEL32, CharSet=CharSet.Unicode, EntryPoint=LSTRLENW)]
internal static extern int lstrlenW(IntPtr ptr);
[DllImport(Win32Native.OLEAUT32, CharSet=CharSet.Unicode)]
internal static extern IntPtr SysAllocStringLen(String src, int len); // BSTR
[DllImport(Win32Native.OLEAUT32)]
internal static extern int SysStringLen(IntPtr bstr);
[DllImport(Win32Native.OLEAUT32)]
internal static extern void SysFreeString(IntPtr bstr);
[DllImport(KERNEL32, CharSet=CharSet.Unicode, EntryPoint=MOVEMEMORY)]
internal static extern void CopyMemoryUni(IntPtr pdst, String psrc, IntPtr sizetcb);
[DllImport(KERNEL32, CharSet=CharSet.Unicode, EntryPoint=MOVEMEMORY)]
internal static extern void CopyMemoryUni(StringBuilder pdst,
IntPtr psrc, IntPtr sizetcb);
[DllImport(KERNEL32, CharSet=CharSet.Ansi, EntryPoint=MOVEMEMORY)]
internal static extern void CopyMemoryAnsi(IntPtr pdst, String psrc, IntPtr sizetcb);
[DllImport(KERNEL32, CharSet=CharSet.Ansi, EntryPoint=MOVEMEMORY)]
internal static extern void CopyMemoryAnsi(StringBuilder pdst,
IntPtr psrc, IntPtr sizetcb);
[DllImport(KERNEL32)]
internal static extern int GetACP();
// For GetFullPathName, the last param is a useless TCHAR**, set by native.
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
internal static extern int GetFullPathName(String path, int numBufferChars, StringBuilder buffer, IntPtr mustBeZero);
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
internal static extern IntPtr CreateFile(String lpFileName,
int dwDesiredAccess, int dwShareMode,
IntPtr lpSecurityAttributes, int dwCreationDisposition,
int dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
internal static extern IntPtr CreateFile(String lpFileName,
int dwDesiredAccess, System.IO.FileShare dwShareMode,
SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition,
int dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport(KERNEL32)]
internal static extern bool CloseHandle(IntPtr handle);
[DllImport(KERNEL32)]
internal static extern int GetFileType(IntPtr handle);
[DllImport(KERNEL32, SetLastError=true)]
internal static extern bool SetEndOfFile(IntPtr hFile);
[DllImport(KERNEL32, SetLastError=true, EntryPoint="SetFilePointer")]
private unsafe static extern int SetFilePointerWin32(IntPtr handle, int lo, int * hi, int origin);
internal unsafe static long SetFilePointer(IntPtr handle, long offset, System.IO.SeekOrigin origin, out int hr) {
hr = 0;
int lo = (int) offset;
int hi = (int) (offset >> 32);
lo = SetFilePointerWin32(handle, lo, &hi, (int) origin);
if (lo == -1 && ((hr = Marshal.GetLastWin32Error()) != 0))
return -1;
return (long) (((ulong) ((uint) hi)) << 32) | ((uint) lo);
}
[DllImport(KERNEL32, CharSet=CharSet.Unicode, SetLastError=true, EntryPoint="PAL_GetPALDirectoryW")]
internal static extern int GetSystemDirectory(StringBuilder sb, int length);
[DllImport(OLEAUT32, CharSet=CharSet.Unicode, SetLastError=true, EntryPoint="PAL_FetchConfigurationStringW")]
internal static extern bool FetchConfigurationString(bool perMachine, String parameterName, StringBuilder parameterValue, int parameterValueLength);
[DllImport(KERNEL32, SetLastError=true)]
internal unsafe static extern bool SetFileTime(IntPtr hFile, FILE_TIME* creationTime,
FILE_TIME* lastAccessTime, FILE_TIME* lastWriteTime);
[DllImport(KERNEL32, SetLastError=true)]
internal static extern int GetFileSize(IntPtr hFile, out int highSize);
[DllImport(KERNEL32, SetLastError=true)]
internal static extern bool LockFile(IntPtr handle, long offset, long count);
[DllImport(KERNEL32, SetLastError=true)]
internal static extern bool UnlockFile(IntPtr handle,long offset,long count);
[DllImport(KERNEL32, SetLastError=true)]
internal static extern IntPtr GetStdHandle(int nStdHandle); // param is NOT a handle, but it returns one!
internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // WinBase.h
internal static readonly IntPtr NULL = IntPtr.Zero;
// Note, these are #defines used to extract handles, and are NOT handles.
internal const int STD_INPUT_HANDLE = -10;
internal const int STD_OUTPUT_HANDLE = -11;
internal const int STD_ERROR_HANDLE = -12;
// From wincon.h
internal const int ENABLE_LINE_INPUT = 0x0002;
internal const int ENABLE_ECHO_INPUT = 0x0004;
// From WinBase.h
internal const int FILE_TYPE_DISK = 0x0001;
internal const int FILE_TYPE_CHAR = 0x0002;
internal const int FILE_TYPE_PIPE = 0x0003;
// Constants from WinNT.h
internal const int FILE_ATTRIBUTE_DIRECTORY = 0x10;
// Error codes from WinError.h
internal const int ERROR_FILE_NOT_FOUND = 0x2;
internal const int ERROR_PATH_NOT_FOUND = 0x3;
internal const int ERROR_ACCESS_DENIED = 0x5;
internal const int ERROR_INVALID_HANDLE = 0x6;
internal const int ERROR_NO_MORE_FILES = 0x12;
internal const int ERROR_NOT_READY = 0x15;
internal const int ERROR_SHARING_VIOLATION = 0x20;
internal const int ERROR_FILE_EXISTS = 0x50;
internal const int ERROR_INVALID_PARAMETER = 0x57;
internal const int ERROR_CALL_NOT_IMPLEMENTED = 0x78;
internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE; // filename too long.
internal const int ERROR_DLL_INIT_FAILED = 0x45A;
// For the registry class
internal const int ERROR_MORE_DATA = 234;
// Use this to translate error codes like the above into HRESULTs like
// 0x80070006 for ERROR_INVALID_HANDLE
internal static int MakeHRFromErrorCode(int errorCode)
{
BCLDebug.Assert((0xFFFF0000 & errorCode) == 0, "This is an HRESULT, not an error code!");
return unchecked(((int)0x80070000) | errorCode);
}
// Win32 Structs in N/Direct style
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto), Serializable]
internal class WIN32_FIND_DATA {
internal int dwFileAttributes = 0;
// ftCreationTime was a by-value FILETIME structure
internal int ftCreationTime_dwLowDateTime = 0 ;
internal int ftCreationTime_dwHighDateTime = 0;
// ftLastAccessTime was a by-value FILETIME structure
internal int ftLastAccessTime_dwLowDateTime = 0;
internal int ftLastAccessTime_dwHighDateTime = 0;
// ftLastWriteTime was a by-value FILETIME structure
internal int ftLastWriteTime_dwLowDateTime = 0;
internal int ftLastWriteTime_dwHighDateTime = 0;
internal int nFileSizeHigh = 0;
internal int nFileSizeLow = 0;
internal int dwReserved0 = 0;
internal int dwReserved1 = 0;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=260)]
internal String cFileName = null;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=14)]
internal String cAlternateFileName = null;
}
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
internal static extern bool CopyFile(
String src, String dst, bool failIfExists);
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
internal static extern bool CreateDirectory(
String path, int lpSecurityAttributes);
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
internal static extern bool DeleteFile(String path);
[DllImport(KERNEL32, SetLastError=true)]
internal static extern bool FindClose(IntPtr hndFindFile);
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
internal static extern IntPtr FindFirstFile(
String pFileName,
[In, Out]
WIN32_FIND_DATA pFindFileData);
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
internal static extern bool FindNextFile(
IntPtr hndFindFile,
[In, Out, MarshalAs(UnmanagedType.LPStruct)]
WIN32_FIND_DATA lpFindFileData);
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
internal static extern int GetCurrentDirectory(
int nBufferLength,
StringBuilder lpBuffer);
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
internal static extern int GetFileAttributes(String name);
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
internal static extern bool GetFileAttributesEx(String name, int fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation);
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
internal static extern bool SetFileAttributes(String name, int attr);
#if !PLATFORM_UNIX
[DllImport("kernel32.dll", SetLastError=true)]
internal static extern int GetLogicalDrives();
#endif // !PLATFORM_UNIX
[DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
internal static extern uint GetTempFileName(String tmpPath, String prefix, uint uniqueIdOrZero, StringBuilder tmpFileName);
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
internal static extern bool MoveFile(String src, String dst);
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
internal static extern bool RemoveDirectory(String path);
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto)]
internal static extern bool SetCurrentDirectory(String path);
[DllImport(KERNEL32, SetLastError=false)]
internal static extern int SetErrorMode(int newMode);
internal const int LCID_SUPPORTED = 0x00000002; // supported locale ids
[DllImport(KERNEL32)]
internal static extern int /*LCID*/ GetUserDefaultLCID();
[DllImport(KERNEL32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
internal static extern int GetModuleFileName(IntPtr hModule, StringBuilder buffer, int length);
// managed cryptography wrapper around the PALRT cryptography api
internal const int PAL_HCRYPTPROV = 123;
internal const int CALG_MD2 = ((4 << 13) | 1);
internal const int CALG_MD4 = ((4 << 13) | 2);
internal const int CALG_MD5 = ((4 << 13) | 3);
internal const int CALG_SHA = ((4 << 13) | 4);
internal const int CALG_SHA1 = ((4 << 13) | 4);
internal const int CALG_MAC = ((4 << 13) | 5);
internal const int CALG_SSL3_SHAMD5 = ((4 << 13) | 8);
internal const int CALG_HMAC = ((4 << 13) | 9);
internal const int HP_ALGID = 0x0001;
internal const int HP_HASHVAL = 0x0002;
internal const int HP_HASHSIZE = 0x0004;
[DllImport(OLEAUT32, CharSet=CharSet.Unicode, EntryPoint="CryptAcquireContextW")]
internal extern static bool CryptAcquireContext(out IntPtr hProv,
[MarshalAs(UnmanagedType.LPWStr)] string container,
[MarshalAs(UnmanagedType.LPWStr)] string provider,
int provType,
int flags);
[DllImport(OLEAUT32, SetLastError=true)]
internal extern static bool CryptReleaseContext( IntPtr hProv, int flags);
[DllImport(OLEAUT32, SetLastError=true)]
internal extern static bool CryptCreateHash(IntPtr hProv, int Algid, IntPtr hKey, int flags, out IntPtr hHash);
[DllImport(OLEAUT32, SetLastError=true)]
internal extern static bool CryptDestroyHash(IntPtr hHash);
[DllImport(OLEAUT32, SetLastError=true)]
internal extern static bool CryptHashData(IntPtr hHash,
[In, MarshalAs(UnmanagedType.LPArray)] byte[] data,
int length,
int flags);
[DllImport(OLEAUT32, SetLastError=true)]
internal extern static bool CryptGetHashParam(IntPtr hHash,
int param,
[Out, MarshalAs(UnmanagedType.LPArray)] byte[] digest,
ref int length,
int flags);
[DllImport(OLEAUT32, SetLastError=true)]
internal extern static bool CryptGetHashParam(IntPtr hHash,
int param,
out int data,
ref int length,
int flags);
[DllImport(KERNEL32, EntryPoint="PAL_Random")]
internal extern static bool Random(bool bStrong,
[Out, MarshalAs(UnmanagedType.LPArray)] byte[] buffer, int length);
}
}
+60
View File
@@ -0,0 +1,60 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
//*****************************************************************************
// mscorlib.rc
//
// Holds version stamp for this program.
//
//*****************************************************************************
#include <winver.h>
#include <__file__.ver> //file version info - variable, but same for all files
#include <__product__.ver> //product version info - variable
#include <corver.h> //product version info - fixed
#include "__file__.h" // file version info - fixed per file
VS_VERSION_INFO VERSIONINFO
FILEVERSION VER_FILEVERSION
PRODUCTVERSION VER_PRODUCTVERSION
FILEFLAGSMASK VER_FILEFLAGSMASK
FILEFLAGS VER_FILEFLAGS
FILEOS VER_FILEOS
FILETYPE VER_FILETYPE
BEGIN
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1252
// English language (0x409) and the Windows ANSI codepage (1252)
END
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904E4" // Lang=US English, CharSet=Windows Multilingual
BEGIN
// Note: Non-standard value strings must be first as FileManager has a bug
// that leaves garbage in its name buffer otherwise.
VALUE "Platform", VER_PLATFORMINFO_STR
VALUE "CompanyName", VER_COMPANYNAME_STR
VALUE "FileDescription", VER_FILEDESCRIPTION_STR
VALUE "FileVersion", VER_FILEVERSION_STR
VALUE "InternalName", VER_INTERNALNAME_STR
VALUE "LegalCopyright", VER_LEGALCOPYRIGHT_STR
VALUE "LegalTrademarks", VER_LEGALTRADEMARKS_STR
VALUE "OriginalFilename",VER_ORIGFILENAME_STR
VALUE "ProductName", VER_PRODUCTNAME_STR
VALUE "ProductVersion", VER_PRODUCTVERSION_STR
VALUE "Comments", VER_FILEDESCRIPTION_STR
END
END
END
File diff suppressed because it is too large Load Diff
+823
View File
@@ -0,0 +1,823 @@
# ==++==
#
#
# Copyright (c) 2002 Microsoft Corporation. All rights reserved.
#
# The use and distribution terms for this software are contained in the file
# named license.txt, which can be found in the root of this distribution.
# By using this software in any fashion, you are agreeing to be bound by the
# terms of this license.
#
# You must not remove this notice, or any other, from this software.
#
#
# ==--==
SYNCHRONIZE_DRAIN=1
SYNCHRONIZE_BLOCK=1
!CMDSWITCHES -I
NEWCALL_TOO = 1
NTTARGETFILE0 = prep_target
!include $(NTMAKEENV)\sources.csc
TARGETNAME =mscorlib
TARGETLIBNAME =$(TARGETNAME)
TARGETPATH =$(TARGETCORLIB)\$(TARGET_DIRECTORY)\$(DDKBUILDENV)
TARGETTYPE =DYNLINK
NO_BROWSER_FILE =1
SOURCES =
BUILDING_MSCORLIB = 1
REQUIRES_SETUP_PHASE = 1
INCLUDE_ASSEMBLY_ATTRIBUTES=
!ifdef LINKONLY
NTTARGETFILES = $(NTTARGETFILES) CopyManagedPdb
!endif
CSC_SOURCE_DIR = $(CORBASE)\src\bcl
CSC_CLASS_DIR = $(CSC_SOURCE_DIR)\$(_OBJ_DIR)\$(TARGET_DIRECTORY)
CSC_TARGET_TYPE = DYNLINK
# Base address to load mscorlib.dll
CSC_BASE = $(TARGETNAME)
ASSEMBLY_KEY_TYPE=ECMA
SIGN_ASSEMBLY=1
# Run comreg to export a type library (.tlb)
CSC_TYPELIB_EXPORT = 1
INCLUDES=$(INCLUDES);$(NTMAKEENV)
# Include a version stamp for Windows' Explorer's version tab.
WIN32_RESOURCE_FILE = mscorlib.rc
CSC_COMPILE_FLAGS = $(CSC_COMPILE_FLAGS) /d:_NEW_CLASSLOADER /nostdlib /nowarn:679 /nowarn:169 /d:NODEFAULTLIB /test:moduleName=CommonLanguageRuntimeLibrary /d:_USE_NLS_PLUS_TABLE /unsafe
# In retail, ignore warnings about unused variables.
!if "$(DDKBUILDENV)" != "checked" && "$(DDKBUILDENV)" != "fastchecked"
CSC_COMPILE_FLAGS = $(CSC_COMPILE_FLAGS) /nowarn:649
!endif
CSC_COMPILE_FLAGS = $(CSC_EXTRA_PREPROCESS_FLAGS) $(CSC_COMPILE_FLAGS)
!if "$(_TGTOS)" == "NT64"
CSC_COMPILE_FLAGS = $(CSC_COMPILE_FLAGS) /d:WIN64
!else
CSC_COMPILE_FLAGS = $(CSC_COMPILE_FLAGS) /d:WIN32
!endif
CSC_SECURITY_DB = securitydb
CSC_RESOURCE_FLAGS = \
/res:$(TARGETPATH)\mscorlib.resources,mscorlib.resources \
/linkres:$(TARGETPATH)\ctype.nlp,ctype.nlp \
/linkres:$(TARGETPATH)\l_intl.nlp,l_intl.nlp \
/linkres:$(TARGETPATH)\l_except.nlp,l_except.nlp \
/linkres:$(TARGETPATH)\culture.nlp,culture.nlp \
/linkres:$(TARGETPATH)\region.nlp,region.nlp \
/linkres:$(TARGETPATH)\sortkey.nlp,sortkey.nlp \
/linkres:$(TARGETPATH)\sorttbls.nlp,sorttbls.nlp \
/linkres:$(TARGETPATH)\charinfo.nlp,charinfo.nlp \
/linkres:$(TARGETPATH)\big5.nlp,big5.nlp \
/linkres:$(TARGETPATH)\bopomofo.nlp,bopomofo.nlp \
/linkres:$(TARGETPATH)\ksc.nlp,ksc.nlp \
/linkres:$(TARGETPATH)\prc.nlp,prc.nlp \
/linkres:$(TARGETPATH)\prcp.nlp,prcp.nlp \
/linkres:$(TARGETPATH)\xjis.nlp,xjis.nlp
# The first set of ~17 files are in order of the classes
# loaded at startup. Try not to change this order. Working set
# perf degrades if done so.
RUNTIME_SOURCES = \
system\object.cs \
system\icloneable.cs \
system\array.cs \
system\icomparable.cs \
system\string.cs \
system\text\stringbuilder.cs \
system\exception.cs \
system\datetime.cs \
system\systemexception.cs \
system\outofmemoryexception.cs \
system\stackoverflowexception.cs \
system\executionengineexception.cs \
system\delegate.cs \
system\multicastdelegate.cs \
system\__filters.cs \
system\__hresults.cs \
system\bcldebug.cs \
system\memberaccessexception.cs \
system\activator.cs \
system\applicationexception.cs \
system\appdomain.cs \
system\iappdomain.cs \
system\iappdomainsetup.cs \
system\appdomainattributes.cs \
system\appdomainunloadedexception.cs \
system\argumentexception.cs \
system\argumentnullexception.cs \
system\argumentoutofrangeexception.cs \
system\argiterator.cs \
system\arithmeticexception.cs \
system\arraytypemismatchexception.cs \
system\asynccallback.cs \
system\attribute.cs \
system\attributetargets.cs \
system\attributeusageattribute.cs \
system\badimageformatexception.cs \
system\bitconverter.cs \
system\boolean.cs \
system\buffer.cs \
system\byte.cs \
system\cannotunloadappdomainexception.cs \
system\char.cs \
system\charenumerator.cs \
system\cfgparser.cs \
system\clscompliantattribute.cs \
system\typeunloadedexception.cs \
system\console.cs \
system\contextmarshalexception.cs \
system\convert.cs \
system\contextboundobject.cs \
system\contextstaticattribute.cs \
system\currency.cs \
system\currenttimezone.cs \
system\dayofweek.cs \
system\dbnull.cs \
system\decimal.cs \
system\defaultbinder.cs \
system\delegateserializationholder.cs \
system\dividebyzeroexception.cs \
system\double.cs \
system\duplicatewaitobjectexception.cs \
system\empty.cs \
system\enum.cs \
system\entrypointnotfoundexception.cs \
system\dllnotfoundexception.cs \
system\environment.cs \
system\eventargs.cs \
system\eventhandler.cs \
system\fieldaccessexception.cs \
system\flagsattribute.cs \
system\formatexception.cs \
system\gc.cs \
system\guid.cs \
system\iasyncresult.cs \
system\icustomformatter.cs \
system\idisposable.cs \
system\iformatprovider.cs \
system\iformattable.cs \
system\indexoutofrangeexception.cs \
system\int16.cs \
system\int32.cs \
system\int64.cs \
system\intptr.cs \
system\internal.cs \
system\invalidcastexception.cs \
system\invalidoperationexception.cs \
system\invalidprogramexception.cs \
system\iconvertible.cs \
system\iserviceobjectprovider.cs \
system\_localdatastore.cs \
system\_localdatastoremgr.cs \
system\marshalbyrefobject.cs \
system\math.cs \
system\methodaccessexception.cs \
system\missingfieldexception.cs \
system\missingmemberexception.cs \
system\missingmethodexception.cs \
system\multicastnotsupportedexception.cs \
system\nonserializedattribute.cs \
system\notfinitenumberexception.cs \
system\notimplementedexception.cs \
system\notsupportedexception.cs \
system\nullreferenceexception.cs \
system\number.cs \
system\objectdisposedexception.cs \
system\obsoleteattribute.cs \
system\oleautbinder.cs \
system\overflowexception.cs \
system\paramarrayattribute.cs \
system\parsenumbers.cs \
system\platformnotsupportedexception.cs \
system\random.cs \
system\rankexception.cs \
system\resid.cs \
system\runtimeargumenthandle.cs \
system\runtimefieldhandle.cs \
system\runtimemethodhandle.cs \
system\runtimetype.cs \
system\runtimetypehandle.cs \
system\sbyte.cs \
system\serializableattribute.cs \
system\sharedstatics.cs \
system\single.cs \
system\timespan.cs \
system\timezone.cs \
system\type.cs \
system\typecode.cs \
system\typedreference.cs \
system\typeinitializationexception.cs \
system\typeloadexception.cs \
system\uint16.cs \
system\uint32.cs \
system\uint64.cs \
system\uintptr.cs \
system\unauthorizedaccessexception.cs \
system\unityserializationholder.cs \
system\unhandledexceptioneventargs.cs \
system\unhandledexceptioneventhandler.cs \
system\valuetype.cs \
system\variant.cs \
system\version.cs \
system\void.cs \
system\weakreference.cs \
CONFIGURATION_ASSEMBLIES_SOURCES= \
system\configuration\assemblies\assemblyhash.cs \
system\configuration\assemblies\assemblyhashalgorithm.cs \
system\configuration\assemblies\assemblyversioncompatibility.cs \
THREADING_SOURCES = \
system\threading\__handleprotector.cs \
system\threading\autoresetevent.cs \
system\threading\interlocked.cs \
system\threading\iobjecthandle.cs \
system\threading\lockcookie.cs \
system\threading\manualresetevent.cs \
system\threading\monitor.cs \
system\threading\mutex.cs \
system\threading\overlapped.cs \
system\threading\readerwriterlock.cs \
system\threading\synchronizationlockexception.cs \
system\threading\thread.cs \
system\threading\threadabortexception.cs \
system\threading\threadinterruptedexception.cs \
system\threading\threadpool.cs \
system\threading\threadpriority.cs \
system\threading\threadstart.cs \
system\threading\threadstate.cs \
system\threading\threadstateexception.cs \
system\threadstaticattribute.cs \
system\threading\threadstopexception.cs \
system\threading\timeout.cs \
system\threading\timer.cs \
system\threading\waithandle.cs \
SERIALIZATION_SOURCES = \
system\runtime\serialization\deserializationeventhandler.cs \
system\runtime\serialization\formatter.cs \
system\runtime\serialization\formatterconverter.cs \
system\runtime\serialization\formatterservices.cs \
system\runtime\serialization\ideserializationcallback.cs \
system\runtime\serialization\iformatter.cs \
system\runtime\serialization\iformatterconverter.cs \
system\runtime\serialization\iobjectreference.cs \
system\runtime\serialization\iserializable.cs \
system\runtime\serialization\iserializationsurrogate.cs \
system\runtime\serialization\isurrogateselector.cs \
system\runtime\serialization\objectidgenerator.cs \
system\runtime\serialization\objectmanager.cs \
system\runtime\serialization\memberholder.cs \
system\runtime\serialization\serializationbinder.cs \
system\runtime\serialization\serializationfieldinfo.cs \
system\runtime\serialization\serializationinfo.cs \
system\runtime\serialization\serializationinfoenumerator.cs \
system\runtime\serialization\serializationexception.cs \
system\runtime\serialization\streamingcontext.cs \
system\runtime\serialization\surrogateselector.cs \
system\runtime\serialization\valuetypefixupinfo.cs \
COLLECTIONS_SOURCES = \
system\collections\arraylist.cs \
system\collections\bitarray.cs \
system\collections\caseinsensitivecomparer.cs \
system\collections\caseinsensitivehashcodeprovider.cs \
system\collections\collectionbase.cs \
system\collections\comparer.cs \
system\collections\dictionarybase.cs \
system\collections\dictionaryentry.cs \
system\collections\hashtable.cs \
system\collections\icollection.cs \
system\collections\icomparer.cs \
system\collections\idictionary.cs \
system\collections\idictionaryenumerator.cs \
system\collections\ienumerable.cs \
system\collections\ienumerator.cs \
system\collections\ihashcodeprovider.cs \
system\collections\ilist.cs \
system\collections\queue.cs \
system\collections\readonlycollectionbase.cs \
system\collections\sortedlist.cs \
system\collections\stack.cs \
WIN32_SOURCES = \
microsoft\win32\fusionwrap.cs \
microsoft\win32\win32native.cs \
DIAGNOSTICS_SOURCES = \
system\diagnostics\assert.cs \
system\diagnostics\assertfilter.cs \
system\diagnostics\assertfilters.cs \
system\diagnostics\conditionalattribute.cs \
system\diagnostics\debugger.cs \
system\diagnostics\debuggerattributes.cs \
system\diagnostics\log.cs \
system\diagnostics\logginglevels.cs \
system\diagnostics\logswitch.cs \
system\diagnostics\stacktrace.cs \
system\diagnostics\stackframe.cs \
DIAGNOSTICS_SYMBOLSTORE_SOURCES = \
system\diagnostics\symbolstore\isymbinder.cs \
system\diagnostics\symbolstore\isymdocument.cs \
system\diagnostics\symbolstore\isymdocumentwriter.cs \
system\diagnostics\symbolstore\isymmethod.cs \
system\diagnostics\symbolstore\isymnamespace.cs \
system\diagnostics\symbolstore\isymreader.cs \
system\diagnostics\symbolstore\isymscope.cs \
system\diagnostics\symbolstore\isymvariable.cs \
system\diagnostics\symbolstore\isymwriter.cs \
system\diagnostics\symbolstore\symaddresskind.cs \
system\diagnostics\symbolstore\symdocumenttype.cs \
system\diagnostics\symbolstore\symlanguagetype.cs \
system\diagnostics\symbolstore\symlanguagevendor.cs \
system\diagnostics\symbolstore\token.cs \
PERMISSIONS_SOURCES = \
system\security\permissions\environmentpermission.cs \
system\security\permissions\filedialogpermission.cs \
system\security\permissions\fileiopermission.cs \
system\security\permissions\ibuiltinpermission.cs \
system\security\permissions\isolatedstoragepermission.cs \
system\security\permissions\isolatedstoragefilepermission.cs \
system\security\permissions\permissionstate.cs \
system\security\permissions\permissionattributes.cs \
system\security\permissions\reflectionpermission.cs \
system\security\permissions\principalpermission.cs \
system\security\permissions\securitypermission.cs \
system\security\permissions\siteidentitypermission.cs \
system\security\permissions\strongnameidentitypermission.cs \
system\security\permissions\strongnamepublickeyblob.cs \
system\security\permissions\uipermission.cs \
system\security\permissions\urlidentitypermission.cs \
system\security\permissions\zoneidentitypermission.cs \
system\security\permissions\iunrestrictedpermission.cs \
SEC_UTIL_SOURCES = \
system\security\util\config.cs \
system\security\util\hex.cs \
system\security\util\sitestring.cs \
system\security\util\stringexpressionset.cs \
system\security\util\tokenbasedset.cs \
system\security\util\tokenbasedsetenumerator.cs \
system\security\util\urlstring.cs \
system\security\util\xmlutil.cs \
SECURITY_SOURCES = \
system\security\attributes.cs \
system\security\codeaccesspermission.cs \
system\security\codeaccesssecurityengine.cs \
system\security\ievidencefactory.cs \
system\security\ipermission.cs \
system\security\isecurityencodable.cs \
system\security\isecuritypolicyencodable.cs \
system\security\istackwalk.cs \
system\security\framesecuritydescriptor.cs \
system\security\permissionsetenumerator.cs \
system\security\permissionlist.cs \
system\security\permissionlistset.cs \
system\security\permissionlistsetenumerator.cs \
system\security\permissiontoken.cs \
system\security\policymanager.cs \
system\security\securityexception.cs \
system\security\securitymanager.cs \
system\security\securityruntime.cs \
system\security\securityzone.cs \
system\security\verificationexception.cs \
SECURITY_POLICY_SOURCES = \
system\security\policy\allmembershipcondition.cs \
system\security\policy\applicationdirectory.cs \
system\security\policy\applicationdirectorymembershipcondition.cs \
system\security\policy\codegroup.cs \
system\security\policy\evidence.cs \
system\security\policy\filecodegroup.cs \
system\security\policy\firstmatchcodegroup.cs \
system\security\policy\ibuiltinevidence.cs \
system\security\policy\iidentitypermissionfactory.cs \
system\security\policy\iconstantmembershipcondition.cs \
system\security\policy\imembershipcondition.cs \
system\security\policy\netcodegroup.cs \
system\security\policy\permissionrequestevidence.cs \
system\security\policy\policyexception.cs \
system\security\policy\policylevel.cs \
system\security\policy\policystatement.cs \
system\security\policy\site.cs \
system\security\policy\sitemembershipcondition.cs \
system\security\policy\strongname.cs \
system\security\policy\strongnamemembershipcondition.cs \
system\security\policy\unioncodegroup.cs \
system\security\policy\url.cs \
system\security\policy\urlmembershipcondition.cs \
system\security\policy\zone.cs \
system\security\policy\zonemembershipcondition.cs \
SECURITY_PRINCIPAL_SOURCES = \
system\security\principal\genericidentity.cs \
system\security\principal\genericprincipal.cs \
system\security\principal\iidentity.cs \
system\security\principal\iprincipal.cs \
system\security\principal\principalpolicy.cs \
SECURITY_SOURCES_PRE = \
system\security\permissionset.cs \
system\security\namedpermissionset.cs \
ISOSTORE_SOURCES = \
system\io\isolatedstorage\isolatedstorage.cs \
system\io\isolatedstorage\isolatedstoragefile.cs \
system\io\isolatedstorage\isolatedstoragefilestream.cs \
system\io\isolatedstorage\isolatedstorageexception.cs \
system\io\isolatedstorage\inormalizeforisolatedstorage.cs \
system\io\isolatedstorage\__hresults.cs \
XML_SOURCES = \
system\security\securityelement.cs \
system\security\util\parser.cs \
system\security\util\tokenizer.cs \
system\security\xmlsyntaxexception.cs \
REFLECTION_SOURCES = \
system\reflection\__filters.cs \
system\reflection\ambiguousmatchexception.cs \
system\reflection\assembly.cs \
system\reflection\assemblyattributes.cs \
system\reflection\assemblyname.cs \
system\reflection\assemblynameproxy.cs \
system\reflection\assemblynameflags.cs \
system\reflection\assemblyreflectionattributes.cs \
system\reflection\customattributeformatexception.cs \
system\reflection\binder.cs \
system\reflection\bindingflags.cs \
system\reflection\callingconventions.cs \
system\reflection\customattribute.cs \
system\reflection\constructorinfo.cs \
system\reflection\defaultmemberattribute.cs \
system\reflection\eventattributes.cs \
system\reflection\eventinfo.cs \
system\reflection\fieldattributes.cs \
system\reflection\fieldinfo.cs \
system\reflection\icustomattributeprovider.cs \
system\reflection\interfacemapping.cs \
system\reflection\invalidfiltercriteriaexception.cs \
system\reflection\ireflect.cs \
system\reflection\manifestresourceinfo.cs \
system\reflection\memberfilter.cs \
system\reflection\memberinfo.cs \
system\reflection\memberinfoserializationholder.cs \
system\reflection\methodbase.cs \
system\reflection\membertypes.cs \
system\reflection\methodattributes.cs \
system\reflection\methodimplattributes.cs \
system\reflection\methodinfo.cs \
system\reflection\methodsemanticsattributes.cs \
system\reflection\missing.cs \
system\reflection\module.cs \
system\reflection\parameterinfo.cs \
system\reflection\parameterattributes.cs \
system\reflection\parametermodifier.cs \
system\reflection\pointer.cs \
system\reflection\propertyinfo.cs \
system\reflection\propertyattributes.cs \
system\reflection\reflectiontypeloadexception.cs \
system\reflection\resourceattributes.cs \
system\reflection\runtimeconstructorinfo.cs \
system\reflection\runtimeeventinfo.cs \
system\reflection\runtimefieldinfo.cs \
system\reflection\runtimemethodinfo.cs \
system\reflection\runtimepropertyinfo.cs \
system\reflection\strongnamekeypair.cs \
system\reflection\targetexception.cs \
system\reflection\targetinvocationexception.cs \
system\reflection\targetparametercountexception.cs \
system\reflection\typeattributes.cs \
system\reflection\typedelegator.cs \
system\reflection\typefilter.cs \
system\reflection\unmanagedmarshal.cs \
REFLECTION_EMIT_SOURCES = \
system\reflection\emit\assemblybuilder.cs \
system\reflection\emit\assemblybuilderdata.cs \
system\reflection\emit\assemblybuilderaccess.cs \
system\reflection\emit\constructorbuilder.cs \
system\reflection\emit\eventbuilder.cs \
system\reflection\emit\eventtoken.cs \
system\reflection\emit\fieldbuilder.cs \
system\reflection\emit\fieldtoken.cs \
system\reflection\emit\ilgenerator.cs \
system\reflection\emit\label.cs \
system\reflection\emit\localbuilder.cs \
system\reflection\emit\methodbuilder.cs \
system\reflection\emit\symboltype.cs \
system\reflection\emit\symbolmethod.cs \
system\reflection\emit\customattributebuilder.cs \
system\reflection\emit\methodrental.cs \
system\reflection\emit\methodtoken.cs \
system\reflection\emit\modulebuilder.cs \
system\reflection\emit\modulebuilderdata.cs \
system\reflection\emit\pefilekinds.cs \
system\reflection\emit\opcodes.cs \
system\reflection\emit\opcode.cs \
system\reflection\emit\opcodetype.cs \
system\reflection\emit\stackbehaviour.cs \
system\reflection\emit\operandtype.cs \
system\reflection\emit\flowcontrol.cs \
system\reflection\emit\parameterbuilder.cs \
system\reflection\emit\parametertoken.cs \
system\reflection\emit\propertybuilder.cs \
system\reflection\emit\propertytoken.cs \
system\reflection\emit\signaturehelper.cs \
system\reflection\emit\signaturetoken.cs \
system\reflection\emit\stringtoken.cs \
system\reflection\emit\typebuilder.cs \
system\reflection\emit\enumbuilder.cs \
system\reflection\emit\typetoken.cs
REFLECTION_CACHE_SOURCES = \
system\reflection\cache\cacheobjtype.cs \
system\reflection\cache\clearcacheeventargs.cs \
system\reflection\cache\clearcachehandler.cs \
system\reflection\cache\internalcache.cs \
system\reflection\cache\internalcacheitem.cs \
system\reflection\cache\typenamecache.cs \
system\reflection\cache\typenamestruct.cs \
GLOBALIZATION_SOURCES = \
system\globalization\calendar.cs \
system\globalization\calendartable.cs \
system\globalization\characterinfo.cs \
system\globalization\compareinfo.cs \
system\globalization\cultureinfo.cs \
system\globalization\culturetypes.cs \
system\globalization\datetimeformat.cs \
system\globalization\datetimeparse.cs \
system\globalization\datetimestyles.cs \
system\globalization\datetimeformatinfo.cs \
system\globalization\daylighttime.cs \
system\globalization\defaultlcidmap.cs \
system\globalization\encodingdataitem.cs \
system\globalization\encodingtable.cs \
system\globalization\globalizationassembly.cs \
system\globalization\gregoriancalendar.cs \
system\globalization\gregoriancalendarhelper.cs \
system\globalization\hebrewcalendar.cs \
system\globalization\hijricalendar.cs \
system\globalization\japanesecalendar.cs \
system\globalization\juliancalendar.cs \
system\globalization\koreancalendar.cs \
system\globalization\namelcidinfo.cs \
system\globalization\regioninfo.cs \
system\globalization\sortkey.cs \
system\globalization\stringinfo.cs \
system\globalization\taiwancalendar.cs \
system\globalization\textelementenumerator.cs \
system\globalization\textinfo.cs \
system\globalization\thaibuddhistcalendar.cs \
system\globalization\numberformatinfo.cs \
system\globalization\numberstyles.cs \
system\globalization\unicodecategory.cs \
system\globalization\culturetable.cs \
system\globalization\regiontable.cs \
TEXT_SOURCES = \
system\text\asciiencoding.cs \
system\text\codepageencoding.cs \
system\text\decoder.cs \
system\text\encoder.cs \
system\text\encoding.cs \
system\text\surrogateencoder.cs \
system\text\unicodeencoding.cs \
system\text\utf7encoding.cs \
system\text\utf8encoding.cs \
IO_SOURCES = \
system\io\__debugoutputtextwriter.cs \
system\io\__consolestream.cs \
system\io\__error.cs \
system\io\__hresults.cs \
system\io\__unmanagedmemorystream.cs \
system\io\binaryreader.cs \
system\io\binarywriter.cs \
system\io\bufferedstream.cs \
system\io\directory.cs \
system\io\directoryinfo.cs \
system\io\directorynotfoundexception.cs \
system\io\endofstreamexception.cs \
system\io\file.cs \
system\io\fileinfo.cs \
system\io\fileaccess.cs \
system\io\filemode.cs \
system\io\fileloadexception.cs \
system\io\filenotfoundexception.cs \
system\io\fileshare.cs \
system\io\filestream.cs \
system\io\filesysteminfo.cs \
system\io\fileattributes.cs \
system\io\ioexception.cs \
system\io\memorystream.cs \
system\io\path.cs \
system\io\pathtoolongexception.cs \
system\io\seekorigin.cs \
system\io\stream.cs \
system\io\streamreader.cs \
system\io\streamwriter.cs \
system\io\stringreader.cs \
system\io\stringwriter.cs \
system\io\textreader.cs \
system\io\textwriter.cs \
COMPILER_SERVICES_SOURCES = \
system\runtime\compilerservices\accessedthroughpropertyattribute.cs \
system\runtime\compilerservices\assemblyattributesgohere.cs \
system\runtime\compilerservices\callingconvention.cs \
system\runtime\compilerservices\runtimehelpers.cs \
system\runtime\compilerservices\customconstantattribute.cs \
system\runtime\compilerservices\datetimeconstantattribute.cs \
system\runtime\compilerservices\discardableattribute.cs \
system\runtime\compilerservices\decimalconstantattribute.cs \
system\runtime\compilerservices\compilationrelaxations.cs \
system\runtime\compilerservices\compilerglobalscopeattribute.cs \
system\runtime\compilerservices\indexernameattribute.cs \
system\runtime\compilerservices\isvolatile.cs \
system\runtime\compilerservices\methodimplattribute.cs \
system\runtime\compilerservices\requiredattributeattribute.cs \
INTEROP_SOURCES = \
system\runtime\interopservices\arraywithoffset.cs \
system\runtime\interopservices\attributes.cs \
system\runtime\interopservices\callingconvention.cs \
system\runtime\interopservices\charset.cs \
system\runtime\interopservices\comexception.cs \
system\runtime\interopservices\externalexception.cs \
system\runtime\interopservices\gchandle.cs \
system\runtime\interopservices\handleref.cs \
system\runtime\interopservices\icustommarshaler.cs \
system\runtime\interopservices\invalidolevarianttypeexception.cs \
system\runtime\interopservices\layoutkind.cs \
system\runtime\interopservices\marshal.cs \
system\runtime\interopservices\marshaldirectiveexception.cs \
system\runtime\interopservices\pinvokemap.cs \
system\runtime\interopservices\runtimeenvironment.cs \
system\runtime\interopservices\sehexception.cs \
INTEROP_EXPANDO_SOURCES = \
system\runtime\interopservices\expando\iexpando.cs \
RESOURCES_SOURCES = \
system\resources\__fastresourcecomparer.cs \
system\resources\iresourcereader.cs \
system\resources\iresourcewriter.cs \
system\resources\missingmanifestresourceexception.cs \
system\resources\neutralresourceslanguageattribute.cs \
system\resources\resourcemanager.cs \
system\resources\resourcereader.cs \
system\resources\resourceset.cs \
system\resources\resourcewriter.cs \
system\resources\runtimeresourceset.cs \
system\resources\satellitecontractversionattribute.cs
REMOTING_SOURCES = \
system\runtime\remoting\__hresults.cs \
system\runtime\remoting\activationservices.cs \
system\runtime\remoting\asyncresult.cs \
system\runtime\remoting\callcontext.cs \
system\runtime\remoting\channelservices.cs \
system\runtime\remoting\channelsinkstacks.cs \
system\runtime\remoting\clientsponsor.cs \
system\runtime\remoting\configuration.cs \
system\runtime\remoting\context.cs \
system\runtime\remoting\contextproperty.cs \
system\runtime\remoting\crosscontextchannel.cs \
system\runtime\remoting\crossappdomainchannel.cs \
system\runtime\remoting\dispatchchannelsink.cs \
system\runtime\remoting\dynamicpropertyholder.cs \
system\runtime\remoting\header.cs \
system\runtime\remoting\headerhandler.cs \
system\runtime\remoting\iactivator.cs \
system\runtime\remoting\ichannel.cs \
system\runtime\remoting\icontributeclientcontextsink.cs \
system\runtime\remoting\icontributedynamicsink.cs \
system\runtime\remoting\icontributeenvoysink.cs \
system\runtime\remoting\icontributeobjectsink.cs \
system\runtime\remoting\icontributeservercontextsink.cs \
system\runtime\remoting\idynamicmessagesink.cs \
system\runtime\remoting\identity.cs \
system\runtime\remoting\identityholder.cs \
system\runtime\remoting\iinternalmessage.cs \
system\runtime\remoting\ilease.cs \
system\runtime\remoting\isponsor.cs \
system\runtime\remoting\imessage.cs \
system\runtime\remoting\imessagectrl.cs \
system\runtime\remoting\imessagesink.cs \
system\runtime\remoting\imethodmessage.cs \
system\runtime\remoting\iremotingformatter.cs \
system\runtime\remoting\lease.cs \
system\runtime\remoting\leasemanager.cs \
system\runtime\remoting\leasestate.cs \
system\runtime\remoting\lifetimeservices.cs \
system\runtime\remoting\message.cs \
system\runtime\remoting\messagesmuggler.cs \
system\runtime\remoting\objecthandle.cs \
system\runtime\remoting\objref.cs \
system\runtime\remoting\onewayattribute.cs \
system\runtime\remoting\proxyattribute.cs \
system\runtime\remoting\realproxy.cs \
system\runtime\remoting\redirectionproxy.cs \
system\runtime\remoting\remotingattributes.cs \
system\runtime\remoting\remotingconfigparser.cs \
system\runtime\remoting\remotingconfiguration.cs \
system\runtime\remoting\remotingexception.cs \
system\runtime\remoting\remotingproxy.cs \
system\runtime\remoting\remotingservices.cs \
system\runtime\remoting\remotingsurrogateselector.cs \
system\runtime\remoting\serveridentity.cs \
system\runtime\remoting\soap.cs \
system\runtime\remoting\soapinteroptypes.cs \
system\runtime\remoting\stackbuildersink.cs \
system\runtime\remoting\synchronizeddispatch.cs \
system\runtime\remoting\__transparentproxy.cs \
system\runtime\remoting\terminatorsinks.cs \
system\runtime\remoting\trackingservices.cs \
system\runtime\remoting\urlattribute.cs
SERIALIZATION_FORMATTERS_SOURCES = \
system\runtime\serialization\formatters\commonenums.cs \
system\runtime\serialization\formatters\isoapmessage.cs \
system\runtime\serialization\formatters\ifieldinfo.cs \
system\runtime\serialization\formatters\sertrace.cs \
system\runtime\serialization\formatters\soapmessage.cs \
system\runtime\serialization\formatters\soapfault.cs
SERIALIZATION_FORMATTERS_BINARY_SOURCES = \
system\runtime\serialization\formatters\binary\binaryenums.cs \
system\runtime\serialization\formatters\binary\binaryformatter.cs \
system\runtime\serialization\formatters\binary\binaryparser.cs \
system\runtime\serialization\formatters\binary\binaryformatterwriter.cs \
system\runtime\serialization\formatters\binary\binarycommonclasses.cs \
system\runtime\serialization\formatters\binary\binaryutilclasses.cs \
system\runtime\serialization\formatters\binary\binaryobjectreader.cs \
system\runtime\serialization\formatters\binary\binaryobjectwriter.cs \
system\runtime\serialization\formatters\binary\binaryconverter.cs \
system\runtime\serialization\formatters\binary\binaryobjectinfo.cs \
system\runtime\serialization\formatters\binary\binarymethodmessage.cs
CSC_SOURCES = \
$(RUNTIME_SOURCES) \
$(THREADING_SOURCES) \
$(COLLECTIONS_SOURCES) \
$(DIAGNOSTICS_SOURCES) \
$(DIAGNOSTICS_SYMBOLSTORE_SOURCES) \
$(REFLECTION_SOURCES) \
$(SERIALIZATION_SOURCES) \
$(GLOBALIZATION_SOURCES) \
$(TEXT_SOURCES) \
$(RESOURCES_SOURCES) \
$(WIN32_SOURCES) \
$(SEC_UTIL_SOURCES) \
$(SECURITY_POLICY_SOURCES) \
$(SECURITY_PRINCIPAL_SOURCES) \
$(STREAM_SOURCES) \
$(COMPILERSERVICES_SOURCES) \
$(INTEROP_SOURCES) \
$(INTEROP_EXPANDO_SOURCES) \
$(IO_SOURCES) \
$(COMPILER_SERVICES_SOURCES) \
$(COMPILER_SERVICES_CSHARP_SOURCES) \
$(SECURITY_SOURCES_PRE) \
$(XML_SOURCES) \
$(PERMISSIONS_SOURCES) \
$(SECURITY_SOURCES) \
$(REMOTING_SOURCES) \
$(ISOSTORE_SOURCES) \
$(SERIALIZATION_FORMATTERS_SOURCES) \
$(SERIALIZATION_FORMATTERS_BINARY_SOURCES) \
$(REFLECTION_EMIT_SOURCES) \
$(REFLECTION_CACHE_SOURCES) \
$(CONFIGURATION_ASSEMBLIES_SOURCES) \
+161
View File
@@ -0,0 +1,161 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
// __Filters.cs
//
// This class defines the delegate methods for the COM+ implemented filters.
//
// Date: July 98
//
namespace System {
using System;
using System.Reflection;
using System.Globalization;
[Serializable()]
internal class __Filters {
// Filters...
// The following are the built in filters defined for this class. These
// should really be defined as static methods. They are used in as delegates
// which currently doesn't support static methods. We will change this
// once the compiler supports delegates.
// FilterAttribute
// This method will search for a member based upon the attribute passed in.
// filterCriteria -- an Int32 representing the attribute
internal virtual bool FilterAttribute(MemberInfo m,Object filterCriteria)
{
// Check that the criteria object is an Integer object
if (filterCriteria == null)
throw new InvalidFilterCriteriaException(Environment.GetResourceString("RFLCT.FltCritInt"));
switch (m.MemberType)
{
case MemberTypes.Constructor:
case MemberTypes.Method: {
MethodAttributes criteria = 0;
try {
int i = (int) filterCriteria;
criteria = (MethodAttributes) i;
}
catch (Exception) {
throw new InvalidFilterCriteriaException(Environment.GetResourceString("RFLCT.FltCritInt"));
}
MethodAttributes attr;
if (m.MemberType == MemberTypes.Method)
attr = ((MethodInfo) m).Attributes;
else
attr = ((ConstructorInfo) m).Attributes;
if (((criteria & MethodAttributes.MemberAccessMask) != 0) && (attr & MethodAttributes.MemberAccessMask) != (criteria & MethodAttributes.MemberAccessMask))
return false;
if (((criteria & MethodAttributes.Static) != 0) && (attr & MethodAttributes.Static) == 0)
return false;
if (((criteria & MethodAttributes.Final) != 0) && (attr & MethodAttributes.Final) == 0)
return false;
if (((criteria & MethodAttributes.Virtual) != 0) && (attr & MethodAttributes.Virtual) == 0)
return false;
if (((criteria & MethodAttributes.Abstract) != 0) && (attr & MethodAttributes.Abstract) == 0)
return false;
if (((criteria & MethodAttributes.SpecialName) != 0) && (attr & MethodAttributes.SpecialName) == 0)
return false;
return true;
}
case MemberTypes.Field:
{
FieldAttributes criteria = 0;
try {
int i = (int) filterCriteria;
criteria = (FieldAttributes) i;
}
catch (Exception) {
throw new InvalidFilterCriteriaException(Environment.GetResourceString("RFLCT.FltCritInt"));
}
FieldAttributes attr = ((FieldInfo) m).Attributes;
if (((criteria & FieldAttributes.FieldAccessMask) != 0) && (attr & FieldAttributes.FieldAccessMask) != (criteria & FieldAttributes.FieldAccessMask))
return false;
if (((criteria & FieldAttributes.Static) != 0) && (attr & FieldAttributes.Static) == 0)
return false;
if (((criteria & FieldAttributes.InitOnly) != 0) && (attr & FieldAttributes.InitOnly) == 0)
return false;
if (((criteria & FieldAttributes.Literal) != 0) && (attr & FieldAttributes.Literal) == 0)
return false;
if (((criteria & FieldAttributes.NotSerialized) != 0) && (attr & FieldAttributes.NotSerialized) == 0)
return false;
if (((criteria & FieldAttributes.PinvokeImpl) != 0) && (attr & FieldAttributes.PinvokeImpl) == 0)
return false;
return true;
}
}
return false;
}
// FilterName
// This method will filter based upon the name. A partial wildcard
// at the end of the string is supported.
// filterCriteria -- This is the string name
internal virtual bool FilterName(MemberInfo m,Object filterCriteria)
{
// Check that the criteria object is a String object
if(filterCriteria == null || !(filterCriteria is String))
throw new InvalidFilterCriteriaException(Environment.GetResourceString("RFLCT.FltCritString"));
// At the moment this fails if its done on a single line....
String str = ((String) filterCriteria);
str = str.Trim();
String name = m.Name;
// hack to skip the get the nested class name only, as opposed to the mangled one
if (m.MemberType == MemberTypes.NestedType)
name = name.Substring(name.LastIndexOf('+') + 1);
// Check to see if this is a prefix or exact match requirement
if (str.Length > 0 && str[str.Length - 1] == '*') {
str = str.Substring(0, str.Length - 1);
return (name.StartsWith(str));
}
return (name.Equals(str));
}
// FilterIgnoreCase
// This delegate will do a name search but does it with the
// ignore case specified.
internal virtual bool FilterIgnoreCase(MemberInfo m,Object filterCriteria)
{
// Check that the criteria object is a String object
if(filterCriteria == null || !(filterCriteria is String))
throw new InvalidFilterCriteriaException(Environment.GetResourceString("RFLCT.FltCritString"));
String str = (String) filterCriteria;
str = str.Trim();
String name = m.Name;
// hack to skip the get the nested class name only, as opposed to the mangled one
if (m.MemberType == MemberTypes.NestedType)
name = name.Substring(name.LastIndexOf('+') + 1);
// Check to see if this is a prefix or exact match requirement
if (str.Length > 0 && str[str.Length - 1] == '*') {
str = str.Substring(0, str.Length - 1);
return (String.Compare(name,0,str,0,str.Length,true,CultureInfo.InvariantCulture)==0);
}
return (String.Compare(str,name, true, CultureInfo.InvariantCulture) == 0);
}
}
}
+116
View File
@@ -0,0 +1,116 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
//=============================================================================
//
// Class: __HResults
//
// Purpose: Define HResult constants. Every exception has one of these.
//
// Date: 98/08/31 11:57:11 AM
//
//===========================================================================*/
namespace System {
// Note: FACILITY_URT is defined as 0x13 (0x8013xxxx). Within that
// range, 0x1yyy is for Runtime errors (used for Security, Metadata, etc).
// In that subrange, 0x15zz and 0x16zz have been allocated for classlib-type
// HResults. Also note that some of our HResults have to map to certain
// COM HR's, etc.
// Another arbitrary decision... Feel free to change this, as long as you
// renumber the HResults yourself (and update rexcep.h).
// Reflection will use 0x1600 -> 0x1620. IO will use 0x1620 -> 0x1640.
// Security will use 0x1640 -> 0x1660
// There are __HResults files in the IO, Remoting, Reflection &
// Security/Util directories as well, so choose your HResults carefully.
using System;
internal sealed class __HResults
{
public const int E_FAIL = unchecked((int)0x80004005);
public const int E_POINTER = unchecked((int)0x80004003);
public const int E_NOTIMPL = unchecked((int)0x80004001);
public const int COR_E_AMBIGUOUSMATCH = unchecked((int)0x8000211D);
public const int COR_E_APPDOMAINUNLOADED = unchecked((int)0x80131014);
public const int COR_E_APPLICATION = unchecked((int)0x80131600);
public const int COR_E_ARGUMENT = unchecked((int)0x80070057);
public const int COR_E_ARGUMENTOUTOFRANGE = unchecked((int)0x80131502);
public const int COR_E_ARITHMETIC = unchecked((int)0x80070216);
public const int COR_E_ARRAYTYPEMISMATCH = unchecked((int)0x80131503);
public const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000B);
public const int COR_E_TYPEUNLOADED = unchecked((int)0x80131013);
public const int COR_E_CANNOTUNLOADAPPDOMAIN = unchecked((int)0x80131015);
public const int COR_E_COMEMULATE = unchecked((int)0x80131535);
public const int COR_E_CONTEXTMARSHAL = unchecked((int)0x80131504);
public const int COR_E_CUSTOMATTRIBUTEFORMAT = unchecked((int)0x80131605);
public const int COR_E_DIVIDEBYZERO = unchecked((int)0x80020012); // DISP_E_DIVBYZERO
public const int COR_E_DUPLICATEWAITOBJECT = unchecked((int)0x80131529);
public const int COR_E_EXCEPTION = unchecked((int)0x80131500);
public const int COR_E_EXECUTIONENGINE = unchecked((int)0x80131506);
public const int COR_E_FIELDACCESS = unchecked((int)0x80131507);
public const int COR_E_FORMAT = unchecked((int)0x80131537);
public const int COR_E_INDEXOUTOFRANGE = unchecked((int)0x80131508);
public const int COR_E_INVALIDCAST = unchecked((int)0x80004002);
public const int COR_E_INVALIDCOMOBJECT = unchecked((int)0x80131527);
public const int COR_E_INVALIDFILTERCRITERIA = unchecked((int)0x80131601);
public const int COR_E_INVALIDOLEVARIANTTYPE = unchecked((int)0x80131531);
public const int COR_E_INVALIDOPERATION = unchecked((int)0x80131509);
public const int COR_E_INVALIDPROGRAM = unchecked((int)0x8013153A);
public const int COR_E_MARSHALDIRECTIVE = unchecked((int)0x80131535);
public const int COR_E_MEMBERACCESS = unchecked((int)0x8013151A);
public const int COR_E_METHODACCESS = unchecked((int)0x80131510);
public const int COR_E_MISSINGFIELD = unchecked((int)0x80131511);
public const int COR_E_MISSINGMANIFESTRESOURCE = unchecked((int)0x80131532);
public const int COR_E_MISSINGMEMBER = unchecked((int)0x80131512);
public const int COR_E_MISSINGMETHOD = unchecked((int)0x80131513);
public const int COR_E_MULTICASTNOTSUPPORTED = unchecked((int)0x80131514);
public const int COR_E_NOTFINITENUMBER = unchecked((int)0x80131528);
public const int COR_E_PLATFORMNOTSUPPORTED = unchecked((int)0x80131539);
public const int COR_E_NOTSUPPORTED = unchecked((int)0x80131515);
public const int COR_E_NULLREFERENCE = unchecked((int)0x80004003);
public const int COR_E_OUTOFMEMORY = unchecked((int)0x8007000E);
public const int COR_E_OVERFLOW = unchecked((int)0x80131516);
public const int COR_E_RANK = unchecked((int)0x80131517);
public const int COR_E_REFLECTIONTYPELOAD = unchecked((int)0x80131602);
public const int COR_E_SAFEARRAYRANKMISMATCH = unchecked((int)0x80131538);
public const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked((int)0x80131533);
public const int COR_E_SECURITY = unchecked((int)0x8013150A);
public const int COR_E_SERIALIZATION = unchecked((int)0x8013150C);
public const int COR_E_STACKOVERFLOW = unchecked((int)0x800703E9);
public const int COR_E_SYNCHRONIZATIONLOCK = unchecked((int)0x80131518);
public const int COR_E_SYSTEM = unchecked((int)0x80131501);
public const int COR_E_TARGET = unchecked((int)0x80131603);
public const int COR_E_TARGETINVOCATION = unchecked((int)0x80131604);
public const int COR_E_TARGETPARAMCOUNT = unchecked((int)0x8002000e);
public const int COR_E_THREADABORTED = unchecked((int)0x80131530);
public const int COR_E_THREADINTERRUPTED = unchecked((int)0x80131519);
public const int COR_E_THREADSTATE = unchecked((int)0x80131520);
public const int COR_E_THREADSTOP = unchecked((int)0x80131521);
public const int COR_E_TYPEINITIALIZATION = unchecked((int)0x80131534);
public const int COR_E_TYPELOAD = unchecked((int)0x80131522);
public const int COR_E_ENTRYPOINTNOTFOUND = unchecked((int)0x80131523);
public const int COR_E_DLLNOTFOUND = unchecked((int)0x80131524);
public const int COR_E_UNAUTHORIZEDACCESS = unchecked((int)0x80070005);
public const int COR_E_UNSUPPORTEDFORMAT = unchecked((int)0x80131523);
public const int COR_E_VERIFICATION = unchecked((int)0x8013150D);
public const int CORSEC_E_MIN_GRANT_FAIL = unchecked((int)0x80131417);
public const int CORSEC_E_NO_EXEC_PERM = unchecked((int)0x80131418);
public const int CORSEC_E_POLICY_EXCEPTION = unchecked((int)0x80131416);
public const int CORSEC_E_XMLSYNTAX = unchecked((int)0x80131418);
public const int NTE_FAIL = unchecked((int)0x80090020);
public const int CORSEC_E_CRYPTO = unchecked((int)0x80131430);
public const int CORSEC_E_CRYPTO_UNEX_OPER = unchecked((int)0x80131431);
}
}
+143
View File
@@ -0,0 +1,143 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: LocalDataStore
**
**
**
** Purpose: Class that stores local data. This class is used in cooperation
** with the _LocalDataStoreMgr class.
**
** Date: March 25, 1999
**
=============================================================================*/
namespace System {
using System;
// This class will not be marked serializable
internal class LocalDataStore
{
/*=========================================================================
** DON'T CHANGE THESE UNLESS YOU MODIFY LocalDataStoreBaseObject in vm\object.h
=========================================================================*/
private Object[] m_DataTable;
private LocalDataStoreMgr m_Manager;
private int DONT_USE_InternalStore = 0; // pointer
/*=========================================================================
** Initialize the data store.
=========================================================================*/
public LocalDataStore(LocalDataStoreMgr mgr, int InitialCapacity)
{
if (null == mgr)
throw new ArgumentNullException("mgr");
// Store the manager of the local data store.
m_Manager = mgr;
// Allocate the array that will contain the data.
m_DataTable = new Object[InitialCapacity];
}
/*=========================================================================
** Retrieves the value from the specified slot.
=========================================================================*/
public Object GetData(LocalDataStoreSlot slot)
{
Object o = null;
// Validate the slot.
m_Manager.ValidateSlot(slot);
// Cache the slot index to avoid synchronization issues.
int slotIdx = slot.Slot;
if (slotIdx >= 0)
{
// Delay expansion of m_DataTable if we can
if (slotIdx >= m_DataTable.Length)
return null;
// Retrieve the data from the given slot.
o = m_DataTable[slotIdx];
}
// Check if the slot has become invalid.
if (!slot.IsValid())
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SlotHasBeenFreed"));
return o;
}
/*=========================================================================
** Sets the data in the specified slot.
=========================================================================*/
public void SetData(LocalDataStoreSlot slot, Object data)
{
// Validate the slot.
m_Manager.ValidateSlot(slot);
// I can't think of a way to avoid the race described in the
// LocalDataStoreSlot finalizer method without a lock.
lock (m_Manager)
{
if (!slot.IsValid())
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SlotHasBeenFreed"));
// Do the actual set operation.
SetDataInternal(slot.Slot, data, true /*bAlloc*/ );
}
}
/*=========================================================================
** This method does the actual work of setting the data.
=========================================================================*/
internal void SetDataInternal(int slot, Object data, bool bAlloc)
{
// We try to delay allocate the dataTable (in cases like the manager clearing a
// just-freed slot in all stores
if (slot >= m_DataTable.Length)
{
if (!bAlloc)
return;
SetCapacity(m_Manager.GetSlotTableLength());
}
// Set the data on the given slot.
m_DataTable[slot] = data;
}
/*=========================================================================
** Method used to set the capacity of the local data store.
=========================================================================*/
private void SetCapacity(int capacity)
{
// Validate that the specified capacity is larger than the current one.
if (capacity < m_DataTable.Length)
throw new ArgumentException(Environment.GetResourceString("Argument_ALSInvalidCapacity"));
// Allocate the new data table.
Object[] NewDataTable = new Object[capacity];
// Copy all the objects into the new table.
Array.Copy(m_DataTable, NewDataTable, m_DataTable.Length);
// Save the new table.
m_DataTable = NewDataTable;
}
}
}
+308
View File
@@ -0,0 +1,308 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: LocalDataStoreMgr
**
**
**
** Purpose: Class that manages stores of local data. This class is used in
** cooperation with the LocalDataStore class.
**
** Date: March 25, 1999
**
=============================================================================*/
namespace System {
using System;
using System.Collections;
// This is a cheesy internal helper class that is used to make sure memory
// is actually being accessed and not some cached copy of a field in a
// register.
// WARNING: If we every do type analysis to eliminate virtual functions,
// this will break.
// This class will not be marked serializable
internal class LdsSyncHelper
{
internal virtual int Get(ref int slot)
{
return slot;
}
}
// This class is an encapsulation of a slot so that it is managed in a secure fashion.
// It is constructed by the LocalDataStoreManager, holds the slot and the manager
// and cleans up when it is finalized.
// This class will not be marked serializable
/// <include file='doc\_LocalDataStoreMgr.uex' path='docs/doc[@for="LocalDataStoreSlot"]/*' />
public sealed class LocalDataStoreSlot
{
private static LdsSyncHelper m_helper = new LdsSyncHelper();
private LocalDataStoreMgr m_mgr;
private int m_slot;
// Construct the object to encapsulate the slot.
internal LocalDataStoreSlot(LocalDataStoreMgr mgr, int slot)
{
m_mgr = mgr;
m_slot = slot;
}
// Accessors for the two fields of this class.
internal LocalDataStoreMgr Manager
{
get
{
return m_mgr;
}
}
internal int Slot
{
get
{
return m_slot;
}
}
// This is used to make sure we are actually reading and writing to
// memory to fetch the slot (rather than possibly using a value
// cached in a register).
internal bool IsValid()
{
return m_helper.Get(ref m_slot) != -1;
}
// Release the slot reserved by this object when this object goes away.
// There is a race condition that can happen in the face of
// resurrection where another thread is fetching values or assigning
// while the finalizer thread is here. We are counting on the fact
// that code that fetches values calls IsValid after fetching a value
// and before giving it to anyone. See LocalDataStore for the other
// half of this. We are also counting on code that sets values locks
// the manager.
/// <include file='doc\_LocalDataStoreMgr.uex' path='docs/doc[@for="LocalDataStoreSlot.Finalize"]/*' />
~LocalDataStoreSlot()
{
int slot = m_slot;
// This lock fixes synchronization with the assignment of values.
lock (m_mgr)
{
// Mark the slot as free.
m_slot = -1;
m_mgr.FreeDataSlot(slot);
}
}
}
// This class will not be marked serializable
internal class LocalDataStoreMgr
{
private const byte DataSlotOccupied = 0x01;
private const int InitialSlotTableSize = 64;
private const int SlotTableDoubleThreshold = 512;
private const int LargeSlotTableSizeIncrease = 128;
/*=========================================================================
** Create a data store to be managed by this manager and add it to the
** list. The initial size of the new store matches the number of slots
** allocated in this manager.
=========================================================================*/
public LocalDataStore CreateLocalDataStore()
{
// Create a new local data store.
LocalDataStore Store = new LocalDataStore(this, m_SlotInfoTable.Length);
lock(this) {
// Add the store to the array list and return it.
m_ManagedLocalDataStores.Add(Store);
}
return Store;
}
/*=========================================================================
* Remove the specified store from the list of managed stores..
=========================================================================*/
public void DeleteLocalDataStore(LocalDataStore store)
{
lock(this) {
// Remove the store to the array list and return it.
m_ManagedLocalDataStores.Remove(store);
}
}
/*=========================================================================
** Allocates a data slot by finding an available index and wrapping it
** an object to prevent clients from manipulating it directly, allowing us
** to make assumptions its integrity.
=========================================================================*/
public LocalDataStoreSlot AllocateDataSlot()
{
lock(this) {
int i;
LocalDataStoreSlot slot;
// Retrieve the current size of the table.
int SlotTableSize = m_SlotInfoTable.Length;
// Check if there are any slots left.
if (m_FirstAvailableSlot < SlotTableSize)
{
// Save the first available slot.
slot = new LocalDataStoreSlot(this, m_FirstAvailableSlot);
m_SlotInfoTable[m_FirstAvailableSlot] = DataSlotOccupied;
// Find the next available slot.
for (i=m_FirstAvailableSlot+1; i < SlotTableSize; ++i)
if (0 == (m_SlotInfoTable[i] & DataSlotOccupied))
break;
// Save the new "first available slot".
m_FirstAvailableSlot = i;
// Return the slot index.
return slot;
}
// The table is full so we need to increase its size.
int NewSlotTableSize;
if (SlotTableSize < SlotTableDoubleThreshold)
{
// The table is still relatively small so double it.
NewSlotTableSize = SlotTableSize * 2;
}
else
{
// The table is relatively large so simply increase its size by a given amount.
NewSlotTableSize = SlotTableSize + LargeSlotTableSizeIncrease;
}
// Allocate the new slot info table.
byte[] NewSlotInfoTable = new byte[NewSlotTableSize];
// Copy the old array into the new one.
Array.Copy(m_SlotInfoTable, NewSlotInfoTable, SlotTableSize);
m_SlotInfoTable = NewSlotInfoTable;
// SlotTableSize is the index of the first empty slot in the expanded table.
slot = new LocalDataStoreSlot(this, SlotTableSize);
m_SlotInfoTable[SlotTableSize] = DataSlotOccupied;
m_FirstAvailableSlot = SlotTableSize + 1;
// Return the selected slot
return slot;
}
}
/*=========================================================================
** Allocate a slot and associate a name with it.
=========================================================================*/
public LocalDataStoreSlot AllocateNamedDataSlot(String name)
{
lock(this)
{
// Allocate a normal data slot.
LocalDataStoreSlot slot = AllocateDataSlot();
// Insert the association between the name and the data slot number
// in the hash table.
m_KeyToSlotMap.Add(name, slot);
return slot;
}
}
/*=========================================================================
** Retrieve the slot associated with a name, allocating it if no such
** association has been defined.
=========================================================================*/
public LocalDataStoreSlot GetNamedDataSlot(String name)
{
lock(this)
{
// Lookup in the hashtable to try find a slot for the name.
LocalDataStoreSlot slot = (LocalDataStoreSlot) m_KeyToSlotMap[name];
// If the name is not yet in the hashtable then add it.
if (null == slot)
return AllocateNamedDataSlot(name);
// The name was in the hashtable so return the associated slot.
return slot;
}
}
/*=========================================================================
** Eliminate the association of a name with a slot. The actual slot will
** be reclaimed when the finalizer for the slot object runs.
=========================================================================*/
public void FreeNamedDataSlot(String name)
{
lock(this)
{
// Remove the name slot association from the hashtable.
m_KeyToSlotMap.Remove(name);
}
}
/*=========================================================================
** Free's a previously allocated data slot on ALL the managed data stores.
=========================================================================*/
internal void FreeDataSlot(int slot)
{
lock(this) {
// Go thru all the managed stores and set the data on the specified slot to 0.
for (int i=0; i < m_ManagedLocalDataStores.Count; i++)
{
((LocalDataStore)m_ManagedLocalDataStores[i]).SetDataInternal(
slot,
null,
false);
}
// Mark the slot as being no longer occupied.
m_SlotInfoTable[slot] = 0;
if (slot < m_FirstAvailableSlot)
m_FirstAvailableSlot = slot;
}
}
/*=========================================================================
** Return the number of allocated slots in this manager.
=========================================================================*/
public void ValidateSlot(LocalDataStoreSlot slot)
{
// Make sure the slot was allocated for this store.
if (slot==null || slot.Manager != this)
throw new ArgumentException(Environment.GetResourceString("Argument_ALSInvalidSlot"));
}
/*=========================================================================
** Return the number of allocated slots in this manager.
=========================================================================*/
internal int GetSlotTableLength()
{
return m_SlotInfoTable.Length;
}
private byte[] m_SlotInfoTable = new byte[InitialSlotTableSize];
private int m_FirstAvailableSlot = 0;
private ArrayList m_ManagedLocalDataStores = new ArrayList();
private Hashtable m_KeyToSlotMap = new Hashtable();
}
}
+61
View File
@@ -0,0 +1,61 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
////////////////////////////////////////////////////////////////////////////////
// AccessException
// Thrown when we try accessing a member that we cannot
// access, due to it being removed, private or something similar.
////////////////////////////////////////////////////////////////////////////////
namespace System {
using System;
using System.Runtime.Serialization;
// The AccessException is thrown when trying to access a class
// member fails.
//
/// <include file='doc\AccessException.uex' path='docs/doc[@for="AccessException"]/*' />
[Serializable()] public class AccessException : SystemException {
// Creates a new AccessException with its message string set to
// the empty string, its HRESULT set to COR_E_MEMBERACCESS,
// and its ExceptionInfo reference set to null.
/// <include file='doc\AccessException.uex' path='docs/doc[@for="AccessException.AccessException"]/*' />
public AccessException()
: base(Environment.GetResourceString("Arg_AccessException")) {
SetErrorCode(__HResults.COR_E_MEMBERACCESS);
}
// Creates a new AccessException with its message string set to
// message, its HRESULT set to COR_E_ACCESS,
// and its ExceptionInfo reference set to null.
//
/// <include file='doc\AccessException.uex' path='docs/doc[@for="AccessException.AccessException1"]/*' />
public AccessException(String message)
: base(message) {
SetErrorCode(__HResults.COR_E_MEMBERACCESS);
}
/// <include file='doc\AccessException.uex' path='docs/doc[@for="AccessException.AccessException2"]/*' />
public AccessException(String message, Exception inner)
: base(message, inner) {
SetErrorCode(__HResults.COR_E_MEMBERACCESS);
}
/// <include file='doc\AccessException.uex' path='docs/doc[@for="AccessException.AccessException3"]/*' />
protected AccessException(SerializationInfo info, StreamingContext context) : base(info, context) {
}
}
}
+325
View File
@@ -0,0 +1,325 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Activator is an object that contains the Activation (CreateInstance/New)
// methods for late bound support.
//
// Date: March 2000
//
namespace System {
using System;
using System.Reflection;
using System.Runtime.Remoting;
using Message = System.Runtime.Remoting.Messaging.Message;
using CultureInfo = System.Globalization.CultureInfo;
using Evidence = System.Security.Policy.Evidence;
using StackCrawlMark = System.Threading.StackCrawlMark;
using System.Runtime.InteropServices;
using System.Security.Permissions;
// Only statics, does not need to be marked with the serializable attribute
/// <include file='doc\Activator.uex' path='docs/doc[@for="Activator"]/*' />
public sealed class Activator {
internal const int LookupMask = 0x000000FF;
internal const BindingFlags ConLookup = (BindingFlags) (BindingFlags.Instance | BindingFlags.Public);
internal const BindingFlags ConstructorDefault= BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance;
// This class only contains statics, so hide the worthless constructor
private Activator()
{
}
// CreateInstance
// The following methods will create a new instance of an Object
// Full Binding Support
// For all of these methods we need to get the underlying RuntimeType and
// call the Impl version.
/// <include file='doc\Activator.uex' path='docs/doc[@for="Activator.CreateInstance"]/*' />
static public Object CreateInstance(Type type,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture)
{
return CreateInstance(type, bindingAttr, binder, args, culture, null);
}
/// <include file='doc\Activator.uex' path='docs/doc[@for="Activator.CreateInstance1"]/*' />
static public Object CreateInstance(Type type,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes)
{
if (type == null)
throw new ArgumentNullException("type");
if (type is System.Reflection.Emit.TypeBuilder)
throw new NotSupportedException(Environment.GetResourceString( "NotSupported_CreateInstanceWithTypeBuilder" ));
// If they didn't specify a lookup, then we will provide the default lookup.
if ((bindingAttr & (BindingFlags) LookupMask) == 0)
bindingAttr |= Activator.ConstructorDefault;
try {
RuntimeType rt = (RuntimeType) type.UnderlyingSystemType;
return rt.CreateInstanceImpl(bindingAttr,binder,args,culture,activationAttributes);
}
catch (InvalidCastException) {
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"type");
}
}
/// <include file='doc\Activator.uex' path='docs/doc[@for="Activator.CreateInstance2"]/*' />
static public Object CreateInstance(Type type, Object[] args)
{
return CreateInstance(type,
Activator.ConstructorDefault,
null,
args,
null,
null);
}
/// <include file='doc\Activator.uex' path='docs/doc[@for="Activator.CreateInstance3"]/*' />
static public Object CreateInstance(Type type,
Object[] args,
Object[] activationAttributes)
{
return CreateInstance(type,
Activator.ConstructorDefault,
null,
args,
null,
activationAttributes);
}
/// <include file='doc\Activator.uex' path='docs/doc[@for="Activator.CreateInstance4"]/*' />
static public Object CreateInstance(Type type)
{
return Activator.CreateInstance(type, false);
}
/*
* Create an instance using the name of type and the assembly where it exists. This allows
* types to be created remotely without having to load the type locally.
*/
/// <include file='doc\Activator.uex' path='docs/doc[@for="Activator.CreateInstance5"]/*' />
static public ObjectHandle CreateInstance(String assemblyName,
String typeName)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return CreateInstance(assemblyName,
typeName,
false,
Activator.ConstructorDefault,
null,
null,
null,
null,
null,
ref stackMark);
}
/// <include file='doc\Activator.uex' path='docs/doc[@for="Activator.CreateInstance6"]/*' />
static public ObjectHandle CreateInstance(String assemblyName,
String typeName,
Object[] activationAttributes)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return CreateInstance(assemblyName,
typeName,
false,
Activator.ConstructorDefault,
null,
null,
null,
activationAttributes,
null,
ref stackMark);
}
/// <include file='doc\Activator.uex' path='docs/doc[@for="Activator.CreateInstance8"]/*' />
static public Object CreateInstance(Type type, bool nonPublic)
{
if (type == null)
throw new ArgumentNullException("type");
try {
RuntimeType rt = (RuntimeType) type.UnderlyingSystemType;
return rt.CreateInstanceImpl(!nonPublic);
}
catch (InvalidCastException) {
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"type");
}
}
/// <include file='doc\Activator.uex' path='docs/doc[@for="Activator.CreateInstanceFrom"]/*' />
static public ObjectHandle CreateInstanceFrom(String assemblyFile,
String typeName)
{
return CreateInstanceFrom(assemblyFile, typeName, null);
}
/// <include file='doc\Activator.uex' path='docs/doc[@for="Activator.CreateInstanceFrom1"]/*' />
static public ObjectHandle CreateInstanceFrom(String assemblyFile,
String typeName,
Object[] activationAttributes)
{
return CreateInstanceFrom(assemblyFile,
typeName,
false,
Activator.ConstructorDefault,
null,
null,
null,
activationAttributes,
null);
}
/// <include file='doc\Activator.uex' path='docs/doc[@for="Activator.CreateInstance7"]/*' />
static public ObjectHandle CreateInstance(String assemblyName,
String typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityInfo)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return CreateInstance(assemblyName,
typeName,
ignoreCase,
bindingAttr,
binder,
args,
culture,
activationAttributes,
securityInfo,
ref stackMark);
}
static internal ObjectHandle CreateInstance(String assemblyName,
String typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityInfo,
ref StackCrawlMark stackMark)
{
Assembly assembly;
if(assemblyName == null)
assembly = Assembly.nGetExecutingAssembly(ref stackMark);
else
assembly = Assembly.InternalLoad(assemblyName, securityInfo, ref stackMark);
Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyName);
if(assembly == null) return null;
Type t = assembly.GetTypeInternal(typeName, true, ignoreCase, false);
Object o = Activator.CreateInstance(t,
bindingAttr,
binder,
args,
culture,
activationAttributes);
Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
if(o == null)
return null;
else {
ObjectHandle Handle = new ObjectHandle(o);
return Handle;
}
}
/// <include file='doc\Activator.uex' path='docs/doc[@for="Activator.CreateInstanceFrom2"]/*' />
static public ObjectHandle CreateInstanceFrom(String assemblyFile,
String typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityInfo)
{
Assembly assembly = Assembly.LoadFrom(assemblyFile, securityInfo);
Type t = assembly.GetTypeInternal(typeName, true, ignoreCase, false);
Object o = Activator.CreateInstance(t,
bindingAttr,
binder,
args,
culture,
activationAttributes);
Log(o != null, "CreateInstanceFrom:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
if(o == null)
return null;
else {
ObjectHandle Handle = new ObjectHandle(o);
return Handle;
}
}
// This method is a helper method and delegates to the remoting
// services to do the actual work.
/// <include file='doc\Activator.uex' path='docs/doc[@for="Activator.GetObject"]/*' />
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.RemotingConfiguration)]
static public Object GetObject(Type type, String url)
{
return GetObject(type, url, null);
}
// This method is a helper method and delegates to the remoting
// services to do the actual work.
/// <include file='doc\Activator.uex' path='docs/doc[@for="Activator.GetObject1"]/*' />
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.RemotingConfiguration)]
static public Object GetObject(Type type, String url, Object state)
{
if (type == null)
throw new ArgumentNullException("type");
return RemotingServices.Connect(type, url, state);
}
[System.Diagnostics.Conditional("_DEBUG")]
private static void Log(bool test, string title, string success, string failure)
{
if(test)
Message.DebugOut(title+success+"\n");
else
Message.DebugOut(title+failure+"\n");
}
}
}
File diff suppressed because it is too large Load Diff
+64
View File
@@ -0,0 +1,64 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** File: AppDomainAttributes
**
** Author:
**
** Purpose: For AppDomain-related custom attributes.
**
** Date: July, 2000
**
=============================================================================*/
namespace System {
/// <include file='doc\AppDomainAttributes.uex' path='docs/doc[@for="LoaderOptimization"]/*' />
[Serializable()]
public enum LoaderOptimization
{
/// <include file='doc\AppDomainAttributes.uex' path='docs/doc[@for="LoaderOptimization.NotSpecified"]/*' />
NotSpecified = 0,
/// <include file='doc\AppDomainAttributes.uex' path='docs/doc[@for="LoaderOptimization.SingleDomain"]/*' />
SingleDomain = 1,
/// <include file='doc\AppDomainAttributes.uex' path='docs/doc[@for="LoaderOptimization.MultiDomain"]/*' />
MultiDomain = 2,
/// <include file='doc\AppDomainAttributes.uex' path='docs/doc[@for="LoaderOptimization.MultiDomainHost"]/*' />
MultiDomainHost = 3,
}
/// <include file='doc\AppDomainAttributes.uex' path='docs/doc[@for="LoaderOptimizationAttribute"]/*' />
[AttributeUsage (AttributeTargets.Method)]
public sealed class LoaderOptimizationAttribute : Attribute
{
internal byte _val;
/// <include file='doc\AppDomainAttributes.uex' path='docs/doc[@for="LoaderOptimizationAttribute.LoaderOptimizationAttribute"]/*' />
public LoaderOptimizationAttribute(byte value)
{
_val = value;
}
/// <include file='doc\AppDomainAttributes.uex' path='docs/doc[@for="LoaderOptimizationAttribute.LoaderOptimizationAttribute1"]/*' />
public LoaderOptimizationAttribute(LoaderOptimization value)
{
_val = (byte) value;
}
/// <include file='doc\AppDomainAttributes.uex' path='docs/doc[@for="LoaderOptimizationAttribute.Value"]/*' />
public LoaderOptimization Value
{ get {return (LoaderOptimization) _val;} }
}
}
+767
View File
@@ -0,0 +1,767 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: LoaderFlags
**
** Purpose: Defines the settings that the loader uses to find assemblies in an
** AppDomain
**
** Date: Dec 22, 2000
**
=============================================================================*/
namespace System {
using System;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Globalization;
using Path = System.IO.Path;
// Only statics, does not need to be marked with the serializable attribute
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup"]/*' />
[Serializable]
public sealed class AppDomainSetup : IAppDomainSetup
{
[Serializable]
internal enum LoaderInformation
{
ApplicationBaseValue = LOADER_APPLICATION_BASE,
ConfigurationFileValue = LOADER_CONFIGURATION_BASE,
DynamicBaseValue = LOADER_DYNAMIC_BASE,
DevPathValue = LOADER_DEVPATH,
ApplicationNameValue = LOADER_APPLICATION_NAME,
PrivateBinPathValue = LOADER_PRIVATE_PATH,
PrivateBinPathProbeValue = LOADER_PRIVATE_BIN_PATH_PROBE,
ShadowCopyDirectoriesValue = LOADER_SHADOW_COPY_DIRECTORIES,
ShadowCopyFilesValue = LOADER_SHADOW_COPY_FILES,
CachePathValue = LOADER_CACHE_PATH,
LicenseFileValue = LOADER_LICENSE_FILE,
DisallowPublisherPolicyValue=LOADER_DISALLOW_PUBLISHER_POLICY,
LoaderMaximum = LOADER_MAXIMUM,
}
private string[] _Entries;
private LoaderOptimization _LoaderOptimization;
private String _AppBase;
internal AppDomainSetup(AppDomainSetup copy)
{
string[] mine = Value;
if(copy != null) {
string[] other = copy.Value;
int size = _Entries.Length;
for(int i = 0; i < size; i++)
mine[i] = other[i];
_LoaderOptimization = copy._LoaderOptimization;
}
else
_LoaderOptimization = LoaderOptimization.NotSpecified;
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.AppDomainSetup"]/*' />
public AppDomainSetup()
{
_LoaderOptimization = LoaderOptimization.NotSpecified;
}
internal string[] Value
{
get {
if( _Entries == null)
_Entries = new String[LOADER_MAXIMUM];
return _Entries;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.ApplicationBase"]/*' />
public String ApplicationBase
{
get {
if (_AppBase == null) {
String appbase = Value[(int) LoaderInformation.ApplicationBaseValue];
if (appbase != null)
_AppBase = NormalizePath(appbase, false);
}
if ((_AppBase != null) && IsFilePath(_AppBase))
new FileIOPermission( FileIOPermissionAccess.PathDiscovery, _AppBase ).Demand();
return _AppBase;
}
set {
Value[(int) LoaderInformation.ApplicationBaseValue] = value;
}
}
private String NormalizePath(String path, bool useAppBase)
{
int len = path.Length;
if ((len > 7) &&
(String.Compare( path, 0, "file:", 0, 5, true, CultureInfo.InvariantCulture ) == 0)) {
// Don't allow "file:\\", because we can't tell the difference
// with it for "file:\\" + "\\server" and "file:\\\" + "\localpath"
if (path[5] == '\\')
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars"));
int trim;
if (path[7] == '/')
trim = 8;
else
trim = 7;
path = path.Substring(trim);
}
#if !PLATFORM_UNIX
if (path.IndexOf(':') == -1) {
#else
if ( (path.Length >= 1) && ( (path[0] == '/') || (path[0] == '\\') ) ) {
#endif // !PLATFORM_UNIX
if (useAppBase) {
String appBase = Value[(int) LoaderInformation.ApplicationBaseValue];
if ((appBase == null) || (appBase.Length == 0))
throw new MemberAccessException(Environment.GetResourceString("AppDomain_AppBaseNotSet"));
if (_AppBase == null)
_AppBase = NormalizePath(appBase, false);
StringBuilder result = new StringBuilder();
result.Append(_AppBase);
int aLen = _AppBase.Length;
if (!( (_AppBase[aLen-1] == '/') ||
(_AppBase[aLen-1] == '\\') )) {
#if !PLATFORM_UNIX
if ((aLen > 7) &&
(String.Compare(_AppBase, 0, "http:", 0, 5, true, CultureInfo.InvariantCulture) == 0))
result.Append('/');
else
result.Append('\\');
#else
result.Append('/');
#endif // !PLATFORM_UNIX
}
result.Append(path);
path = result.ToString();
}
else
path = Path.GetFullPathInternal(path);
}
return path;
}
private bool IsFilePath(String path)
{
#if !PLATFORM_UNIX
return (path[1] == ':') || ( (path[0] == '\\') && (path[1] == '\\') );
#else
return (path[0] == '/');
#endif // !PLATFORM_UNIX
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.ApplicationBaseKey"]/*' />
internal static String ApplicationBaseKey
{
get {
return ACTAG_APP_BASE_URL;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.ConfigurationFile"]/*' />
public String ConfigurationFile
{
get {
String config = Value[(int) LoaderInformation.ConfigurationFileValue];
if ((config != null) && (config.Length > 1)) {
config = NormalizePath(config, true);
if (IsFilePath(config))
new FileIOPermission( FileIOPermissionAccess.PathDiscovery, config ).Demand();
}
return config;
}
set {
Value[(int) LoaderInformation.ConfigurationFileValue] = value;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.ConfigurationFileKey"]/*' />
internal static String ConfigurationFileKey
{
get {
return ACTAG_APP_CONFIG_FILE;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.DynamicBase"]/*' />
public String DynamicBase
{
get {
String dynbase = Value[(int) LoaderInformation.DynamicBaseValue];
if ((dynbase != null) && (dynbase.Length > 1)) {
dynbase = NormalizePath(dynbase, true);
if (IsFilePath(dynbase))
new FileIOPermission( FileIOPermissionAccess.PathDiscovery, dynbase ).Demand();
}
return dynbase;
}
set {
if (value == null)
Value[(int) LoaderInformation.DynamicBaseValue] = null;
else {
if(ApplicationName == null)
throw new MemberAccessException(Environment.GetResourceString("AppDomain_RequireApplicationName"));
StringBuilder s = new StringBuilder(value);
s.Append('\\');
string h = ParseNumbers.IntToString(ApplicationName.GetHashCode(),
16, 8, '0', ParseNumbers.PrintAsI4);
s.Append(h);
Value[(int) LoaderInformation.DynamicBaseValue] = s.ToString();
}
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.DynamicBaseKey"]/*' />
internal static String DynamicBaseKey
{
get {
return ACTAG_APP_DYNAMIC_BASE;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.DisallowPublisherPolicy"]/*' />
public bool DisallowPublisherPolicy
{
get
{
return (Value[(int) LoaderInformation.DisallowPublisherPolicyValue] != null);
}
set
{
if (value)
Value[(int) LoaderInformation.DisallowPublisherPolicyValue]="true";
else
Value[(int) LoaderInformation.DisallowPublisherPolicyValue]=null;
}
}
internal String DeveloperPath
{
get {
return Value[(int) LoaderInformation.DevPathValue];
}
set {
if(value == null)
Value[(int) LoaderInformation.DevPathValue] = null;
else {
String[] directories = value.Split(';');
int size = directories.Length;
if(size > 0) {
StringBuilder newPath = new StringBuilder();
bool fDelimiter = false;
for(int i = 0; i < size; i++) {
if(directories[i].Length > 0) {
if(fDelimiter)
newPath.Append(";");
else
fDelimiter = true;
newPath.Append(Path.GetFullPathInternal(directories[i]));
}
}
Value[(int) LoaderInformation.DevPathValue] = newPath.ToString();
}
}
}
}
internal static String DisallowPublisherPolicyKey
{
get
{
return ACTAG_DISALLOW_APPLYPUBLISHERPOLICY;
}
}
internal static String DeveloperPathKey
{
get {
return ACTAG_DEV_PATH;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.ApplicationName"]/*' />
public String ApplicationName
{
get {
return Value[(int) LoaderInformation.ApplicationNameValue];
}
set {
Value[(int) LoaderInformation.ApplicationNameValue] = value;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.ApplicationNameKey"]/*' />
internal static String ApplicationNameKey
{
get {
return ACTAG_APP_NAME;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.PrivateBinPath"]/*' />
public String PrivateBinPath
{
get {
return Value[(int) LoaderInformation.PrivateBinPathValue];
}
set {
Value[(int) LoaderInformation.PrivateBinPathValue] = value;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.PrivateBinPathKey"]/*' />
internal static String PrivateBinPathKey
{
get {
return ACTAG_APP_PRIVATE_BINPATH;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.PrivateBinPathProbe"]/*' />
public String PrivateBinPathProbe
{
get {
return Value[(int) LoaderInformation.PrivateBinPathProbeValue];
}
set {
Value[(int) LoaderInformation.PrivateBinPathProbeValue] = value;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.PrivateBinPathProbeKey"]/*' />
internal static String PrivateBinPathProbeKey
{
get {
return ACTAG_BINPATH_PROBE_ONLY;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.ShadowCopyDirectories"]/*' />
public String ShadowCopyDirectories
{
get {
String dirs = Value[(int) LoaderInformation.ShadowCopyDirectoriesValue];
if (dirs != null) {
String[] dirArray = dirs.Split(';');
int len = dirArray.Length;
for (int i = 0; i < len; i++) {
if (dirArray[i].Length > 1) {
dirArray[i] = NormalizePath(dirArray[i], true);
if (IsFilePath(dirArray[i]))
new FileIOPermission( FileIOPermissionAccess.PathDiscovery, dirArray[i] ).Demand();
}
}
}
return dirs;
}
set {
if (value == null)
Value[(int) LoaderInformation.ShadowCopyDirectoriesValue] = null;
else {
String[] dirArray = value.Split(';');
int len = dirArray.Length;
StringBuilder newPath = new StringBuilder();
bool fDelimiter = false;
for(int i = 0; i < len; i++) {
if(dirArray[i].Length > 0) {
if(fDelimiter)
newPath.Append(";");
else
fDelimiter = true;
newPath.Append(dirArray[i]);
}
}
Value[(int) LoaderInformation.ShadowCopyDirectoriesValue] = newPath.ToString();
}
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.ShadowCopyDirectoriesKey"]/*' />
internal static String ShadowCopyDirectoriesKey
{
get {
return ACTAG_APP_SHADOW_COPY_DIRS;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.ShadowCopyFiles"]/*' />
public String ShadowCopyFiles
{
get {
return Value[(int) LoaderInformation.ShadowCopyFilesValue];
}
set {
Value[(int) LoaderInformation.ShadowCopyFilesValue] = value;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.ShadowCopyFilesKey"]/*' />
internal static String ShadowCopyFilesKey
{
get {
return ACTAG_FORCE_CACHE_INSTALL;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.CachePath"]/*' />
public String CachePath
{
get {
String dir = Value[(int) LoaderInformation.CachePathValue];
if ((dir != null) && (dir.Length > 1)) {
dir = NormalizePath(dir, true);
if (IsFilePath(dir))
new FileIOPermission( FileIOPermissionAccess.PathDiscovery, dir ).Demand();
}
return dir;
}
set {
Value[(int) LoaderInformation.CachePathValue] = value;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.CachePathKey"]/*' />
internal static String CachePathKey
{
get {
return ACTAG_APP_CACHE_BASE;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.LicenseFile"]/*' />
public String LicenseFile
{
get {
String dir = Value[(int) LoaderInformation.LicenseFileValue];
if ((dir != null) && (dir.Length > 1)) {
dir = NormalizePath(dir, true);
if (IsFilePath(dir))
new FileIOPermission( FileIOPermissionAccess.PathDiscovery, dir ).Demand();
}
return dir;
}
set {
Value[(int) LoaderInformation.LicenseFileValue] = value;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.LicenseFileKey"]/*' />
internal static String LicenseFileKey
{
get {
return LICENSE_FILE;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.LoaderOptimization"]/*' />
public LoaderOptimization LoaderOptimization
{
get {
return _LoaderOptimization;
}
set {
_LoaderOptimization = value;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.LoaderOptimizationKey"]/*' />
internal static string LoaderOptimizationKey
{
get {
return LOADER_OPTIMIZATION;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.DynamicDirectoryKey"]/*' />
internal static string DynamicDirectoryKey
{
get {
return DYNAMIC_DIRECTORY;
}
}
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.ConfigurationExtension"]/*' />
internal static string ConfigurationExtension
{
get {
return CONFIGURATION_EXTENSION;
}
}
internal static String PrivateBinPathEnvironmentVariable
{
get {
return APPENV_RELATIVEPATH;
}
}
internal static string RuntimeConfigurationFile
{
get {
return MACHINE_CONFIGURATION_FILE;
}
}
internal static string MachineConfigKey
{
get {
return ACTAG_MACHINE_CONFIG;
}
}
internal static string HostBindingKey
{
get {
return ACTAG_HOST_CONFIG_FILE;
}
}
internal void SetupFusionContext(IntPtr fusionContext)
{
String appbase = Value[(int) LoaderInformation.ApplicationBaseValue];
if(appbase != null)
UpdateContextProperty(fusionContext, ApplicationBaseKey, appbase);
if(PrivateBinPath != null)
UpdateContextProperty(fusionContext, PrivateBinPathKey, PrivateBinPath);
if(DeveloperPath != null)
UpdateContextProperty(fusionContext, DeveloperPathKey, DeveloperPath);
if (DisallowPublisherPolicy)
UpdateContextProperty(fusionContext, DisallowPublisherPolicyKey, "true");
if(ShadowCopyFiles != null) {
UpdateContextProperty(fusionContext, ShadowCopyFilesKey, ShadowCopyFiles);
// If we are asking for shadow copy directories then default to
// only to the ones that are in the private bin path.
if(Value[(int) LoaderInformation.ShadowCopyDirectoriesValue] == null)
ShadowCopyDirectories = BuildShadowCopyDirectories();
String shadowDirs = Value[(int) LoaderInformation.ShadowCopyDirectoriesValue];
if(shadowDirs != null)
UpdateContextProperty(fusionContext, ShadowCopyDirectoriesKey, shadowDirs);
}
String cache = Value[(int) LoaderInformation.CachePathValue];
if(cache != null)
UpdateContextProperty(fusionContext, CachePathKey, cache);
if(PrivateBinPathProbe != null)
UpdateContextProperty(fusionContext, PrivateBinPathProbeKey, PrivateBinPathProbe);
String config = Value[(int) LoaderInformation.ConfigurationFileValue];
if (config != null)
UpdateContextProperty(fusionContext, ConfigurationFileKey, config);
if(ApplicationName != null)
UpdateContextProperty(fusionContext, ApplicationNameKey, ApplicationName);
String dynbase = Value[(int) LoaderInformation.DynamicBaseValue];
if(dynbase != null)
UpdateContextProperty(fusionContext, DynamicBaseKey, dynbase);
// Always add the runtime configuration file to the appdomain
StringBuilder configFile = new StringBuilder();
configFile.Append(RuntimeEnvironment.GetRuntimeDirectoryImpl());
configFile.Append(RuntimeConfigurationFile);
UpdateContextProperty(fusionContext, MachineConfigKey, configFile.ToString());
String hostBindingFile = RuntimeEnvironment.GetHostBindingFile();
if(hostBindingFile != null)
UpdateContextProperty(fusionContext, HostBindingKey, hostBindingFile);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void UpdateContextProperty(IntPtr fusionContext, string key, string value);
/// <include file='doc\AppDomainSetup.uex' path='docs/doc[@for="AppDomainSetup.Locate"]/*' />
static internal int Locate(String s)
{
return Mapping.Locate(s);
}
private string BuildShadowCopyDirectories()
{
String binPath = PrivateBinPath;
if(binPath == null)
return null;
StringBuilder result = new StringBuilder();
String appBase = Value[(int) LoaderInformation.ApplicationBaseValue];
if(appBase != null) {
char[] sep = {';'};
string[] directories = binPath.Split(sep);
int size = directories.Length;
bool appendSlash = !( (appBase[appBase.Length-1] == '/') ||
(appBase[appBase.Length-1] == '\\') );
if (size == 0) {
result.Append(appBase);
if (appendSlash)
result.Append('\\');
result.Append(binPath);
}
else {
for(int i = 0; i < size; i++) {
result.Append(appBase);
if (appendSlash)
result.Append('\\');
result.Append(directories[i]);
if (i < size-1)
result.Append(';');
}
}
}
return result.ToString();
}
// This is a separate class that will be loaded only when a mapping is
// required.
private class Mapping {
struct Entry
{
public string value;
public int slot;
}
private static Object _table;
// Make sure these are sorted
static private string[] OldNames =
{
ACTAG_APP_CONFIG_FILE,
ACTAG_APP_NAME,
ACTAG_APP_BASE_URL,
ACTAG_BINPATH_PROBE_ONLY,
ACTAG_APP_CACHE_BASE,
ACTAG_DEV_PATH,
ACTAG_APP_DYNAMIC_BASE,
ACTAG_FORCE_CACHE_INSTALL,
LICENSE_FILE,
ACTAG_APP_PRIVATE_BINPATH,
ACTAG_APP_SHADOW_COPY_DIRS,
};
static private LoaderInformation[] Location =
{
LoaderInformation.ConfigurationFileValue,
LoaderInformation.ApplicationNameValue,
LoaderInformation.ApplicationBaseValue,
LoaderInformation.PrivateBinPathProbeValue,
LoaderInformation.CachePathValue,
LoaderInformation.DevPathValue,
LoaderInformation.DynamicBaseValue,
LoaderInformation.ShadowCopyFilesValue,
LoaderInformation.LicenseFileValue,
LoaderInformation.PrivateBinPathValue,
LoaderInformation.ShadowCopyDirectoriesValue,
};
internal static int Locate(String setting)
{
if(setting == null)
return -1;
Entry[] t = Table();
int l = 0;
int r = t.Length - 1;
int piviot;
while(true) {
piviot = (l + r) / 2;
int v = String.Compare(t[piviot].value, setting, false, CultureInfo.InvariantCulture);
if(v == 0)
return t[piviot].slot; // Found it
else if(v < 0)
l = piviot + 1;
else
r = piviot - 1;
if(l > r) return -1; // Not here
}
}
private static Entry[] Table()
{
if(_table == null) {
int size = OldNames.Length;
Entry[] newTable = new Entry[size];
for(int i = 0; i < size; i++) {
newTable[i].value = OldNames[i];
newTable[i].slot = (int) Location[i];
}
Interlocked.CompareExchange(ref _table, (Object) newTable, (Object) null);
}
if(_table == null)
throw new NullReferenceException();
return (Entry[]) _table;
}
}
}
}
@@ -0,0 +1,59 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: AppDomainUnloadedException
**
**
**
** Purpose: Exception class for attempt to access an unloaded AppDomain
**
** Date: March 17, 1998
**
=============================================================================*/
namespace System {
using System.Runtime.Serialization;
/// <include file='doc\AppDomainUnloadedException.uex' path='docs/doc[@for="AppDomainUnloadedException"]/*' />
[Serializable()] public class AppDomainUnloadedException : SystemException {
/// <include file='doc\AppDomainUnloadedException.uex' path='docs/doc[@for="AppDomainUnloadedException.AppDomainUnloadedException"]/*' />
public AppDomainUnloadedException()
: base(Environment.GetResourceString("Arg_AppDomainUnloadedException")) {
SetErrorCode(__HResults.COR_E_APPDOMAINUNLOADED);
}
/// <include file='doc\AppDomainUnloadedException.uex' path='docs/doc[@for="AppDomainUnloadedException.AppDomainUnloadedException1"]/*' />
public AppDomainUnloadedException(String message)
: base(message) {
SetErrorCode(__HResults.COR_E_APPDOMAINUNLOADED);
}
/// <include file='doc\AppDomainUnloadedException.uex' path='docs/doc[@for="AppDomainUnloadedException.AppDomainUnloadedException2"]/*' />
public AppDomainUnloadedException(String message, Exception innerException)
: base(message, innerException) {
SetErrorCode(__HResults.COR_E_APPDOMAINUNLOADED);
}
//
//This constructor is required for serialization.
//
/// <include file='doc\AppDomainUnloadedException.uex' path='docs/doc[@for="AppDomainUnloadedException.AppDomainUnloadedException3"]/*' />
protected AppDomainUnloadedException(SerializationInfo info, StreamingContext context) : base(info, context) {
}
}
}
@@ -0,0 +1,61 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: AppDomainUnloadInProgressException
**
**
**
** Purpose: Exception class for attempt unload multiple AppDomains
** simultaneously
**
** Date: March 17, 1998
**
=============================================================================*/
namespace System {
using System.Runtime.Serialization;
/// <include file='doc\AppDomainUnloadInProgressException.uex' path='docs/doc[@for="AppDomainUnloadInProgressException"]/*' />
[Serializable()] public class AppDomainUnloadInProgressException : SystemException {
/// <include file='doc\AppDomainUnloadInProgressException.uex' path='docs/doc[@for="AppDomainUnloadInProgressException.AppDomainUnloadInProgressException"]/*' />
public AppDomainUnloadInProgressException()
: base(Environment.GetResourceString("Arg_CannotUnloadAppDomainException")) {
SetErrorCode(__HResults.COR_E_CANNOTUNLOADAPPDOMAIN);
}
/// <include file='doc\AppDomainUnloadInProgressException.uex' path='docs/doc[@for="AppDomainUnloadInProgressException.AppDomainUnloadInProgressException1"]/*' />
public AppDomainUnloadInProgressException(String message)
: base(message) {
SetErrorCode(__HResults.COR_E_CANNOTUNLOADAPPDOMAIN);
}
/// <include file='doc\AppDomainUnloadInProgressException.uex' path='docs/doc[@for="AppDomainUnloadInProgressException.AppDomainUnloadInProgressException2"]/*' />
public AppDomainUnloadInProgressException(String message, Exception innerException)
: base(message, innerException) {
SetErrorCode(__HResults.COR_E_CANNOTUNLOADAPPDOMAIN);
}
//
// This constructor is required for serialization
//
/// <include file='doc\AppDomainUnloadInProgressException.uex' path='docs/doc[@for="AppDomainUnloadInProgressException.AppDomainUnloadInProgressException3"]/*' />
protected AppDomainUnloadInProgressException(SerializationInfo info, StreamingContext context) : base(info, context) {
}
}
}
@@ -0,0 +1,72 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: ApplicationException
**
** Author:
**
** Purpose: The base class for all "less serious" exceptions that must be
** declared or caught.
**
** Date: March 11, 1998
**
=============================================================================*/
namespace System {
using System.Runtime.Serialization;
// The ApplicationException is the base class for nonfatal,
// application errors that occur. These exceptions are generated
// (i.e., thrown) by an application, not the Runtime. Applications that need
// to create their own exceptions do so by extending this class.
// ApplicationException extends but adds no new functionality to
// RecoverableException.
//
/// <include file='doc\ApplicationException.uex' path='docs/doc[@for="ApplicationException"]/*' />
[Serializable()] public class ApplicationException : Exception {
// Creates a new ApplicationException with its message string set to
// the empty string, its HRESULT set to COR_E_APPLICATION,
// and its ExceptionInfo reference set to null.
/// <include file='doc\ApplicationException.uex' path='docs/doc[@for="ApplicationException.ApplicationException"]/*' />
public ApplicationException()
: base(Environment.GetResourceString("Arg_ApplicationException")) {
SetErrorCode(__HResults.COR_E_APPLICATION);
}
// Creates a new ApplicationException with its message string set to
// message, its HRESULT set to COR_E_APPLICATION,
// and its ExceptionInfo reference set to null.
//
/// <include file='doc\ApplicationException.uex' path='docs/doc[@for="ApplicationException.ApplicationException1"]/*' />
public ApplicationException(String message)
: base(message) {
SetErrorCode(__HResults.COR_E_APPLICATION);
}
/// <include file='doc\ApplicationException.uex' path='docs/doc[@for="ApplicationException.ApplicationException2"]/*' />
public ApplicationException(String message, Exception innerException)
: base(message, innerException) {
SetErrorCode(__HResults.COR_E_APPLICATION);
}
/// <include file='doc\ApplicationException.uex' path='docs/doc[@for="ApplicationException.ApplicationException3"]/*' />
protected ApplicationException(SerializationInfo info, StreamingContext context) : base(info, context) {
}
}
}
+115
View File
@@ -0,0 +1,115 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace System {
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// This class will not be marked serializable
/// <include file='doc\ArgIterator.uex' path='docs/doc[@for="ArgIterator"]/*' />
[StructLayout(LayoutKind.Auto)]
public struct ArgIterator
{
// create an arg iterator that points at the first argument that
// is not statically declared (that is the first ... arg)
// 'arglist' is the value returned by the ARGLIST instruction
/// <include file='doc\ArgIterator.uex' path='docs/doc[@for="ArgIterator.ArgIterator"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern ArgIterator(RuntimeArgumentHandle arglist);
// create an arg iterator that points just past 'firstArg'.
// 'arglist' is the value returned by the ARGLIST instruction
// This is much like the C va_start macro
/// <include file='doc\ArgIterator.uex' path='docs/doc[@for="ArgIterator.ArgIterator1"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall), CLSCompliant(false)]
public unsafe extern ArgIterator(RuntimeArgumentHandle arglist, void* ptr);
// Fetch an argument as a typed referece, advance the iterator.
// Throws an exception if past end of argument list
/// <include file='doc\ArgIterator.uex' path='docs/doc[@for="ArgIterator.GetNextArg"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall), CLSCompliant(false)]
public extern TypedReference GetNextArg();
// Alternate version of GetNextArg() intended primarily for IJW code
// generated by VC's "va_arg()" construct.
/// <include file='doc\ArgIterator.uex' path='docs/doc[@for="ArgIterator.GetNextArg1"]/*' />
[CLSCompliant(false)]
public TypedReference GetNextArg(RuntimeTypeHandle rth)
{
if (SigPtr != IntPtr.Zero)
{
// This is an ordinary ArgIterator capable of determining
// types from a signature. Just do a regular GetNextArg.
return GetNextArg();
}
else
{
return InternalGetNextArg(rth);
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall), CLSCompliant(false)]
private extern TypedReference InternalGetNextArg(RuntimeTypeHandle rth);
// Invalidate the iterator (va_end)
/// <include file='doc\ArgIterator.uex' path='docs/doc[@for="ArgIterator.End"]/*' />
public void End()
{
}
// How many arguments are left in the list
/// <include file='doc\ArgIterator.uex' path='docs/doc[@for="ArgIterator.GetRemainingCount"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern int GetRemainingCount();
// Gets the type of the current arg, does NOT advance the iterator
/// <include file='doc\ArgIterator.uex' path='docs/doc[@for="ArgIterator.GetNextArgType"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern RuntimeTypeHandle GetNextArgType();
/// <include file='doc\ArgIterator.uex' path='docs/doc[@for="ArgIterator.GetHashCode"]/*' />
public override int GetHashCode()
{
return unchecked((int)((long)ArgCookie));
}
// Inherited from object
/// <include file='doc\ArgIterator.uex' path='docs/doc[@for="ArgIterator.Equals"]/*' />
public override bool Equals(Object o)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NYI"));
}
private IntPtr ArgCookie; // Cookie from the EE.
private IntPtr SigPtr; // Pointer to remaining signature.
private IntPtr ArgPtr; // Pointer to remaining args.
private int RemainingArgs; // # of remaining args.
//
// This is just designed to prevent compiler warnings.
// This field is used from native, but we need to prevent the compiler warnings.
//
#if _DEBUG
private void DontTouchThis() {
ArgCookie = IntPtr.Zero;
SigPtr = IntPtr.Zero;
ArgPtr = IntPtr.Zero;
RemainingArgs = 0;
}
#endif
}
}
+121
View File
@@ -0,0 +1,121 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: ArgumentException
**
** Author:
**
** Purpose: Exception class for invalid arguments to a method.
**
** Date: March 24, 1998
**
=============================================================================*/
namespace System {
using System;
using System.Runtime.Remoting;
using System.Runtime.Serialization;
// The ArgumentException is thrown when an argument does not meet
// the contract of the method. Ideally it should give a meaningful error
// message describing what was wrong and which parameter is incorrect.
//
/// <include file='doc\ArgumentException.uex' path='docs/doc[@for="ArgumentException"]/*' />
[Serializable()] public class ArgumentException : SystemException, ISerializable {
private String m_paramName;
// Creates a new ArgumentException with its message
// string set to the empty string.
/// <include file='doc\ArgumentException.uex' path='docs/doc[@for="ArgumentException.ArgumentException"]/*' />
public ArgumentException()
: base(Environment.GetResourceString("Arg_ArgumentException")) {
SetErrorCode(__HResults.COR_E_ARGUMENT);
}
// Creates a new ArgumentException with its message
// string set to message.
//
/// <include file='doc\ArgumentException.uex' path='docs/doc[@for="ArgumentException.ArgumentException1"]/*' />
public ArgumentException(String message)
: base(message) {
SetErrorCode(__HResults.COR_E_ARGUMENT);
}
/// <include file='doc\ArgumentException.uex' path='docs/doc[@for="ArgumentException.ArgumentException2"]/*' />
public ArgumentException(String message, Exception innerException)
: base(message, innerException) {
SetErrorCode(__HResults.COR_E_ARGUMENT);
}
/// <include file='doc\ArgumentException.uex' path='docs/doc[@for="ArgumentException.ArgumentException3"]/*' />
public ArgumentException(String message, String paramName, Exception innerException)
: base(message, innerException) {
m_paramName = paramName;
SetErrorCode(__HResults.COR_E_ARGUMENT);
}
/// <include file='doc\ArgumentException.uex' path='docs/doc[@for="ArgumentException.ArgumentException4"]/*' />
public ArgumentException (String message, String paramName)
: base (message) {
m_paramName = paramName;
SetErrorCode(__HResults.COR_E_ARGUMENT);
}
/// <include file='doc\ArgumentException.uex' path='docs/doc[@for="ArgumentException.ArgumentException5"]/*' />
protected ArgumentException(SerializationInfo info, StreamingContext context) : base(info, context) {
m_paramName = info.GetString("ParamName");
}
/// <include file='doc\ArgumentException.uex' path='docs/doc[@for="ArgumentException.Message"]/*' />
public override String Message
{
get {
String s = base.Message;
if (! ((m_paramName == null) ||
(m_paramName.Length == 0)) )
return s + Environment.NewLine + String.Format(Environment.GetResourceString("Arg_ParamName_Name"), m_paramName);
else
return s;
}
}
/*
public String ToString()
{
String s = super.ToString();
if (m_paramName != null)
return s + "Parameter name: "+m_paramName+"\tActual value: "+(m_actualValue==null ? "<null>" : m_actualValue.ToString());
else
return s;
}
*/
/// <include file='doc\ArgumentException.uex' path='docs/doc[@for="ArgumentException.ParamName"]/*' />
public virtual String ParamName {
get { return m_paramName; }
}
/// <include file='doc\ArgumentException.uex' path='docs/doc[@for="ArgumentException.GetObjectData"]/*' />
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException("info");
}
base.GetObjectData(info, context);
info.AddValue("ParamName", m_paramName, typeof(String));
}
}
}
@@ -0,0 +1,76 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: ArgumentNullException
**
**
**
** Purpose: Exception class for null arguments to a method.
**
** Date: April 28, 1999
**
=============================================================================*/
namespace System {
using System;
using System.Runtime.Serialization;
using System.Runtime.Remoting;
// The ArgumentException is thrown when an argument
// is null when it shouldn't be.
//
/// <include file='doc\ArgumentNullException.uex' path='docs/doc[@for="ArgumentNullException"]/*' />
[Serializable] public class ArgumentNullException : ArgumentException
{
private static String _nullMessage = null;
private static String NullMessage {
get {
// Don't bother with synchronization here. A duplicated string
// is not a major problem.
if (_nullMessage == null)
_nullMessage = Environment.GetResourceString("ArgumentNull_Generic");
return _nullMessage;
}
}
// Creates a new ArgumentNullException with its message
// string set to a default message explaining an argument was null.
/// <include file='doc\ArgumentNullException.uex' path='docs/doc[@for="ArgumentNullException.ArgumentNullException"]/*' />
public ArgumentNullException()
: base(NullMessage) {
// Use E_POINTER - COM used that for null pointers. Description is "invalid pointer"
SetErrorCode(__HResults.E_POINTER);
}
/// <include file='doc\ArgumentNullException.uex' path='docs/doc[@for="ArgumentNullException.ArgumentNullException1"]/*' />
public ArgumentNullException(String paramName)
: base(NullMessage, paramName) {
SetErrorCode(__HResults.E_POINTER);
}
/// <include file='doc\ArgumentNullException.uex' path='docs/doc[@for="ArgumentNullException.ArgumentNullException2"]/*' />
public ArgumentNullException(String paramName, String message)
: base(message, paramName) {
SetErrorCode(__HResults.E_POINTER);
}
/// <include file='doc\ArgumentNullException.uex' path='docs/doc[@for="ArgumentNullException.ArgumentNullException3"]/*' />
protected ArgumentNullException(SerializationInfo info, StreamingContext context) : base(info, context) {
}
}
}
@@ -0,0 +1,119 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: ArgumentOutOfRangeException
**
**
**
** Purpose: Exception class for method arguments outside of the legal range.
**
** Date: April 28, 1999
**
=============================================================================*/
namespace System {
using System;
using System.Runtime.Remoting;
using System.Runtime.Serialization;
// The ArgumentOutOfRangeException is thrown when an argument
// is outside the legal range for that argument. This may often be caused
// by
//
/// <include file='doc\ArgumentOutOfRangeException.uex' path='docs/doc[@for="ArgumentOutOfRangeException"]/*' />
[Serializable()] public class ArgumentOutOfRangeException : ArgumentException, ISerializable {
private static String _rangeMessage;
private Object m_actualValue;
private static String RangeMessage {
get {
if (_rangeMessage == null)
_rangeMessage = Environment.GetResourceString("Arg_ArgumentOutOfRangeException");
return _rangeMessage;
}
}
// Creates a new ArgumentOutOfRangeException with its message
// string set to a default message explaining an argument was out of range.
/// <include file='doc\ArgumentOutOfRangeException.uex' path='docs/doc[@for="ArgumentOutOfRangeException.ArgumentOutOfRangeException"]/*' />
public ArgumentOutOfRangeException()
: base(RangeMessage) {
SetErrorCode(__HResults.COR_E_ARGUMENTOUTOFRANGE);
}
/// <include file='doc\ArgumentOutOfRangeException.uex' path='docs/doc[@for="ArgumentOutOfRangeException.ArgumentOutOfRangeException1"]/*' />
public ArgumentOutOfRangeException(String paramName)
: base(RangeMessage, paramName) {
SetErrorCode(__HResults.COR_E_ARGUMENTOUTOFRANGE);
}
/// <include file='doc\ArgumentOutOfRangeException.uex' path='docs/doc[@for="ArgumentOutOfRangeException.ArgumentOutOfRangeException2"]/*' />
public ArgumentOutOfRangeException(String paramName, String message)
: base(message, paramName) {
SetErrorCode(__HResults.COR_E_ARGUMENTOUTOFRANGE);
}
// We will not use this in the classlibs, but we'll provide it for
// anyone that's really interested so they don't have to stick a bunch
// of printf's in their code.
/// <include file='doc\ArgumentOutOfRangeException.uex' path='docs/doc[@for="ArgumentOutOfRangeException.ArgumentOutOfRangeException3"]/*' />
public ArgumentOutOfRangeException(String paramName, Object actualValue, String message)
: base(message, paramName) {
m_actualValue = actualValue;
SetErrorCode(__HResults.COR_E_ARGUMENTOUTOFRANGE);
}
/// <include file='doc\ArgumentOutOfRangeException.uex' path='docs/doc[@for="ArgumentOutOfRangeException.Message"]/*' />
public override String Message
{
get {
String s = base.Message;
if (m_actualValue != null) {
String valueMessage = String.Format(Environment.GetResourceString("ArgumentOutOfRange_ActualValue"), m_actualValue.ToString());
if (s == null)
return valueMessage;
return s + Environment.NewLine + valueMessage;
}
return s;
}
}
// Gets the value of the argument that caused the exception.
// Note - we don't set this anywhere in the class libraries in
// version 1, but it might come in handy for other developers who
// want to avoid sticking printf's in their code.
/// <include file='doc\ArgumentOutOfRangeException.uex' path='docs/doc[@for="ArgumentOutOfRangeException.ActualValue"]/*' />
public virtual Object ActualValue {
get { return m_actualValue; }
}
/// <include file='doc\ArgumentOutOfRangeException.uex' path='docs/doc[@for="ArgumentOutOfRangeException.GetObjectData"]/*' />
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException("info");
}
base.GetObjectData(info, context);
info.AddValue("ActualValue", m_actualValue, typeof(Object));
}
/// <include file='doc\ArgumentOutOfRangeException.uex' path='docs/doc[@for="ArgumentOutOfRangeException.ArgumentOutOfRangeException4"]/*' />
protected ArgumentOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context) {
m_actualValue = info.GetValue("ActualValue", typeof(Object));
}
}
}
+68
View File
@@ -0,0 +1,68 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: ArithmeticException
**
** Author:
**
** Purpose: Exception class for bad arithmetic conditions!
**
** Date: March 17, 1998
**
=============================================================================*/
namespace System {
using System;
using System.Runtime.Serialization;
// The ArithmeticException is thrown when overflow or underflow
// occurs.
//
/// <include file='doc\ArithmeticException.uex' path='docs/doc[@for="ArithmeticException"]/*' />
[Serializable] public class ArithmeticException : SystemException
{
// Creates a new ArithmeticException with its message string set to
// the empty string, its HRESULT set to COR_E_ARITHMETIC,
// and its ExceptionInfo reference set to null.
/// <include file='doc\ArithmeticException.uex' path='docs/doc[@for="ArithmeticException.ArithmeticException"]/*' />
public ArithmeticException()
: base(Environment.GetResourceString("Arg_ArithmeticException")) {
SetErrorCode(__HResults.COR_E_ARITHMETIC);
}
// Creates a new ArithmeticException with its message string set to
// message, its HRESULT set to COR_E_ARITHMETIC,
// and its ExceptionInfo reference set to null.
//
/// <include file='doc\ArithmeticException.uex' path='docs/doc[@for="ArithmeticException.ArithmeticException1"]/*' />
public ArithmeticException(String message)
: base(message) {
SetErrorCode(__HResults.COR_E_ARITHMETIC);
}
/// <include file='doc\ArithmeticException.uex' path='docs/doc[@for="ArithmeticException.ArithmeticException2"]/*' />
public ArithmeticException(String message, Exception innerException)
: base(message, innerException) {
SetErrorCode(__HResults.COR_E_ARITHMETIC);
}
/// <include file='doc\ArithmeticException.uex' path='docs/doc[@for="ArithmeticException.ArithmeticException3"]/*' />
protected ArithmeticException(SerializationInfo info, StreamingContext context) : base(info, context) {
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,68 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: ArrayTypeMismatchException
**
** Author:
**
** Purpose: The arrays are of different primitive types.
**
** Date: March 30, 1998
**
=============================================================================*/
namespace System {
using System;
using System.Runtime.Serialization;
// The ArrayMismatchException is thrown when an attempt to store
// an object of the wrong type within an array occurs.
//
/// <include file='doc\ArrayTypeMismatchException.uex' path='docs/doc[@for="ArrayTypeMismatchException"]/*' />
[Serializable()] public class ArrayTypeMismatchException : SystemException {
// Creates a new ArrayMismatchException with its message string set to
// the empty string, its HRESULT set to COR_E_ARRAYTYPEMISMATCH,
// and its ExceptionInfo reference set to null.
/// <include file='doc\ArrayTypeMismatchException.uex' path='docs/doc[@for="ArrayTypeMismatchException.ArrayTypeMismatchException"]/*' />
public ArrayTypeMismatchException()
: base(Environment.GetResourceString("Arg_ArrayTypeMismatchException")) {
SetErrorCode(__HResults.COR_E_ARRAYTYPEMISMATCH);
}
// Creates a new ArrayMismatchException with its message string set to
// message, its HRESULT set to COR_E_ARRAYTYPEMISMATCH,
// and its ExceptionInfo reference set to null.
//
/// <include file='doc\ArrayTypeMismatchException.uex' path='docs/doc[@for="ArrayTypeMismatchException.ArrayTypeMismatchException1"]/*' />
public ArrayTypeMismatchException(String message)
: base(message) {
SetErrorCode(__HResults.COR_E_ARRAYTYPEMISMATCH);
}
/// <include file='doc\ArrayTypeMismatchException.uex' path='docs/doc[@for="ArrayTypeMismatchException.ArrayTypeMismatchException2"]/*' />
public ArrayTypeMismatchException(String message, Exception innerException)
: base(message, innerException) {
SetErrorCode(__HResults.COR_E_ARRAYTYPEMISMATCH);
}
/// <include file='doc\ArrayTypeMismatchException.uex' path='docs/doc[@for="ArrayTypeMismatchException.ArrayTypeMismatchException3"]/*' />
protected ArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) {
}
}
}
+27
View File
@@ -0,0 +1,27 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Interface: AsyncCallbackDelegate
**
** Purpose: Type of callback for async operations
**
===========================================================*/
namespace System {
/// <include file='doc\AsyncCallback.uex' path='docs/doc[@for="AsyncCallback"]/*' />
[Serializable()]
public delegate void AsyncCallback(IAsyncResult ar);
}
+843
View File
@@ -0,0 +1,843 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: Attribute
**
**
**
** Purpose: The class used as an attribute to denote that
** another class can be used as an attribute.
**
** Date: December 7, 1999
**
===========================================================*/
namespace System {
using System;
using System.Reflection;
using System.Collections;
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute"]/*' />
[Serializable, AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple=false)] // Base class for all attributes
public abstract class Attribute {
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.Attribute"]/*' />
protected Attribute(){}
// This is a private enum used solely for the purpose of avoiding code repeat for these types
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttributes8"]/*' />
public static Attribute[] GetCustomAttributes(MemberInfo element, Type type)
{
return GetCustomAttributes(element, type, true);
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttributes"]/*' />
public static Attribute[] GetCustomAttributes(MemberInfo element, Type type, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (type == null)
throw new ArgumentNullException("type");
if (!type.IsSubclassOf(typeof(Attribute)) && type != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Object[] attributes = null;
switch(element.MemberType)
{
case MemberTypes.Method:
attributes = ((MethodInfo)element).GetCustomAttributes(type, inherit);
break;
case MemberTypes.TypeInfo:
case MemberTypes.NestedType:
attributes = ((Type)element).GetCustomAttributes(type, inherit);
break;
case MemberTypes.Constructor:
attributes = ((ConstructorInfo)element).GetCustomAttributes(type, inherit);
break;
case MemberTypes.Field:
attributes = ((FieldInfo)element).GetCustomAttributes(type, inherit);
break;
case MemberTypes.Property:
return InternalGetCustomAttributes((PropertyInfo)element, type, inherit);
case MemberTypes.Event:
return InternalGetCustomAttributes((EventInfo)element, type, inherit);
default:
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnsupportedMemberInfoTypes"));
}
return (Attribute[])attributes;
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttributes9"]/*' />
public static Attribute[] GetCustomAttributes(MemberInfo element)
{
return GetCustomAttributes(element, true);
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttributes1"]/*' />
public static Attribute[] GetCustomAttributes(MemberInfo element, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
Object[] attributes = null;
switch(element.MemberType)
{
case MemberTypes.Method:
attributes = ((MethodInfo)element).GetCustomAttributes(s_AttributeType, inherit);
break;
case MemberTypes.TypeInfo:
case MemberTypes.NestedType:
attributes = ((Type)element).GetCustomAttributes(s_AttributeType, inherit);
break;
case MemberTypes.Constructor:
attributes = ((ConstructorInfo)element).GetCustomAttributes(s_AttributeType, inherit);
break;
case MemberTypes.Field:
attributes = ((FieldInfo)element).GetCustomAttributes(s_AttributeType, inherit);
break;
case MemberTypes.Property:
return InternalGetCustomAttributes((PropertyInfo)element, s_AttributeType, inherit);
case MemberTypes.Event:
return InternalGetCustomAttributes((EventInfo)element, s_AttributeType, inherit);
default:
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnsupportedMemberInfoTypes"));
}
return (Attribute[])attributes;
}
private static Attribute[] InternalGetCustomAttributes(PropertyInfo element, Type type, bool inherit)
{
// walk up the hierarchy chain
Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit);
if (inherit) {
// create the hashtable that keeps track of inherited types
Hashtable types = new Hashtable(11);
// create an array list to collect all the requested attibutes
ArrayList attributeList = new ArrayList();
CopyToArrayList(attributeList, attributes, types);
PropertyInfo baseProp = GetParentDefinition(element);
while (baseProp != null) {
attributes = GetCustomAttributes(baseProp, type, false);
AddAttributesToList(attributeList, attributes, types);
baseProp = GetParentDefinition(baseProp);
}
return (Attribute[])attributeList.ToArray(type);
}
else
return attributes;
}
private static Attribute[] InternalGetCustomAttributes(EventInfo element, Type type, bool inherit)
{
// walk up the hierarchy chain
Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit);
if (inherit) {
// create the hashtable that keeps track of inherited types
Hashtable types = new Hashtable(11);
// create an array list to collect all the requested attibutes
ArrayList attributeList = new ArrayList();
CopyToArrayList(attributeList, attributes, types);
EventInfo baseEvent = GetParentDefinition(element);
while (baseEvent != null) {
attributes = GetCustomAttributes(baseEvent, type, false);
AddAttributesToList(attributeList, attributes, types);
baseEvent = GetParentDefinition(baseEvent);
}
return (Attribute[])attributeList.ToArray(type);
}
else
return attributes;
}
//
// utility functions
//
static private void CopyToArrayList(ArrayList attributeList, Attribute[] attributes, Hashtable types) {
for (int i = 0; i < attributes.Length; i++) {
attributeList.Add(attributes[i]);
Type attrType = attributes[i].GetType();
if (!types.Contains(attrType))
types[attrType] = InternalGetAttributeUsage(attrType);
}
}
static private void AddAttributesToList(ArrayList attributeList, Attribute[] attributes, Hashtable types) {
for (int i = 0; i < attributes.Length; i++) {
Type attrType = attributes[i].GetType();
AttributeUsageAttribute usage = (AttributeUsageAttribute)types[attrType];
if (usage == null) {
// the type has never been seen before if it's inheritable add it to the list
usage = InternalGetAttributeUsage(attrType);
types[attrType] = usage;
if (usage.Inherited)
attributeList.Add(attributes[i]);
}
else if (usage.Inherited && usage.AllowMultiple)
// we saw this type already add it only if it is inheritable and it does allow multiple
attributeList.Add(attributes[i]);
}
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttributes10"]/*' />
public static Attribute[] GetCustomAttributes (ParameterInfo element, Type attributeType)
{
return (Attribute[])GetCustomAttributes (element, attributeType, true);
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttributes2"]/*' />
public static Attribute[] GetCustomAttributes (ParameterInfo element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
MemberInfo member = element.Member;
if (member.MemberType == MemberTypes.Method && inherit)
return InternalParamGetCustomAttributes((MethodInfo)member, element, attributeType, inherit);
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
}
// For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain that
// have this ParameterInfo defined. .We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes
// that are marked inherited from the remainder of the MethodInfo's in the inheritance chain.
// For MethodInfo's on an interface we do not do an inheritance walk so the default ParameterInfo attributes are returned.
// For MethodInfo's on a class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the
// class inherits from and return the respective ParameterInfo attributes
private static Attribute[] InternalParamGetCustomAttributes(MethodInfo method, ParameterInfo param, Type type, bool inherit)
{
ArrayList disAllowMultiple = new ArrayList();
Object [] objAttr;
if (type == null)
type = s_AttributeType;
objAttr = param.GetCustomAttributes(type, false);
for (int i=0;i<objAttr.Length;i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if (attribUsage.AllowMultiple == false)
disAllowMultiple.Add(objType);
}
// Get all the attributes that have Attribute as the base class
Attribute [] ret = null;
if (objAttr.Length == 0)
ret = (Attribute[])Array.CreateInstance(type,0);
else
ret = (Attribute[])objAttr;
if (method.DeclaringType == null) // This is an interface so we are done.
return ret;
if (!inherit)
return ret;
int paramPosition = param.Position;
method = method.GetParentDefinition();
while (method != null)
{
// Find the ParameterInfo on this method
ParameterInfo [] parameters = method.GetParameters();
param = parameters[paramPosition]; // Point to the correct ParameterInfo of the method
objAttr = param.GetCustomAttributes(type, false);
int count = 0;
for (int i=0;i<objAttr.Length;i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if ((attribUsage.Inherited)
&& (disAllowMultiple.Contains(objType) == false))
{
if (attribUsage.AllowMultiple == false)
disAllowMultiple.Add(objType);
count++;
}
else
objAttr[i] = null;
}
// Get all the attributes that have Attribute as the base class
Attribute [] attributes = (Attribute[])Array.CreateInstance(type,count);
count=0;
for (int i=0;i<objAttr.Length;i++)
{
if (objAttr[i] != null)
{
attributes[count] = (Attribute)objAttr[i];
count++;
}
}
Attribute [] temp = ret;
ret = (Attribute[])Array.CreateInstance(type,temp.Length + count);
Array.Copy(temp,ret,temp.Length);
int offset = temp.Length;
for (int i=0;i<attributes.Length;i++)
ret[offset + i] = attributes[i];
method = method.GetParentDefinition();
}
return ret;
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttributes11"]/*' />
public static Attribute[] GetCustomAttributes (Module element, Type attributeType)
{
return GetCustomAttributes (element, attributeType, true);
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttributes3"]/*' />
public static Attribute[] GetCustomAttributes (Module element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttributes12"]/*' />
public static Attribute[] GetCustomAttributes (Assembly element, Type attributeType)
{
return GetCustomAttributes (element, attributeType, true);
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttributes4"]/*' />
public static Attribute[] GetCustomAttributes (Assembly element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttributes13"]/*' />
public static Attribute[] GetCustomAttributes(ParameterInfo element)
{
return GetCustomAttributes(element, true);
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttributes5"]/*' />
public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
MemberInfo member = element.Member;
if (member.MemberType == MemberTypes.Method && inherit)
return InternalParamGetCustomAttributes((MethodInfo)member, element, null, inherit);
return (Attribute[])element.GetCustomAttributes(s_AttributeType, inherit);
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttributes14"]/*' />
public static Attribute[] GetCustomAttributes(Module element)
{
return GetCustomAttributes(element, true);
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttributes6"]/*' />
public static Attribute[] GetCustomAttributes(Module element, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
return (Attribute[])element.GetCustomAttributes(s_AttributeType, inherit);
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttributes15"]/*' />
public static Attribute[] GetCustomAttributes(Assembly element)
{
return GetCustomAttributes(element, true);
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttributes7"]/*' />
public static Attribute[] GetCustomAttributes(Assembly element, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
return (Attribute[])element.GetCustomAttributes(s_AttributeType, inherit);
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.IsDefined4"]/*' />
public static bool IsDefined (MemberInfo element, Type attributeType)
{
return IsDefined(element, attributeType, true);
}
// Returns true if a custom attribute subclass of attributeType class/interface with inheritance walk
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.IsDefined"]/*' />
public static bool IsDefined (MemberInfo element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
switch(element.MemberType)
{
case MemberTypes.Method:
return ((MethodInfo)element).IsDefined(attributeType,inherit);
case MemberTypes.TypeInfo:
case MemberTypes.NestedType:
return ((Type)element).IsDefined(attributeType,inherit);
case MemberTypes.Constructor:
return ((ConstructorInfo)element).IsDefined(attributeType,false);
case MemberTypes.Field:
return ((FieldInfo)element).IsDefined(attributeType,false);
case MemberTypes.Property:
return InternalIsDefined((PropertyInfo)element,attributeType,false);
case MemberTypes.Event:
return InternalIsDefined((EventInfo)element,attributeType,false);
default:
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnsupportedMemberInfoTypes"));
}
}
private static bool InternalIsDefined (PropertyInfo element, Type attributeType, bool inherit)
{
// walk up the hierarchy chain
if (element.IsDefined(attributeType, inherit))
return true;
if (inherit) {
AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType);
if (!usage.Inherited)
return false;
PropertyInfo baseProp = GetParentDefinition(element);
while (baseProp != null) {
if (baseProp.IsDefined(attributeType, false))
return true;
baseProp = GetParentDefinition(baseProp);
}
}
return false;
}
private static bool InternalIsDefined (EventInfo element, Type attributeType, bool inherit)
{
// walk up the hierarchy chain
if (element.IsDefined(attributeType, inherit))
return true;
if (inherit) {
AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType);
if (!usage.Inherited)
return false;
EventInfo baseEvent = GetParentDefinition(element);
while (baseEvent != null) {
if (baseEvent.IsDefined(attributeType, false))
return true;
baseEvent = GetParentDefinition(baseEvent);
}
}
return false;
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.IsDefined5"]/*' />
public static bool IsDefined (ParameterInfo element, Type attributeType)
{
return IsDefined(element, attributeType, true);
}
// Returns true is a custom attribute subclass of attributeType class/interface with inheritance walk
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.IsDefined1"]/*' />
public static bool IsDefined (ParameterInfo element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
MemberInfo member = element.Member;
switch(member.MemberType)
{
case MemberTypes.Method: // We need to climb up the member hierarchy
return InternalParamIsDefined((MethodInfo)member,element,attributeType,inherit);
case MemberTypes.Constructor:
return element.IsDefined(attributeType,false);
case MemberTypes.Property:
return element.IsDefined(attributeType,false);
default:
BCLDebug.Assert(false,"Invalid type for ParameterInfo member in Attribute class");
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParamInfo"));
}
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.IsDefined6"]/*' />
public static bool IsDefined (Module element, Type attributeType)
{
return IsDefined(element, attributeType, false);
}
// Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.IsDefined2"]/*' />
public static bool IsDefined (Module element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
return element.IsDefined(attributeType,false);
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.IsDefined7"]/*' />
public static bool IsDefined (Assembly element, Type attributeType)
{
return IsDefined (element, attributeType, true);
}
// Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.IsDefined3"]/*' />
public static bool IsDefined (Assembly element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
return element.IsDefined(attributeType, false);
}
// For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain.
// We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes that are marked inherited from the remainder of the ParameterInfo's in the inheritance chain.
// For MethodInfo's on an interface we do not do an inheritance walk. For ParameterInfo's on a
// Class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the
// class inherits from.
private static bool InternalParamIsDefined(MethodInfo method,ParameterInfo param,Type type, bool inherit)
{
if (param.IsDefined(type, false))
return true;
if (method.DeclaringType == null || !inherit) // This is an interface so we are done.
return false;
int paramPosition = param.Position;
method = method.GetParentDefinition();
while (method != null)
{
ParameterInfo [] parameters = method.GetParameters();
param = parameters[paramPosition];
Object [] objAttr = param.GetCustomAttributes(type, false);
for (int i=0;i<objAttr.Length;i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if ((objAttr[i] is Attribute)
&& (attribUsage.Inherited))
return true;
}
method = method.GetParentDefinition();
}
return false;
}
// Check if the custom attributes is Inheritable
private static AttributeUsageAttribute InternalGetAttributeUsage(Type type)
{
Object [] obj = type.GetCustomAttributes(s_AttributeUsageType, false);
AttributeUsageAttribute attrib;
if (obj.Length == 1)
attrib = (AttributeUsageAttribute)obj[0];
else
if (obj.Length == 0)
attrib = AttributeUsageAttribute.Default;
else
throw new FormatException(Environment.GetResourceString("Format_AttributeUsage"));
return attrib;
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttribute4"]/*' />
public static Attribute GetCustomAttribute (MemberInfo element, Type attributeType)
{
return GetCustomAttribute (element, attributeType, true);
}
// Returns an Attribute of base class/inteface attributeType on the MemberInfo or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttribute"]/*' />
public static Attribute GetCustomAttribute (MemberInfo element, Type attributeType, bool inherit)
{
Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit);
if (attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
else
throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttribute5"]/*' />
public static Attribute GetCustomAttribute (ParameterInfo element, Type attributeType)
{
return GetCustomAttribute (element, attributeType, true);
}
// Returns an Attribute of base class/inteface attributeType on the ParameterInfo or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttribute1"]/*' />
public static Attribute GetCustomAttribute (ParameterInfo element, Type attributeType, bool inherit)
{
Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit);
if (attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
else
throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttribute6"]/*' />
public static Attribute GetCustomAttribute (Module element, Type attributeType)
{
return GetCustomAttribute (element, attributeType, true);
}
// Returns an Attribute of base class/inteface attributeType on the Module or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttribute2"]/*' />
public static Attribute GetCustomAttribute (Module element, Type attributeType, bool inherit)
{
Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit);
if (attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
else
throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttribute7"]/*' />
public static Attribute GetCustomAttribute (Assembly element, Type attributeType)
{
return GetCustomAttribute (element, attributeType, true);
}
// Returns an Attribute of base class/inteface attributeType on the Assembly or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetCustomAttribute3"]/*' />
public static Attribute GetCustomAttribute (Assembly element, Type attributeType, bool inherit)
{
Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit);
if (attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
else
throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.TypeId"]/*' />
public virtual Object TypeId {
get {
return GetType();
}
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.Match"]/*' />
public virtual bool Match(Object obj) {
return Equals(obj);
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.Equals"]/*' />
/// <internalonly/>
public override bool Equals(Object obj){
if (obj == null)
return false;
BCLDebug.Assert((this.GetType() as RuntimeType) != null,"Only RuntimeType's are supported");
RuntimeType thisType = (RuntimeType)this.GetType();
BCLDebug.Assert((obj.GetType() as RuntimeType) != null,"Only RuntimeType's are supported");
RuntimeType thatType = (RuntimeType)obj.GetType();
if (thatType!=thisType) {
return false;
}
Object thisObj = (Object)this;
Object thisResult, thatResult;
FieldInfo[] thisFields = thisType.InternalGetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, false);
for (int i=0; i<thisFields.Length; i++) {
thisResult = ((RuntimeFieldInfo)thisFields[i]).InternalGetValue(thisObj,false);
thatResult = ((RuntimeFieldInfo)thisFields[i]).InternalGetValue(obj, false);
if (thisResult == null) {
if (thatResult != null)
return false;
}
else
if (!thisResult.Equals(thatResult)) {
return false;
}
}
return true;
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.GetHashCode"]/*' />
public override int GetHashCode()
{
BCLDebug.Assert((this.GetType() as RuntimeType) != null,"Only RuntimeType's are supported");
RuntimeType runtimeType = (RuntimeType)this.GetType();
FieldInfo[] fields = runtimeType.InternalGetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, false);
Object vThis = null;
for(int i = 0; i < fields.Length; i++) {
RuntimeFieldInfo runtimeField = fields[i] as RuntimeFieldInfo;
vThis = runtimeField.InternalGetValue(this, false);
if (vThis != null)
break;
}
if (vThis != null)
return vThis.GetHashCode();
return runtimeType.GetHashCode();
}
/// <include file='doc\Attribute.uex' path='docs/doc[@for="Attribute.IsDefaultAttribute"]/*' />
public virtual bool IsDefaultAttribute() {
return false;
}
//
// utility function
//
static private PropertyInfo GetParentDefinition(PropertyInfo property) {
// for the current property get the base class of the getter and the setter, they might be different
MethodInfo propAccessor = property.GetGetMethod(true);
if (propAccessor == null)
propAccessor = property.GetSetMethod(true);
if (propAccessor != null) {
propAccessor = propAccessor.GetParentDefinition();
if (propAccessor != null)
return propAccessor.DeclaringType.GetProperty(property.Name, property.PropertyType);
}
return null;
}
static private EventInfo GetParentDefinition(EventInfo ev) {
MethodInfo add = ev.GetAddMethod(true);
if (add != null) {
add = add.GetParentDefinition();
if (add != null)
return add.DeclaringType.GetEvent(ev.Name);
}
return null;
}
private static readonly Type s_AttributeType = typeof(Attribute);
private static readonly Type s_AttributeUsageType = typeof(AttributeUsageAttribute);
}
}
+61
View File
@@ -0,0 +1,61 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
namespace System {
using System;
/** Enum used to indicate all the elements of the
* VOS it is valid to attach this element to.
*/
/// <include file='doc\AttributeTargets.uex' path='docs/doc[@for="AttributeTargets"]/*' />
[Flags,Serializable]
public enum AttributeTargets
{
/// <include file='doc\AttributeTargets.uex' path='docs/doc[@for="AttributeTargets.Assembly"]/*' />
Assembly = 0x0001,
/// <include file='doc\AttributeTargets.uex' path='docs/doc[@for="AttributeTargets.Module"]/*' />
Module = 0x0002,
/// <include file='doc\AttributeTargets.uex' path='docs/doc[@for="AttributeTargets.Class"]/*' />
Class = 0x0004,
/// <include file='doc\AttributeTargets.uex' path='docs/doc[@for="AttributeTargets.Struct"]/*' />
Struct = 0x0008,
/// <include file='doc\AttributeTargets.uex' path='docs/doc[@for="AttributeTargets.Enum"]/*' />
Enum = 0x0010,
/// <include file='doc\AttributeTargets.uex' path='docs/doc[@for="AttributeTargets.Constructor"]/*' />
Constructor = 0x0020,
/// <include file='doc\AttributeTargets.uex' path='docs/doc[@for="AttributeTargets.Method"]/*' />
Method = 0x0040,
/// <include file='doc\AttributeTargets.uex' path='docs/doc[@for="AttributeTargets.Property"]/*' />
Property = 0x0080,
/// <include file='doc\AttributeTargets.uex' path='docs/doc[@for="AttributeTargets.Field"]/*' />
Field = 0x0100,
/// <include file='doc\AttributeTargets.uex' path='docs/doc[@for="AttributeTargets.Event"]/*' />
Event = 0x0200,
/// <include file='doc\AttributeTargets.uex' path='docs/doc[@for="AttributeTargets.Interface"]/*' />
Interface = 0x0400,
/// <include file='doc\AttributeTargets.uex' path='docs/doc[@for="AttributeTargets.Parameter"]/*' />
Parameter = 0x0800,
/// <include file='doc\AttributeTargets.uex' path='docs/doc[@for="AttributeTargets.Delegate"]/*' />
Delegate = 0x1000,
/// <include file='doc\AttributeTargets.uex' path='docs/doc[@for="AttributeTargets.ReturnValue"]/*' />
ReturnValue = 0x2000,
/// <include file='doc\AttributeTargets.uex' path='docs/doc[@for="AttributeTargets.All"]/*' />
All = Assembly | Module | Class | Struct | Enum | Constructor |
Method | Property | Field | Event | Interface | Parameter | Delegate | ReturnValue,
}
}
@@ -0,0 +1,68 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: AttributeUsageAttribute
**
**
**
** Purpose: The class denotes how to specify the usage of an attribute
**
** Date: December 7, 1999
**
===========================================================*/
namespace System {
using System.Reflection;
/* By default, attributes are inherited and multiple attributes are not allowed */
/// <include file='doc\AttributeUsageAttribute.uex' path='docs/doc[@for="AttributeUsageAttribute"]/*' />
[AttributeUsage(AttributeTargets.Class, Inherited = true),Serializable()]
public sealed class AttributeUsageAttribute : Attribute
{
internal AttributeTargets m_attributeTarget = AttributeTargets.All; // Defaults to all
internal bool m_allowMultiple = false; // Defaults to false
internal bool m_inherited = true; // Defaults to true
internal static AttributeUsageAttribute Default = new AttributeUsageAttribute(AttributeTargets.All);
//Constructors
/// <include file='doc\AttributeUsageAttribute.uex' path='docs/doc[@for="AttributeUsageAttribute.AttributeUsageAttribute"]/*' />
public AttributeUsageAttribute(AttributeTargets validOn) {
m_attributeTarget = validOn;
}
//Properties
/// <include file='doc\AttributeUsageAttribute.uex' path='docs/doc[@for="AttributeUsageAttribute.ValidOn"]/*' />
public AttributeTargets ValidOn
{
get{ return m_attributeTarget; }
}
/// <include file='doc\AttributeUsageAttribute.uex' path='docs/doc[@for="AttributeUsageAttribute.AllowMultiple"]/*' />
public bool AllowMultiple
{
get { return m_allowMultiple; }
set { m_allowMultiple = value; }
}
/// <include file='doc\AttributeUsageAttribute.uex' path='docs/doc[@for="AttributeUsageAttribute.Inherited"]/*' />
public bool Inherited
{
get { return m_inherited; }
set { m_inherited = value; }
}
}
}
@@ -0,0 +1,166 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: BadImageFormatException
**
**
**
** Purpose: Exception to an invalid dll or executable format.
**
** Date: May 22, 2000
**
===========================================================*/
namespace System {
using System;
using System.Runtime.Serialization;
using FileLoadException = System.IO.FileLoadException;
using System.Security.Permissions;
using SecurityException = System.Security.SecurityException;
/// <include file='doc\BadImageFormatException.uex' path='docs/doc[@for="BadImageFormatException"]/*' />
[Serializable()] public class BadImageFormatException : SystemException {
private String _fileName; // The name of the corrupt PE file.
private String _fusionLog; // fusion log (when applicable)
/// <include file='doc\BadImageFormatException.uex' path='docs/doc[@for="BadImageFormatException.BadImageFormatException"]/*' />
public BadImageFormatException()
: base(Environment.GetResourceString("Arg_BadImageFormatException")) {
SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT);
}
/// <include file='doc\BadImageFormatException.uex' path='docs/doc[@for="BadImageFormatException.BadImageFormatException1"]/*' />
public BadImageFormatException(String message)
: base(message) {
SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT);
}
/// <include file='doc\BadImageFormatException.uex' path='docs/doc[@for="BadImageFormatException.BadImageFormatException2"]/*' />
public BadImageFormatException(String message, Exception inner)
: base(message, inner) {
SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT);
}
/// <include file='doc\BadImageFormatException.uex' path='docs/doc[@for="BadImageFormatException.BadImageFormatException3"]/*' />
public BadImageFormatException(String message, String fileName) : base(message)
{
SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT);
_fileName = fileName;
}
/// <include file='doc\BadImageFormatException.uex' path='docs/doc[@for="BadImageFormatException.BadImageFormatException4"]/*' />
public BadImageFormatException(String message, String fileName, Exception inner)
: base(message, inner) {
SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT);
_fileName = fileName;
}
/// <include file='doc\BadImageFormatException.uex' path='docs/doc[@for="BadImageFormatException.Message"]/*' />
public override String Message
{
get {
SetMessageField();
return _message;
}
}
private void SetMessageField()
{
if (_message == null) {
if (_fileName == null)
_message = Environment.GetResourceString("Arg_BadImageFormatException");
else
_message = FileLoadException.FormatFileLoadExceptionMessage(_fileName, HResult);
}
}
/// <include file='doc\BadImageFormatException.uex' path='docs/doc[@for="BadImageFormatException.FileName"]/*' />
public String FileName {
get { return _fileName; }
}
/// <include file='doc\BadImageFormatException.uex' path='docs/doc[@for="BadImageFormatException.ToString"]/*' />
public override String ToString()
{
String s = GetType().FullName + ": " + Message;
if (_fileName != null && _fileName.Length != 0)
s += Environment.NewLine + String.Format(Environment.GetResourceString("IO.FileName_Name"), _fileName);
if (InnerException != null)
s = s + " ---> " + InnerException.ToString();
if (StackTrace != null)
s += Environment.NewLine + StackTrace;
try
{
if(FusionLog!=null)
{
if (s==null)
s=" ";
s+=Environment.NewLine;
s+=Environment.NewLine;
s+="Fusion log follows: ";
s+=Environment.NewLine;
s+=FusionLog;
}
}
catch(SecurityException)
{
}
return s;
}
/// <include file='doc\BadImageFormatException.uex' path='docs/doc[@for="BadImageFormatException.BadImageFormatException5"]/*' />
protected BadImageFormatException(SerializationInfo info, StreamingContext context) : base(info, context) {
// Base class constructor will check info != null.
_fileName = info.GetString("BadImageFormat_FileName");
_fusionLog = info.GetString("BadImageFormat_FusionLog");
}
private BadImageFormatException(String fileName, String fusionLog,int hResult)
: base(null)
{
SetErrorCode(hResult);
_fileName = fileName;
_fusionLog=fusionLog;
SetMessageField();
}
/// <include file='doc\BadImageFormatException.uex' path='docs/doc[@for="BadImageFormatException.FusionLog"]/*' />
public String FusionLog {
[SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
get { return _fusionLog; }
}
/// <include file='doc\BadImageFormatException.uex' path='docs/doc[@for="BadImageFormatException.GetObjectData"]/*' />
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
// Serialize data for our base classes. base will verify info != null.
base.GetObjectData(info, context);
// Serialize data for this class
info.AddValue("BadImageFormat_FileName", _fileName, typeof(String));
info.AddValue("BadImageFormat_FusionLog", _fusionLog, typeof(String));
}
}
}
+430
View File
@@ -0,0 +1,430 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: BCLDebug
**
**
**
** Purpose: Debugging Macros for use in the Base Class Libraries
**
** Date: November 16, 1999
**
============================================================*/
namespace System {
using System.IO;
using System.Text;
using System.Runtime.Remoting;
using System.Diagnostics;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
using System.Security;
[Serializable]
internal enum LogLevel {
Trace = 0,
Status = 20,
Warning= 40,
Error = 50,
Panic = 100,
}
internal struct SwitchStructure {
internal String name;
internal int value;
internal SwitchStructure (String n, int v) {
name = n;
value = v;
}
}
// Only statics, does not need to be marked with the serializable attribute
internal class BCLDebug {
#if WIN32
internal static bool m_registryChecked=false;
internal static bool m_perfWarnings;
internal static bool m_correctnessWarnings;
#if _DEBUG
internal static bool m_domainUnloadAdded;
#endif
internal static PermissionSet m_MakeConsoleErrorLoggingWork;
static SwitchStructure[] switches = {
new SwitchStructure("NLS", 0x00000001),
new SwitchStructure("SER", 0x00000002),
new SwitchStructure("DYNIL",0x00000004),
new SwitchStructure("REMOTE",0x00000008),
new SwitchStructure("BINARY",0x00000010), //Binary Formatter
new SwitchStructure("SOAP",0x00000020), // Soap Formatter
new SwitchStructure("REMOTINGCHANNELS",0x00000040),
new SwitchStructure("CACHE",0x00000080),
new SwitchStructure("RESMGRFILEFORMAT", 0x00000100), // .resources files
new SwitchStructure("PERF", 0x00000200),
new SwitchStructure("CORRECTNESS", 0x00000400),
};
static LogLevel[] levelConversions = {
LogLevel.Panic,
LogLevel.Error,
LogLevel.Error,
LogLevel.Warning,
LogLevel.Warning,
LogLevel.Status,
LogLevel.Status,
LogLevel.Trace,
LogLevel.Trace,
LogLevel.Trace,
LogLevel.Trace
};
#if _DEBUG
internal static void WaitForFinalizers(Object sender, EventArgs e)
{
if (!m_registryChecked) {
CheckRegistry();
}
if (m_correctnessWarnings) {
GC.GetTotalMemory(true);
GC.WaitForPendingFinalizers();
}
}
#endif
#else
[System.Runtime.InteropServices.DllImport(Win32Native.KERNEL32), Conditional("_DEBUG")]
internal static extern void DebugBreak();
#endif // WIN32
[Conditional("_DEBUG")]
static public void Assert(bool condition, String message) {
#if WIN32
#if _DEBUG
// Speed up debug builds marginally by avoiding the garbage from
// concatinating "BCL Assert: " and the message.
if (!condition)
System.Diagnostics.Assert.Check(condition, "BCL Assert: "+message, message);
#endif
#else
if (!condition)
{
Console.WriteLine("BCL Assert: (temp IA64) "+message);
DebugBreak();
}
#endif
}
[Conditional("_LOGGING")]
static public void Log(String message) {
#if WIN32
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
if (!m_registryChecked) {
CheckRegistry();
}
System.Diagnostics.Log.Trace(message);
System.Diagnostics.Log.Trace(Environment.NewLine);
#endif // WIN32
}
[Conditional("_LOGGING")]
static public void Log(String switchName, String message) {
#if WIN32
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
if (!m_registryChecked) {
CheckRegistry();
}
try {
LogSwitch ls;
ls = LogSwitch.GetSwitch(switchName);
if (ls!=null) {
System.Diagnostics.Log.Trace(ls,message);
System.Diagnostics.Log.Trace(ls,Environment.NewLine);
}
} catch (Exception) {
System.Diagnostics.Log.Trace("Exception thrown in logging." + Environment.NewLine);
System.Diagnostics.Log.Trace("Switch was: " + ((switchName==null)?"<null>":switchName) + Environment.NewLine);
System.Diagnostics.Log.Trace("Message was: " + ((message==null)?"<null>":message) + Environment.NewLine);
}
#endif // WIN32
}
//
// This code gets called during security startup, so we can't go through Marshal to get the values. This is
// just a small helper in native code instead of that.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static int GetRegistryValue(out bool loggingEnabled, out bool logToConsole, out int logLevel, out bool perfWarnings, out bool correctnessWarnings);
private static void CheckRegistry() {
#if WIN32
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
if (m_registryChecked) {
return;
}
m_registryChecked = true;
bool loggingEnabled;
bool logToConsole;
int logLevel;
int facilityValue;
facilityValue = GetRegistryValue(out loggingEnabled, out logToConsole, out logLevel, out m_perfWarnings, out m_correctnessWarnings);
// Note we can get into some recursive situations where we call
// ourseves recursively through the .cctor. That's why we have the
// check for levelConversions == null.
if (loggingEnabled && levelConversions!=null) {
try {
//The values returned for the logging levels in the registry don't map nicely onto the
//values which we support internally (which are an approximation of the ones that
//the System.Diagnostics namespace uses) so we have a quick map.
Assert(logLevel>=0 && logLevel<=10, "logLevel>=0 && logLevel<=10");
logLevel = (int)levelConversions[logLevel];
if (facilityValue>0) {
for (int i=0; i<switches.Length; i++) {
if ((switches[i].value & facilityValue)!=0) {
LogSwitch L = new LogSwitch(switches[i].name, switches[i].name, System.Diagnostics.Log.GlobalSwitch);
L.MinimumLevel = (LoggingLevels)logLevel;
}
}
System.Diagnostics.Log.GlobalSwitch.MinimumLevel = (LoggingLevels)logLevel;
System.Diagnostics.Log.IsConsoleEnabled = logToConsole;
}
} catch (Exception) {
//Silently eat any exceptions.
}
}
#endif // WIN32
}
internal static bool CheckEnabled(String switchName) {
#if WIN32
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return false;
if (!m_registryChecked)
CheckRegistry();
LogSwitch logSwitch = LogSwitch.GetSwitch(switchName);
if (logSwitch==null) {
return false;
}
return ((int)logSwitch.MinimumLevel<=(int)LogLevel.Trace);
#else
return false;
#endif // WIN32
}
private static bool CheckEnabled(String switchName, LogLevel level, out LogSwitch logSwitch) {
#if WIN32
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
{
logSwitch = null;
return false;
}
logSwitch = LogSwitch.GetSwitch(switchName);
if (logSwitch==null) {
return false;
}
return ((int)logSwitch.MinimumLevel<=(int)level);
#else
logSwitch = null;
return false;
#endif // WIN32
}
[Conditional("_LOGGING")]
public static void Log(String switchName, LogLevel level, params Object[]messages) {
#if WIN32
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
//Add code to check if logging is enabled in the registry.
LogSwitch logSwitch;
if (!m_registryChecked) {
CheckRegistry();
}
if (!CheckEnabled(switchName, level, out logSwitch)) {
return;
}
StringBuilder sb = new StringBuilder();
for (int i=0; i<messages.Length; i++) {
String s;
try {
if (messages[i]==null) {
s = "<null>";
} else {
s = messages[i].ToString();
}
} catch (Exception) {
s = "<unable to convert>";
}
sb.Append(s);
}
System.Diagnostics.Log.LogMessage((LoggingLevels)((int)level), logSwitch, sb.ToString());
#endif // WIN32
}
[Conditional("_LOGGING")]
public static void Trace(String switchName, params Object[]messages) {
#if WIN32
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
//Add code to check if logging is enabled in the registry.
LogSwitch logSwitch;
if (!m_registryChecked) {
CheckRegistry();
}
if (!CheckEnabled(switchName, LogLevel.Trace, out logSwitch)) {
return;
}
StringBuilder sb = new StringBuilder();
for (int i=0; i<messages.Length; i++) {
String s;
try {
if (messages[i]==null) {
s = "<null>";
} else {
s = messages[i].ToString();
}
} catch (Exception) {
s = "<unable to convert>";
}
sb.Append(s);
}
sb.Append(Environment.NewLine);
System.Diagnostics.Log.LogMessage(LoggingLevels.TraceLevel0, logSwitch, sb.ToString());
#endif // WIN32
}
[Conditional("_LOGGING")]
public static void DumpStack(String switchName) {
#if WIN32
LogSwitch logSwitch;
if (!m_registryChecked) {
CheckRegistry();
}
if (!CheckEnabled(switchName, LogLevel.Trace, out logSwitch)) {
return;
}
StackTrace trace = new StackTrace();
System.Diagnostics.Log.LogMessage(LoggingLevels.TraceLevel0, logSwitch, trace.ToString());
#endif // WIN32
}
// For logging errors related to the console - we often can't expect to
// write to stdout if it doesn't exist.
[Conditional("_DEBUG")]
internal static void ConsoleError(String msg)
{
#if WIN32
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
// Bonk security - make it work.
if (m_MakeConsoleErrorLoggingWork == null) {
PermissionSet perms = new PermissionSet();
perms.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
perms.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess, Path.GetFullPath(".")));
m_MakeConsoleErrorLoggingWork = perms;
}
m_MakeConsoleErrorLoggingWork.Assert();
TextWriter err = File.AppendText("ConsoleErrors.log");
err.WriteLine(msg);
err.Close();
#endif // WIN32
}
// For perf-related asserts. On a debug build, set the registry key
// BCLPerfWarnings to non-zero.
[Conditional("_DEBUG")]
internal static void Perf(bool expr, String msg)
{
#if WIN32
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
if (!m_registryChecked)
CheckRegistry();
if (!m_perfWarnings)
return;
if (!expr) {
Log("PERF", "BCL Perf Warning: "+msg);
}
System.Diagnostics.Assert.Check(expr, "BCL Perf Warning: Your perf may be less than perfect because...", msg);
#endif // WIN32
}
// For correctness-related asserts. On a debug build, set the registry key
// BCLCorrectnessWarnings to non-zero.
[Conditional("_DEBUG")]
internal static void Correctness(bool expr, String msg)
{
#if WIN32
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
if (!m_registryChecked)
CheckRegistry();
if (!m_correctnessWarnings)
return;
#if _DEBUG
if (!m_domainUnloadAdded) {
m_domainUnloadAdded = true;
AppDomain.CurrentDomain.DomainUnload += new EventHandler(WaitForFinalizers);
}
#endif
if (!expr) {
Log("CORRECTNESS", "BCL Correctness Warning: "+msg);
}
System.Diagnostics.Assert.Check(expr, "BCL Correctness Warning: Your program may not work because...", msg);
#endif // WIN32
}
internal static bool CorrectnessEnabled()
{
#if WIN32
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return false;
if (!m_registryChecked)
CheckRegistry();
return m_correctnessWarnings;
#else
return false;
#endif // WIN32
}
}
}
+248
View File
@@ -0,0 +1,248 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: BitConverter
**
**
**
** Purpose: Allows developers to view the base data types as
** an arbitrary array of bits.
**
** Date: August 9, 1998
**
===========================================================*/
namespace System {
using System;
using System.Runtime.CompilerServices;
// The BitConverter class contains methods for
// converting an array of bytes to one of the base data
// types, as well as for converting a base data type to an
// array of bytes.
//
// Only statics, does not need to be marked with the serializable attribute
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter"]/*' />
public sealed class BitConverter {
// This field indicates the "endianess" of the architecture.
// The value is set to true if the architecture is
// little endian; false if it is big endian.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.IsLittleEndian"]/*' />
public static readonly bool IsLittleEndian;
static BitConverter() {
#if BIGENDIAN
IsLittleEndian = false;
#else
IsLittleEndian = true;
#endif
BCLDebug.Assert((GetBytes((short)0xF)[0] == 0xF) == IsLittleEndian,
"[BitConverter.cctor](GetBytes((short)0xF)[0] == 0xF) == IsLittleEndian");
}
// This class only contains static methods and may not be instantiated.
private BitConverter() {
}
// Converts a byte into an array of bytes with length one.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.GetBytes"]/*' />
public static byte[] GetBytes(bool value) {
byte[] r = new byte[1];
r[0] = (value ? (byte)Boolean.True : (byte)Boolean.False );
return r;
}
// Converts a char into an array of bytes with length two.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.GetBytes1"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern byte[] GetBytes(char value);
// Converts a short into an array of bytes with length
// two.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.GetBytes2"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern byte[] GetBytes(short value);
// Converts an int into an array of bytes with length
// four.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.GetBytes3"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern byte[] GetBytes(int value);
// Converts a long into an array of bytes with length
// eight.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.GetBytes4"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern byte[] GetBytes(long value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern byte[] GetUInt16Bytes(ushort value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern byte[] GetUInt32Bytes(uint value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern byte[] GetUInt64Bytes(ulong value);
// Converts an ushort into an array of bytes with
// length two.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.GetBytes5"]/*' />
[CLSCompliant(false)]
public static byte[] GetBytes(ushort value) {
return GetUInt16Bytes(value);
}
// Converts an uint into an array of bytes with
// length four.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.GetBytes6"]/*' />
[CLSCompliant(false)]
public static byte[] GetBytes(uint value) {
return GetUInt32Bytes(value);
}
// Converts an unsigned long into an array of bytes with
// length eight.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.GetBytes7"]/*' />
[CLSCompliant(false)]
public static byte[] GetBytes(ulong value) {
return GetUInt64Bytes(value);
}
// Converts a float into an array of bytes with length
// four.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.GetBytes8"]/*' />
public unsafe static byte[] GetBytes(float value)
{
byte[] bytes = new byte[4];
fixed(byte* b = bytes)
*((float*)b) = value;
return bytes;
}
// Converts a double into an array of bytes with length
// eight.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.GetBytes9"]/*' />
public unsafe static byte[] GetBytes(double value)
{
byte[] bytes = new byte[8];
fixed(byte* b = bytes)
*((double*)b) = value;
return bytes;
}
// Converts an array of bytes into a char.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.ToChar"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern char ToChar(byte[] value, int startIndex);
// Converts an array of bytes into a short.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.ToInt16"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern short ToInt16(byte[] value, int startIndex);
// Converts an array of bytes into an int.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.ToInt32"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int ToInt32 (byte[]value, int startIndex);
// Converts an array of bytes into a long.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.ToInt64"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern long ToInt64 (byte[] value, int startIndex);
// Converts an array of bytes into an ushort.
//
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.ToUInt16"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall), CLSCompliant(false)]
public static extern ushort ToUInt16(byte[] value, int startIndex);
// Converts an array of bytes into an uint.
//
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.ToUInt32"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall), CLSCompliant(false)]
public static extern uint ToUInt32(byte[] value, int startIndex);
// Converts an array of bytes into an unsigned long.
//
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.ToUInt64"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall), CLSCompliant(false)]
public static extern ulong ToUInt64(byte[] value, int startIndex);
// Converts an array of bytes into a float.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.ToSingle"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float ToSingle (byte[]value, int startIndex);
// Converts an array of bytes into a double.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.ToDouble"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double ToDouble (byte []value, int startIndex);
// Converts an array of bytes into a String.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.ToString"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern String ToString (byte[] value, int startIndex, int length);
// Converts an array of bytes into a String.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.ToString1"]/*' />
public static String ToString(byte [] value) {
if (value == null)
throw new ArgumentNullException("value");
return ToString(value, 0, value.Length);
}
// Converts an array of bytes into a String.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.ToString2"]/*' />
public static String ToString (byte [] value, int startIndex) {
if (value == null)
throw new ArgumentNullException("value");
return ToString(value, startIndex, value.Length - startIndex);
}
/*==================================ToBoolean===================================
**Action: Convert an array of bytes to a boolean value. We treat this array
** as if the first 4 bytes were an Int4 an operate on this value.
**Returns: True if the Int4 value of the first 4 bytes is non-zero.
**Arguments: value -- The byte array
** startIndex -- The position within the array.
**Exceptions: See ToInt4.
==============================================================================*/
// Converts an array of bytes into a boolean.
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.ToBoolean"]/*' />
public static bool ToBoolean(byte[]value, int startIndex) {
if (value==null)
throw new ArgumentNullException("value");
if (startIndex < 0)
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (startIndex > value.Length - 1)
throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_Index"));
return (value[startIndex]==0)?false:true;
}
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.DoubleToInt64Bits"]/*' />
public static unsafe long DoubleToInt64Bits(double value) {
return *((long *)&value);
}
/// <include file='doc\BitConverter.uex' path='docs/doc[@for="BitConverter.Int64BitsToDouble"]/*' />
public static unsafe double Int64BitsToDouble(long value) {
return *((double *)&value);
}
}
}
+276
View File
@@ -0,0 +1,276 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: Boolean
**
**
**
** Purpose: The boolean class serves as a wrapper for the primitive
** type boolean.
**
** Date: August 8, 1998
**
===========================================================*/
namespace System {
using System;
using System.Globalization;
// The Boolean class provides the
// object representation of the boolean primitive type.
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean"]/*' />
[Serializable()]
public struct Boolean : IComparable, IConvertible {
//
// Member Variables
//
private bool m_value;
//
// Public Constants
//
// The true value.
//
internal const int True = 1;
// The false value.
//
internal const int False = 0;
// The string representation of true.
//
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.TrueString"]/*' />
public static readonly String TrueString = "True";
// The string representation of false.
//
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.FalseString"]/*' />
public static readonly String FalseString = "False";
//
// Overriden Instance Methods
//
/*=================================GetHashCode==================================
**Args: None
**Returns: 1 or 0 depending on whether this instance represents true or false.
**Exceptions: None
**Overriden From: Value
==============================================================================*/
// Provides a hash code for this instance.
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.GetHashCode"]/*' />
public override int GetHashCode() {
return (m_value)?True:False;
}
/*===================================ToString===================================
**Args: None
**Returns: "True" or "False" depending on the state of the boolean.
**Exceptions: None.
==============================================================================*/
// Converts the boolean value of this instance to a String.
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.ToString"]/*' />
public override String ToString() {
if (false == m_value) {
return FalseString;
}
return TrueString;
}
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.ToString1"]/*' />
public String ToString(IFormatProvider provider) {
if (false == m_value) {
return FalseString;
}
return TrueString;
}
// Determines whether two Boolean objects are equal.
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.Equals"]/*' />
public override bool Equals (Object obj) {
//If it's not a boolean, we're definitely not equal
if (!(obj is Boolean)) {
return false;
}
return (m_value==((Boolean)obj).m_value);
}
// Compares this object to another object, returning an integer that
// indicates the relationship. For booleans, false sorts before true.
// null is considered to be less than any instance.
// If object is not of type boolean, this method throws an ArgumentException.
//
// Returns a value less than zero if this object
//
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.CompareTo"]/*' />
public int CompareTo(Object obj) {
if (obj==null) {
return 1;
}
if (!(obj is Boolean)) {
throw new ArgumentException (Environment.GetResourceString("Arg_MustBeBoolean"));
}
if (m_value==((Boolean)obj).m_value) {
return 0;
} else if (m_value==false) {
return -1;
}
return 1;
}
//
// Static Methods
//
// Determines whether a String represents true or false.
//
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.Parse"]/*' />
public static bool Parse (String value) {
if (value==null) throw new ArgumentNullException("value");
// For perf reasons, let's first see if they're equal, then do the
// trim to get rid of white space, and check again.
if (0==String.Compare(value, TrueString,true, CultureInfo.InvariantCulture))
return true;
if (0==String.Compare(value,FalseString,true, CultureInfo.InvariantCulture))
return false;
value = value.Trim(); // Remove leading & trailing white space.
if (0==String.Compare(value, TrueString,true, CultureInfo.InvariantCulture))
return true;
if (0==String.Compare(value,FalseString,true, CultureInfo.InvariantCulture))
return false;
throw new FormatException(Environment.GetResourceString("Format_BadBoolean"));
}
//
// IValue implementation
//
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.GetTypeCode"]/*' />
public TypeCode GetTypeCode() {
return TypeCode.Boolean;
}
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.IConvertible.ToBoolean"]/*' />
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider) {
return m_value;
}
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.IConvertible.ToChar"]/*' />
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider) {
throw new InvalidCastException(String.Format(Environment.GetResourceString("InvalidCast_FromTo"), "Boolean", "Char"));
}
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.IConvertible.ToSByte"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
sbyte IConvertible.ToSByte(IFormatProvider provider) {
return Convert.ToSByte(m_value);
}
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.IConvertible.ToByte"]/*' />
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider) {
return Convert.ToByte(m_value);
}
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.IConvertible.ToInt16"]/*' />
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider) {
return Convert.ToInt16(m_value);
}
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.IConvertible.ToUInt16"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
ushort IConvertible.ToUInt16(IFormatProvider provider) {
return Convert.ToUInt16(m_value);
}
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.IConvertible.ToInt32"]/*' />
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider) {
return Convert.ToInt32(m_value);
}
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.IConvertible.ToUInt32"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
uint IConvertible.ToUInt32(IFormatProvider provider) {
return Convert.ToUInt32(m_value);
}
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.IConvertible.ToInt64"]/*' />
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider) {
return Convert.ToInt64(m_value);
}
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.IConvertible.ToUInt64"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
ulong IConvertible.ToUInt64(IFormatProvider provider) {
return Convert.ToUInt64(m_value);
}
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.IConvertible.ToSingle"]/*' />
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider) {
return Convert.ToSingle(m_value);
}
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.IConvertible.ToDouble"]/*' />
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider) {
return Convert.ToDouble(m_value);
}
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.IConvertible.ToDecimal"]/*' />
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider) {
return Convert.ToDecimal(m_value);
}
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.IConvertible.ToDateTime"]/*' />
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider) {
throw new InvalidCastException(String.Format(Environment.GetResourceString("InvalidCast_FromTo"), "Boolean", "DateTime"));
}
/// <include file='doc\Boolean.uex' path='docs/doc[@for="Boolean.IConvertible.ToType"]/*' />
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider) {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
//
// This is just designed to prevent compiler warnings.
// This field is used from native, but we need to prevent the compiler warnings.
//
#if _DEBUG
private void DontTouchThis() {
m_value = m_value;
}
#endif
}
}
+71
View File
@@ -0,0 +1,71 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace System {
//Only contains static methods. Does not require serialization
using System;
using System.Runtime.CompilerServices;
/// <include file='doc\Buffer.uex' path='docs/doc[@for="Buffer"]/*' />
public sealed class Buffer
{
private Buffer() {
}
// Copies from one primitive array to another primitive array without
// respecting types. This calls memmove internally.
/// <include file='doc\Buffer.uex' path='docs/doc[@for="Buffer.BlockCopy"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void BlockCopy(Array src, int srcOffset,
Array dst, int dstOffset, int count);
// A very simple and efficient array copy that assumes all of the
// parameter validation has already been done. All counts here are
// in bytes.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void InternalBlockCopy(Array src, int srcOffset,
Array dst, int dstOffset, int count);
// Gets a particular byte out of the array. The array must be an
// array of primitives.
//
// This essentially does the following:
// return ((byte*)array) + index.
//
/// <include file='doc\Buffer.uex' path='docs/doc[@for="Buffer.GetByte"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern byte GetByte(Array array, int index);
// Sets a particular byte in an the array. The array must be an
// array of primitives.
//
// This essentially does the following:
// *(((byte*)array) + index) = value.
//
/// <include file='doc\Buffer.uex' path='docs/doc[@for="Buffer.SetByte"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void SetByte(Array array, int index, byte value);
// Gets a particular byte out of the array. The array must be an
// array of primitives.
//
// This essentially does the following:
// return array.length * sizeof(array.UnderlyingElementType).
//
/// <include file='doc\Buffer.uex' path='docs/doc[@for="Buffer.ByteLength"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int ByteLength(Array array);
}
}
+248
View File
@@ -0,0 +1,248 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: Byte
**
**
**
** Purpose: This class will encapsulate a byte and provide an
** Object representation of it.
**
** Date: August 3, 1998
**
===========================================================*/
namespace System {
using System;
using System.Globalization;
using System.Runtime.InteropServices;
// The Byte class extends the Value class and
// provides object representation of the byte primitive type.
//
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte"]/*' />
[Serializable, System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] public struct Byte : IComparable, IFormattable, IConvertible
{
private byte m_value;
// The maximum value that a Byte may represent: 255.
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.MaxValue"]/*' />
public const byte MaxValue = (byte)0xFF;
// The minimum value that a Byte may represent: 0.
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.MinValue"]/*' />
public const byte MinValue = 0;
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type byte, this method throws an ArgumentException.
//
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.CompareTo"]/*' />
public int CompareTo(Object value) {
if (value == null) {
return 1;
}
if (!(value is Byte)) {
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeByte"));
}
return m_value - (((Byte)value).m_value);
}
// Determines whether two Byte objects are equal.
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.Equals"]/*' />
public override bool Equals(Object obj) {
if (!(obj is Byte)) {
return false;
}
return m_value == ((Byte)obj).m_value;
}
// Gets a hash code for this instance.
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.GetHashCode"]/*' />
public override int GetHashCode() {
return m_value;
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.Parse"]/*' />
public static byte Parse(String s) {
return Parse(s, NumberStyles.Integer, null);
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.Parse1"]/*' />
public static byte Parse(String s, NumberStyles style) {
NumberFormatInfo.ValidateParseStyle(style);
return Parse(s, style, null);
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.Parse2"]/*' />
public static byte Parse(String s, IFormatProvider provider) {
return Parse(s, NumberStyles.Integer, provider);
}
// Parses an unsigned byte from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.Parse3"]/*' />
public static byte Parse(String s, NumberStyles style, IFormatProvider provider) {
NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
NumberFormatInfo.ValidateParseStyle(style);
int i = Number.ParseInt32(s, style, info);
if (i < MinValue || i > MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_Byte"));
return (byte)i;
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.ToString"]/*' />
public override String ToString() {
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.ToString1"]/*' />
public String ToString(String format) {
return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.ToString2"]/*' />
public String ToString(IFormatProvider provider) {
return ToString(null, provider);
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.ToString3"]/*' />
public String ToString(String format, IFormatProvider provider) {
return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
//
// IValue implementation
//
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.GetTypeCode"]/*' />
public TypeCode GetTypeCode() {
return TypeCode.Byte;
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.IConvertible.ToBoolean"]/*' />
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider) {
return Convert.ToBoolean(m_value);
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.IConvertible.ToChar"]/*' />
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider) {
return Convert.ToChar(m_value);
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.IConvertible.ToSByte"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
sbyte IConvertible.ToSByte(IFormatProvider provider) {
return Convert.ToSByte(m_value);
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.IConvertible.ToByte"]/*' />
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider) {
return m_value;
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.IConvertible.ToInt16"]/*' />
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider) {
return Convert.ToInt16(m_value);
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.IConvertible.ToUInt16"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
ushort IConvertible.ToUInt16(IFormatProvider provider) {
return Convert.ToUInt16(m_value);
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.IConvertible.ToInt32"]/*' />
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider) {
return Convert.ToInt32(m_value);
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.IConvertible.ToUInt32"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
uint IConvertible.ToUInt32(IFormatProvider provider) {
return Convert.ToUInt32(m_value);
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.IConvertible.ToInt64"]/*' />
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider) {
return Convert.ToInt64(m_value);
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.IConvertible.ToUInt64"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
ulong IConvertible.ToUInt64(IFormatProvider provider) {
return Convert.ToUInt64(m_value);
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.IConvertible.ToSingle"]/*' />
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider) {
return Convert.ToSingle(m_value);
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.IConvertible.ToDouble"]/*' />
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider) {
return Convert.ToDouble(m_value);
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.IConvertible.ToDecimal"]/*' />
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider) {
return Convert.ToDecimal(m_value);
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.IConvertible.ToDateTime"]/*' />
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider) {
throw new InvalidCastException(String.Format(Environment.GetResourceString("InvalidCast_FromTo"), "Byte", "DateTime"));
}
/// <include file='doc\Byte.uex' path='docs/doc[@for="Byte.IConvertible.ToType"]/*' />
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider) {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
//
// This is just designed to prevent compiler warnings.
// This field is used from native, but we need to prevent the compiler warnings.
//
#if _DEBUG
private void DontTouchThis() {
m_value = m_value;
}
#endif
}
}
@@ -0,0 +1,65 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: CannotUnloadAppDomainException
**
**
**
** Purpose: Exception class for failed attempt to unload an AppDomain.
**
** Date: September 15, 2000
**
=============================================================================*/
namespace System {
using System.Runtime.Serialization;
/// <include file='doc\CannotUnloadAppDomainException.uex' path='docs/doc[@for="CannotUnloadAppDomainException"]/*' />
[Serializable()] public class CannotUnloadAppDomainException : SystemException {
/// <include file='doc\CannotUnloadAppDomainException.uex' path='docs/doc[@for="CannotUnloadAppDomainException.CannotUnloadAppDomainException"]/*' />
public CannotUnloadAppDomainException()
: base(Environment.GetResourceString("Arg_CannotUnloadAppDomainException")) {
SetErrorCode(__HResults.COR_E_CANNOTUNLOADAPPDOMAIN);
}
/// <include file='doc\CannotUnloadAppDomainException.uex' path='docs/doc[@for="CannotUnloadAppDomainException.CannotUnloadAppDomainException1"]/*' />
public CannotUnloadAppDomainException(String message)
: base(message) {
SetErrorCode(__HResults.COR_E_CANNOTUNLOADAPPDOMAIN);
}
/// <include file='doc\CannotUnloadAppDomainException.uex' path='docs/doc[@for="CannotUnloadAppDomainException.CannotUnloadAppDomainException2"]/*' />
public CannotUnloadAppDomainException(String message, Exception innerException)
: base(message, innerException) {
SetErrorCode(__HResults.COR_E_CANNOTUNLOADAPPDOMAIN);
}
//
//This constructor is required for serialization.
//
/// <include file='doc\CannotUnloadAppDomainException.uex' path='docs/doc[@for="CannotUnloadAppDomainException.CannotUnloadAppDomainException3"]/*' />
protected CannotUnloadAppDomainException(SerializationInfo info, StreamingContext context) : base(info, context) {
}
}
}
+482
View File
@@ -0,0 +1,482 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: CfgParser
**
**
** Updated:
**
** Purpose: XMLParser and Tree builder internal to BCL
**
** Date: October, 29, 1999
**
===========================================================*/
//
// These are managed definitions of interfaces used in the shim for XML Parsing
// If you make any change please make a correspoding change in \src\dlls\shim\managedhelper.h
//
//
//
namespace System
{
using System.Runtime.InteropServices;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
using System.Security;
using System.Globalization;
[Serializable]
internal enum ConfigEvents
{
StartDocument = 0,
StartDTD = StartDocument + 1,
EndDTD = StartDTD + 1,
StartDTDSubset = EndDTD + 1,
EndDTDSubset = StartDTDSubset + 1,
EndProlog = EndDTDSubset + 1,
StartEntity = EndProlog + 1,
EndEntity = StartEntity + 1,
EndDocument = EndEntity + 1,
DataAvailable = EndDocument + 1,
LastEvent = DataAvailable
}
[Serializable]
internal enum ConfigNodeType
{
Element = 1,
Attribute = Element + 1,
Pi = Attribute + 1,
XmlDecl = Pi + 1,
DocType = XmlDecl + 1,
DTDAttribute = DocType + 1,
EntityDecl = DTDAttribute + 1,
ElementDecl = EntityDecl + 1,
AttlistDecl = ElementDecl + 1,
Notation = AttlistDecl + 1,
Group = Notation + 1,
IncludeSect = Group + 1,
PCData = IncludeSect + 1,
CData = PCData + 1,
IgnoreSect = CData + 1,
Comment = IgnoreSect + 1,
EntityRef = Comment + 1,
Whitespace = EntityRef + 1,
Name = Whitespace + 1,
NMToken = Name + 1,
String = NMToken + 1,
Peref = String + 1,
Model = Peref + 1,
ATTDef = Model + 1,
ATTType = ATTDef + 1,
ATTPresence = ATTType + 1,
DTDSubset = ATTPresence + 1,
LastNodeType = DTDSubset + 1
}
[Serializable]
internal enum ConfigNodeSubType
{
Version = (int)ConfigNodeType.LastNodeType,
Encoding = Version + 1,
Standalone = Encoding + 1,
NS = Standalone + 1,
XMLSpace = NS + 1,
XMLLang = XMLSpace + 1,
System = XMLLang + 1,
Public = System + 1,
NData = Public + 1,
AtCData = NData + 1,
AtId = AtCData + 1,
AtIdref = AtId + 1,
AtIdrefs = AtIdref + 1,
AtEntity = AtIdrefs + 1,
AtEntities = AtEntity + 1,
AtNmToken = AtEntities + 1,
AtNmTokens = AtNmToken + 1,
AtNotation = AtNmTokens + 1,
AtRequired = AtNotation + 1,
AtImplied = AtRequired + 1,
AtFixed = AtImplied + 1,
PentityDecl = AtFixed + 1,
Empty = PentityDecl + 1,
Any = Empty + 1,
Mixed = Any + 1,
Sequence = Mixed + 1,
Choice = Sequence + 1,
Star = Choice + 1,
Plus = Star + 1,
Questionmark = Plus + 1,
LastSubNodeType = Questionmark + 1
}
internal interface IConfigHandler {
void NotifyEvent(ConfigEvents nEvent);
void BeginChildren(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)] String text,
int textLength,
int prefixLength);
void EndChildren(int fEmpty,
int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)] String text,
int textLength,
int prefixLength);
void Error(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength);
void CreateNode(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength);
void CreateAttribute(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength);
}
internal class ConfigServer
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void RunParser(IConfigHandler factory, String fileName);
}
// Class used to build a DOM like tree of parsed XML
internal class ConfigTreeParser : IConfigHandler
{
ConfigNode rootNode = null;
ConfigNode currentNode = null;
String lastProcessed = null;
String fileName = null;
int attributeEntry;
String key = null;
String [] treeRootPath = null; // element to start tree
bool parsing = false;
int depth = 0;
int pathDepth = 0;
int searchDepth = 0;
bool bNoSearchPath = false;
internal ConfigNode Parse(String fileName)
{
return Parse(fileName, null);
}
// NOTE: This parser takes a path eg. /configuration/system.runtime.remoting
// and will return a node which matches this.
internal ConfigNode Parse(String fileName, String configPath)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
this.fileName = fileName;
if (configPath[0] == '/'){
treeRootPath = configPath.Substring(1).Split('/');
pathDepth = treeRootPath.Length - 1;
bNoSearchPath = false;
}
else{
treeRootPath = new String[1];
treeRootPath[0] = configPath;
bNoSearchPath = true;
}
(new FileIOPermission( FileIOPermissionAccess.Read, System.IO.Path.GetFullPathInternal( fileName ) )).Demand();
(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Assert();
try
{
ConfigServer.RunParser(this, fileName);
}
catch(Exception inner) {
throw new ApplicationException(String.Format(Environment.GetResourceString("XML_Syntax_InvalidSyntaxInFile"),
fileName,
lastProcessed),
inner);
}
return rootNode;
}
public void NotifyEvent(ConfigEvents nEvent)
{
BCLDebug.Trace("REMOTE", "NotifyEvent "+((Enum)nEvent).ToString()+"\n");
}
public void BeginChildren(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)] String text,
int textLength,
int prefixLength)
{
//Trace("BeginChildren",size,subType,nType,terminal,text,textLength,prefixLength,0);
if (!parsing &&
(!bNoSearchPath
&& depth == (searchDepth + 1)
&& String.Compare(text, treeRootPath[searchDepth], false, CultureInfo.InvariantCulture) == 0))
{
searchDepth++;
}
}
public void EndChildren(int fEmpty,
int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)] String text,
int textLength,
int prefixLength)
{
lastProcessed = "</"+text+">";
if (parsing)
{
//Trace("EndChildren",size,subType,nType,terminal,text,textLength,prefixLength,fEmpty);
if (currentNode == rootNode)
{
// End of section of tree which is parsed
parsing = false;
}
currentNode = currentNode.Parent;
}
else if (nType == ConfigNodeType.Element){
if(depth == searchDepth && String.Compare(text, treeRootPath[searchDepth - 1], false, CultureInfo.InvariantCulture) == 0)
{
searchDepth--;
depth--;
}
else
depth--;
}
}
public void Error(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength)
{
//Trace("Error",size,subType,nType,terminal,text,textLength,prefixLength,0);
}
public void CreateNode(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength)
{
//Trace("CreateNode",size,subType,nType,terminal,text,textLength,prefixLength,0);
if (nType == ConfigNodeType.Element)
{
// New Node
lastProcessed = "<"+text+">";
if (parsing
|| (bNoSearchPath &&
String.Compare(text, treeRootPath[0], true, CultureInfo.InvariantCulture) == 0)
|| (depth == searchDepth && searchDepth == pathDepth &&
String.Compare(text, treeRootPath[pathDepth], true, CultureInfo.InvariantCulture) == 0 ))
{
parsing = true;
ConfigNode parentNode = currentNode;
currentNode = new ConfigNode(text, parentNode);
if (rootNode == null)
rootNode = currentNode;
else
parentNode.AddChild(currentNode);
}
else if (nType == ConfigNodeType.PCData)
{
// Data node
currentNode.Value = text;
}
else
depth++;
}
}
public void CreateAttribute(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength)
{
//Trace("CreateAttribute",size,subType,nType,terminal,text,textLength,prefixLength,0);
if (parsing)
{
// if the value of the attribute is null, the parser doesn't come back, so need to store the attribute when the
// attribute name is encountered
if (nType == ConfigNodeType.Attribute)
{
attributeEntry = currentNode.AddAttribute(text, "");
key = text;
}
else if (nType == ConfigNodeType.PCData)
{
currentNode.ReplaceAttribute(attributeEntry, key, text);
}
else
throw new ApplicationException(String.Format(Environment.GetResourceString("XML_Syntax_InvalidSyntaxInFile"),fileName,lastProcessed));
}
}
[System.Diagnostics.Conditional("_LOGGING")]
private void Trace(String name,
int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength, int fEmpty)
{
BCLDebug.Trace("REMOTE","Node "+name);
BCLDebug.Trace("REMOTE","text "+text);
BCLDebug.Trace("REMOTE","textLength "+textLength);
BCLDebug.Trace("REMOTE","size "+size);
BCLDebug.Trace("REMOTE","subType "+((Enum)subType).ToString());
BCLDebug.Trace("REMOTE","nType "+((Enum)nType).ToString());
BCLDebug.Trace("REMOTE","terminal "+terminal);
BCLDebug.Trace("REMOTE","prefixLength "+prefixLength);
BCLDebug.Trace("REMOTE","fEmpty "+fEmpty+"\n");
}
}
// Node in Tree produced by ConfigTreeParser
internal class ConfigNode
{
String m_name = null;
String m_value = null;
ConfigNode m_parent = null;
ArrayList m_children = new ArrayList(5);
ArrayList m_attributes = new ArrayList(5);
internal ConfigNode(String name, ConfigNode parent)
{
m_name = name;
m_parent = parent;
}
internal String Name
{
get {return m_name;}
}
internal String Value
{
get {return m_value;}
set {m_value = value;}
}
internal ConfigNode Parent
{
get {return m_parent;}
}
internal ArrayList Children
{
get {return m_children;}
}
internal ArrayList Attributes
{
get {return m_attributes;}
}
internal void AddChild(ConfigNode child)
{
child.m_parent = this;
m_children.Add(child);
}
internal int AddAttribute(String key, String value)
{
m_attributes.Add(new DictionaryEntry(key, value));
return m_attributes.Count-1;
}
internal void ReplaceAttribute(int index, String key, String value)
{
m_attributes[index] = new DictionaryEntry(key, value);
}
[System.Diagnostics.Conditional("_LOGGING")]
internal void Trace()
{
BCLDebug.Trace("REMOTE","************ConfigNode************");
BCLDebug.Trace("REMOTE","Name = "+m_name);
if (m_value != null)
BCLDebug.Trace("REMOTE","Value = "+m_value);
if (m_parent != null)
BCLDebug.Trace("REMOTE","Parent = "+m_parent.Name);
for (int i=0; i<m_attributes.Count; i++)
{
DictionaryEntry de = (DictionaryEntry)m_attributes[i];
BCLDebug.Trace("REMOTE","Key = "+de.Key+" Value = "+de.Value);
}
for (int i=0; i<m_children.Count; i++)
{
((ConfigNode)m_children[i]).Trace();
}
}
}
}
+563
View File
@@ -0,0 +1,563 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: Char
**
**
**
** Purpose: This is the value class representing a Unicode character
** Char methods until we create this functionality.
**
** Date: August 3, 1998
**
===========================================================*/
namespace System {
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
/// <include file='doc\Char.uex' path='docs/doc[@for="Char"]/*' />
[Serializable, System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] public struct Char : IComparable, IConvertible {
//
// Member Variables
//
internal char m_value;
//
// Public Constants
//
// The maximum character value.
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.MaxValue"]/*' />
public const char MaxValue = (char) 0xFFFF;
// The minimum character value.
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.MinValue"]/*' />
public const char MinValue = (char) 0x00;
//
// Private Constants
//
//
// Overriden Instance Methods
//
// Calculate a hashcode for a 2 byte Unicode character.
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.GetHashCode"]/*' />
public override int GetHashCode() {
return (int)m_value | ((int)m_value << 16);
}
// Used for comparing two boxed Char objects.
//
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.Equals"]/*' />
public override bool Equals(Object obj) {
if (!(obj is Char)) {
return false;
}
return (m_value==((Char)obj).m_value);
}
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Char, this method throws an ArgumentException.
//
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.CompareTo"]/*' />
public int CompareTo(Object value) {
if (value==null) {
return 1;
}
if (!(value is Char)) {
throw new ArgumentException (Environment.GetResourceString("Arg_MustBeChar"));
}
return (m_value-((Char)value).m_value);
}
// Overrides System.Object.ToString.
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.ToString"]/*' />
public override String ToString() {
return Char.ToString(m_value);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.ToString2"]/*' />
public String ToString(IFormatProvider provider) {
return Char.ToString(m_value);
}
//
// Formatting Methods
//
/*===================================ToString===================================
**This static methods takes a character and returns the String representation of it.
==============================================================================*/
// Provides a string representation of a character.
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.ToString1"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern String ToString(char c);
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.Parse"]/*' />
public static char Parse(String s) {
if (s==null) {
throw new ArgumentNullException("s");
}
if (s.Length!=1) {
throw new FormatException(Environment.GetResourceString("Format_NeedSingleChar"));
}
return s[0];
}
//
// Static Methods
//
/*=================================ISDIGIT======================================
**A wrapper for Char. Returns a boolean indicating whether **
**character c is considered to be a digit. **
==============================================================================*/
// Determines whether a character is a digit.
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsDigit"]/*' />
public static bool IsDigit(char c) {
return CharacterInfo.IsDigit(c);
}
/*=================================ISLETTER=====================================
**A wrapper for Char. Returns a boolean indicating whether **
**character c is considered to be a letter. **
==============================================================================*/
// Determines whether a character is a letter.
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsLetter"]/*' />
public static bool IsLetter(char c) {
return CharacterInfo.IsLetter(c);
}
/*===============================ISWHITESPACE===================================
**A wrapper for Char. Returns a boolean indicating whether **
**character c is considered to be a whitespace character. **
==============================================================================*/
// Determines whether a character is whitespace.
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsWhiteSpace"]/*' />
public static bool IsWhiteSpace(char c) {
return CharacterInfo.IsWhiteSpace(c);
}
/*===================================IsUpper====================================
**Arguments: c -- the characater to be checked.
**Returns: True if c is an uppercase character.
==============================================================================*/
// Determines whether a character is upper-case.
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsUpper"]/*' />
public static bool IsUpper(char c) {
return CharacterInfo.IsUpper(c);
}
/*===================================IsLower====================================
**Arguments: c -- the characater to be checked.
**Returns: True if c is an lowercase character.
==============================================================================*/
// Determines whether a character is lower-case.
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsLower"]/*' />
public static bool IsLower(char c) {
return CharacterInfo.IsLower(c);
}
/*================================IsPunctuation=================================
**Arguments: c -- the characater to be checked.
**Returns: True if c is an punctuation mark
==============================================================================*/
// Determines whether a character is a punctuation mark.
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsPunctuation"]/*' />
public static bool IsPunctuation(char c){
return CharacterInfo.IsPunctuation(c);
}
// Determines whether a character is a letter or a digit.
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsLetterOrDigit"]/*' />
public static bool IsLetterOrDigit(char c) {
UnicodeCategory uc = CharacterInfo.GetUnicodeCategory(c);
return (uc == UnicodeCategory.UppercaseLetter
|| uc == UnicodeCategory.LowercaseLetter
|| uc == UnicodeCategory.TitlecaseLetter
|| uc == UnicodeCategory.ModifierLetter
|| uc == UnicodeCategory.OtherLetter
|| uc == UnicodeCategory.DecimalDigitNumber);
}
/*===================================ToUpper====================================
**
==============================================================================*/
// Converts a character to upper-case for the specified culture.
// <;<;Not fully implemented>;>;
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.ToUpper"]/*' />
public static char ToUpper(char c, CultureInfo culture) {
if (culture==null)
throw new ArgumentNullException("culture");
return culture.TextInfo.ToUpper(c);
}
/*=================================TOUPPER======================================
**A wrapper for Char.toUpperCase. Converts character c to its **
**uppercase equivalent. If c is already an uppercase character or is not an **
**alphabetic, nothing happens. **
==============================================================================*/
// Converts a character to upper-case for the default culture.
//
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.ToUpper1"]/*' />
public static char ToUpper(char c) {
return ToUpper(c, CultureInfo.CurrentCulture);
}
/*===================================ToLower====================================
**
==============================================================================*/
// Converts a character to lower-case for the specified culture.
// <;<;Not fully implemented>;>;
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.ToLower"]/*' />
public static char ToLower(char c, CultureInfo culture) {
if (culture==null)
throw new ArgumentNullException("culture");
return culture.TextInfo.ToLower(c);
}
/*=================================TOLOWER======================================
**A wrapper for Char.toLowerCase. Converts character c to its **
**lowercase equivalent. If c is already a lowercase character or is not an **
**alphabetic, nothing happens. **
==============================================================================*/
// Converts a character to lower-case for the default culture.
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.ToLower1"]/*' />
public static char ToLower(char c) {
return ToLower(c, CultureInfo.CurrentCulture);
}
//
// IValue implementation
//
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.GetTypeCode"]/*' />
public TypeCode GetTypeCode() {
return TypeCode.Char;
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IConvertible.ToBoolean"]/*' />
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider) {
throw new InvalidCastException(String.Format(Environment.GetResourceString("InvalidCast_FromTo"), "Char", "Boolean"));
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IConvertible.ToChar"]/*' />
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider) {
return m_value;
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IConvertible.ToSByte"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
sbyte IConvertible.ToSByte(IFormatProvider provider) {
return Convert.ToSByte(m_value);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IConvertible.ToByte"]/*' />
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider) {
return Convert.ToByte(m_value);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IConvertible.ToInt16"]/*' />
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider) {
return Convert.ToInt16(m_value);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IConvertible.ToUInt16"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
ushort IConvertible.ToUInt16(IFormatProvider provider) {
return Convert.ToUInt16(m_value);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IConvertible.ToInt32"]/*' />
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider) {
return Convert.ToInt32(m_value);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IConvertible.ToUInt32"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
uint IConvertible.ToUInt32(IFormatProvider provider) {
return Convert.ToUInt32(m_value);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IConvertible.ToInt64"]/*' />
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider) {
return Convert.ToInt64(m_value);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IConvertible.ToUInt64"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
ulong IConvertible.ToUInt64(IFormatProvider provider) {
return Convert.ToUInt64(m_value);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IConvertible.ToSingle"]/*' />
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider) {
throw new InvalidCastException(String.Format(Environment.GetResourceString("InvalidCast_FromTo"), "Char", "Single"));
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IConvertible.ToDouble"]/*' />
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider) {
throw new InvalidCastException(String.Format(Environment.GetResourceString("InvalidCast_FromTo"), "Char", "Double"));
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IConvertible.ToDecimal"]/*' />
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider) {
throw new InvalidCastException(String.Format(Environment.GetResourceString("InvalidCast_FromTo"), "Char", "Decimal"));
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IConvertible.ToDateTime"]/*' />
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider) {
throw new InvalidCastException(String.Format(Environment.GetResourceString("InvalidCast_FromTo"), "Char", "DateTime"));
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IConvertible.ToType"]/*' />
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider) {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsControl1"]/*' />
public static bool IsControl(char c)
{
return CharacterInfo.IsControl(c);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsControl"]/*' />
public static bool IsControl(String s, int index) {
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
return IsControl(s[index]);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsDigit1"]/*' />
public static bool IsDigit(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
return IsDigit(s[index]);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsLetter1"]/*' />
public static bool IsLetter(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
return IsLetter(s[index]);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsLetterOrDigit1"]/*' />
public static bool IsLetterOrDigit(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
return IsLetterOrDigit(s[index]);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsLower1"]/*' />
public static bool IsLower(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
return IsLower(s[index]);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsNumber"]/*' />
public static bool IsNumber(char c)
{
return CharacterInfo.IsNumber(c);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsNumber1"]/*' />
public static bool IsNumber(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
return IsNumber(s[index]);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsPunctuation1"]/*' />
public static bool IsPunctuation (String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
return IsPunctuation(s[index]);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsSeparator"]/*' />
public static bool IsSeparator(char c)
{
return CharacterInfo.IsSeparator(c);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsSeparator1"]/*' />
public static bool IsSeparator(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
return IsSeparator(s[index]);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsSurrogate"]/*' />
public static bool IsSurrogate(char c)
{
return CharacterInfo.IsSurrogate(c);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsSurrogate1"]/*' />
public static bool IsSurrogate(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
return IsSurrogate(s[index]);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsSymbol"]/*' />
public static bool IsSymbol(char c)
{
return CharacterInfo.IsSymbol(c);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsSymbol1"]/*' />
public static bool IsSymbol(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
return IsSymbol(s[index]);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsUpper1"]/*' />
public static bool IsUpper(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
return IsUpper(s[index]);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.IsWhiteSpace1"]/*' />
public static bool IsWhiteSpace(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
return IsWhiteSpace(s[index]);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.GetUnicodeCategory"]/*' />
public static UnicodeCategory GetUnicodeCategory(char c)
{
return CharacterInfo.GetUnicodeCategory(c);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.GetUnicodeCategory1"]/*' />
public static UnicodeCategory GetUnicodeCategory(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
return GetUnicodeCategory(s[index]);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.GetNumericValue"]/*' />
public static double GetNumericValue(char c)
{
return CharacterInfo.GetNumericValue(c);
}
/// <include file='doc\Char.uex' path='docs/doc[@for="Char.GetNumericValue1"]/*' />
public static double GetNumericValue(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
return GetNumericValue(s[index]);
}
//
// This is just designed to prevent compiler warnings.
// This field is used from native, but we need to prevent the compiler warnings.
//
#if _DEBUG
private void DontTouchThis() {
m_value = m_value;
}
#endif
}
}
+90
View File
@@ -0,0 +1,90 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: CharEnumerator
**
**
**
** Purpose: Enumerates the characters on a string. skips range
** checks.
**
** Date: January 3, 2001
**
============================================================*/
namespace System {
using System.Collections;
/// <include file='doc\CharEnumerator.uex' path='docs/doc[@for="CharEnumerator"]/*' />
[Serializable] public sealed class CharEnumerator : IEnumerator, ICloneable {
private String str;
private int index;
private char currentElement;
internal CharEnumerator(String str) {
this.str = str;
this.index = -1;
}
/// <include file='doc\CharEnumerator.uex' path='docs/doc[@for="CharEnumerator.Clone"]/*' />
public Object Clone() {
return MemberwiseClone();
}
/// <include file='doc\CharEnumerator.uex' path='docs/doc[@for="CharEnumerator.MoveNext"]/*' />
public bool MoveNext() {
if (index < (str.Length-1)) {
index++;
currentElement = str[index];
return true;
}
else
index = str.Length;
return false;
}
/// <include file='doc\CharEnumerator.uex' path='docs/doc[@for="CharEnumerator.IEnumerator.Current"]/*' />
/// <internalonly/>
Object IEnumerator.Current {
get {
if (index == -1)
throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
if (index >= str.Length)
throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
return currentElement;
}
}
/// <include file='doc\CharEnumerator.uex' path='docs/doc[@for="CharEnumerator.Current"]/*' />
public char Current {
get {
if (index == -1)
throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
if (index >= str.Length)
throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
return currentElement;
}
}
/// <include file='doc\CharEnumerator.uex' path='docs/doc[@for="CharEnumerator.Reset"]/*' />
public void Reset() {
currentElement = (char)0;
index = -1;
}
}
}
@@ -0,0 +1,48 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: CLSCompliantAttribute
**
**
**
** Purpose: Container for assemblies.
**
** Date: Jan 28, 2000
**
=============================================================================*/
namespace System {
/// <include file='doc\CLSCompliantAttribute.uex' path='docs/doc[@for="CLSCompliantAttribute"]/*' />
[AttributeUsage (AttributeTargets.All, Inherited=true, AllowMultiple=false),Serializable]
public sealed class CLSCompliantAttribute : Attribute
{
private bool m_compliant;
/// <include file='doc\CLSCompliantAttribute.uex' path='docs/doc[@for="CLSCompliantAttribute.CLSCompliantAttribute"]/*' />
public CLSCompliantAttribute (bool isCompliant)
{
m_compliant = isCompliant;
}
/// <include file='doc\CLSCompliantAttribute.uex' path='docs/doc[@for="CLSCompliantAttribute.IsCompliant"]/*' />
public bool IsCompliant
{
get
{
return m_compliant;
}
}
}
}
File diff suppressed because it is too large Load Diff
+498
View File
@@ -0,0 +1,498 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: BitArray
**
**
**
** Purpose: The BitArray class manages a compact array of bit values.
**
** Date: October 5, 1999
**
=============================================================================*/
namespace System.Collections {
using System;
// A vector of bits. Use this to store bits efficiently, without having to do bit
// shifting yourself.
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray"]/*' />
[Serializable()] public sealed class BitArray : ICollection, ICloneable {
private BitArray() {
}
/*=========================================================================
** Allocates space to hold length bit values. All of the values in the bit
** array are set to false.
**
** Exceptions: ArgumentException if length < 0.
=========================================================================*/
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.BitArray"]/*' />
public BitArray(int length)
: this(length, false) {
}
/*=========================================================================
** Allocates space to hold length bit values. All of the values in the bit
** array are set to defaultValue.
**
** Exceptions: ArgumentOutOfRangeException if length < 0.
=========================================================================*/
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.BitArray1"]/*' />
public BitArray(int length, bool defaultValue) {
if (length < 0) {
throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
m_array = new int[(length + 31) / 32];
m_length = length;
int fillValue = defaultValue ? unchecked(((int)0xffffffff)) : 0;
for (int i = 0; i < m_array.Length; i++) {
m_array[i] = fillValue;
}
_version = 0;
}
/*=========================================================================
** Allocates space to hold the bit values in bytes. bytes[0] represents
** bits 0 - 7, bytes[1] represents bits 8 - 15, etc. The LSB of each byte
** represents the lowest index value; bytes[0] & 1 represents bit 0,
** bytes[0] & 2 represents bit 1, bytes[0] & 4 represents bit 2, etc.
**
** Exceptions: ArgumentException if bytes == null.
=========================================================================*/
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.BitArray2"]/*' />
public BitArray(byte[] bytes) {
if (bytes == null) {
throw new ArgumentNullException("bytes");
}
m_array = new int[(bytes.Length + 3) / 4];
m_length = bytes.Length * 8;
int i = 0;
int j = 0;
while (bytes.Length - j >= 4) {
m_array[i++] = (bytes[j] & 0xff) |
((bytes[j + 1] & 0xff) << 8) |
((bytes[j + 2] & 0xff) << 16) |
((bytes[j + 3] & 0xff) << 24);
j += 4;
}
BCLDebug.Assert(bytes.Length - j >= 0, "BitArray byteLength problem");
BCLDebug.Assert(bytes.Length - j < 4, "BitArray byteLength problem #2");
switch (bytes.Length - j) {
case 3:
m_array[i] = ((bytes[j + 2] & 0xff) << 16);
goto case 2;
// fall through
case 2:
m_array[i] |= ((bytes[j + 1] & 0xff) << 8);
goto case 1;
// fall through
case 1:
m_array[i] |= (bytes[j] & 0xff);
break;
}
_version = 0;
}
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.BitArray3"]/*' />
public BitArray(bool[] values) {
if (values == null) {
throw new ArgumentNullException("values");
}
m_array = new int[(values.Length + 31) / 32];
m_length = values.Length;
for (int i = 0;i<values.Length;i++) {
if (values[i])
m_array[i/32] |= (1 << (i%32));
}
_version = 0;
}
/*=========================================================================
** Allocates space to hold the bit values in values. values[0] represents
** bits 0 - 31, values[1] represents bits 32 - 63, etc. The LSB of each
** integer represents the lowest index value; values[0] & 1 represents bit
** 0, values[0] & 2 represents bit 1, values[0] & 4 represents bit 2, etc.
**
** Exceptions: ArgumentException if values == null.
=========================================================================*/
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.BitArray4"]/*' />
public BitArray(int[] values) {
if (values == null) {
throw new ArgumentNullException("values");
}
m_array = new int[values.Length];
m_length = values.Length * 32;
Array.Copy(values, m_array, values.Length);
_version = 0;
}
/*=========================================================================
** Allocates a new BitArray with the same length and bit values as bits.
**
** Exceptions: ArgumentException if bits == null.
=========================================================================*/
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.BitArray5"]/*' />
public BitArray(BitArray bits) {
if (bits == null) {
throw new ArgumentNullException("bits");
}
m_array = new int[(bits.m_length + 31) / 32];
m_length = bits.m_length;
Array.Copy(bits.m_array, m_array, (bits.m_length + 31) / 32);
_version = bits._version;
}
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.this"]/*' />
public bool this[int index] {
get {
return Get(index);
}
set {
Set(index,value);
}
}
/*=========================================================================
** Returns the bit value at position index.
**
** Exceptions: ArgumentOutOfRangeException if index < 0 or
** index >= GetLength().
=========================================================================*/
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.Get"]/*' />
public bool Get(int index) {
if (index < 0 || index >= m_length) {
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
return (m_array[index / 32] & (1 << (index % 32))) != 0;
}
/*=========================================================================
** Sets the bit value at position index to value.
**
** Exceptions: ArgumentOutOfRangeException if index < 0 or
** index >= GetLength().
=========================================================================*/
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.Set"]/*' />
public void Set(int index, bool value) {
if (index < 0 || index >= m_length) {
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (value) {
m_array[index / 32] |= (1 << (index % 32));
} else {
m_array[index / 32] &= ~(1 << (index % 32));
}
_version++;
}
/*=========================================================================
** Sets all the bit values to value.
=========================================================================*/
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.SetAll"]/*' />
public void SetAll(bool value) {
int fillValue = value ? unchecked(((int)0xffffffff)) : 0;
int ints = (m_length + 31) / 32;
for (int i = 0; i < ints; i++) {
m_array[i] = fillValue;
}
_version++;
}
/*=========================================================================
** Returns a reference to the current instance ANDed with value.
**
** Exceptions: ArgumentException if value == null or
** value.Length != this.Length.
=========================================================================*/
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.And"]/*' />
public BitArray And(BitArray value) {
if (value==null)
throw new ArgumentNullException("value");
if (m_length != value.m_length)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"));
int ints = (m_length + 31) / 32;
for (int i = 0; i < ints; i++) {
m_array[i] &= value.m_array[i];
}
_version++;
return this;
}
/*=========================================================================
** Returns a reference to the current instance ORed with value.
**
** Exceptions: ArgumentException if value == null or
** value.Length != this.Length.
=========================================================================*/
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.Or"]/*' />
public BitArray Or(BitArray value) {
if (value==null)
throw new ArgumentNullException("value");
if (m_length != value.m_length)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"));
int ints = (m_length + 31) / 32;
for (int i = 0; i < ints; i++) {
m_array[i] |= value.m_array[i];
}
_version++;
return this;
}
/*=========================================================================
** Returns a reference to the current instance XORed with value.
**
** Exceptions: ArgumentException if value == null or
** value.Length != this.Length.
=========================================================================*/
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.Xor"]/*' />
public BitArray Xor(BitArray value) {
if (value==null)
throw new ArgumentNullException("value");
if (m_length != value.m_length)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"));
int ints = (m_length + 31) / 32;
for (int i = 0; i < ints; i++) {
m_array[i] ^= value.m_array[i];
}
_version++;
return this;
}
/*=========================================================================
** Inverts all the bit values. On/true bit values are converted to
** off/false. Off/false bit values are turned on/true. The current instance
** is updated and returned.
=========================================================================*/
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.Not"]/*' />
public BitArray Not() {
int ints = (m_length + 31) / 32;
for (int i = 0; i < ints; i++) {
m_array[i] = ~m_array[i];
}
_version++;
return this;
}
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.Length"]/*' />
public int Length {
get { return m_length; }
set {
if (value < 0) {
throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
int newints = (value + 31) / 32;
if (newints > m_array.Length || newints + _ShrinkThreshold < m_array.Length) {
// grow or shrink (if wasting more than _ShrinkThreshold ints)
int[] newarray = new int[newints];
Array.Copy(m_array, newarray, newints > m_array.Length ? m_array.Length : newints);
m_array = newarray;
}
if (value > m_length) {
// clear high bit values in the last int
int last = ((m_length + 31) / 32) - 1;
int bits = m_length % 32;
if (bits > 0) {
m_array[last] &= (1 << bits) - 1;
}
// clear remaining int values
Array.Clear(m_array, last + 1, newints - last - 1);
}
m_length = value;
_version++;
}
}
// ICollection implementation
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.CopyTo"]/*' />
public void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException("array");
if (index < 0)
throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (array is int[])
{
Array.Copy(m_array, 0, array, index, (m_length + 31) / 32);
}
else if (array is byte[])
{
if ((array.Length - index) < (m_length + 7)/8)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
byte [] b = (byte[])array;
for (int i = 0; i<(m_length + 7)/8;i++)
b[index + i] = (byte)((m_array[i/4] >> ((i%4)*8)) & 0x000000FF); // Shift to bring the required byte to LSB, then mask
}
else if (array is bool[])
{
if (array.Length - index < m_length)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
bool [] b = (bool[])array;
for (int i = 0;i<m_length;i++)
b[index + i] = ((m_array[i/32] >> (i%32)) & 0x00000001) != 0;
}
else
throw new ArgumentException(Environment.GetResourceString("Arg_BitArrayTypeUnsupported"));
}
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.Count"]/*' />
public int Count
{
get
{
return m_length;
}
}
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.Clone"]/*' />
public Object Clone()
{
BitArray bitArray = new BitArray(m_array);
bitArray._version = _version;
bitArray.m_length = m_length;
return bitArray;
}
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.SyncRoot"]/*' />
public Object SyncRoot
{
get
{
return this;
}
}
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.IsReadOnly"]/*' />
public bool IsReadOnly
{
get
{
return false;
}
}
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.IsSynchronized"]/*' />
public bool IsSynchronized
{
get
{
return false;
}
}
/// <include file='doc\BitArray.uex' path='docs/doc[@for="BitArray.GetEnumerator"]/*' />
public IEnumerator GetEnumerator()
{
return new BitArrayEnumeratorSimple(this);
}
// For a straightforward enumeration of the entire ArrayList,
// this is faster, because it's smaller.
[Serializable()] private class BitArrayEnumeratorSimple : IEnumerator, ICloneable
{
private BitArray bitarray;
private int index;
private int version;
private bool currentElement;
internal BitArrayEnumeratorSimple(BitArray bitarray) {
this.bitarray = bitarray;
this.index = -1;
version = bitarray._version;
}
public Object Clone() {
return MemberwiseClone();
}
public virtual bool MoveNext() {
if (version != bitarray._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
if (index < (bitarray.Count-1)) {
index++;
currentElement = bitarray.Get(index);
return true;
}
else
index = bitarray.Count;
return false;
}
public virtual Object Current {
get {
if (index == -1)
throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
if (index >= bitarray.Count)
throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
return currentElement;
}
}
public void Reset() {
if (version != bitarray._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
index = -1;
}
}
private int[] m_array;
private int m_length;
private int _version;
private const int _ShrinkThreshold = 256;
}
}
@@ -0,0 +1,75 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: CaseInsensitiveComparer
**
**
**
** Date: May 17, 2000
**
============================================================*/
namespace System.Collections {
//This class does not contain members and does not need to be serializable
using System;
using System.Collections;
using System.Globalization;
/// <include file='doc\CaseInsensitiveComparer.uex' path='docs/doc[@for="CaseInsensitiveComparer"]/*' />
[Serializable]
public class CaseInsensitiveComparer : IComparer {
private CompareInfo m_compareInfo;
/// <include file='doc\CaseInsensitiveComparer.uex' path='docs/doc[@for="CaseInsensitiveComparer.CaseInsensitiveComparer"]/*' />
public CaseInsensitiveComparer() {
m_compareInfo = CultureInfo.CurrentCulture.CompareInfo;
}
/// <include file='doc\CaseInsensitiveComparer.uex' path='docs/doc[@for="CaseInsensitiveComparer.CaseInsensitiveComparer1"]/*' />
public CaseInsensitiveComparer(CultureInfo culture) {
if (culture==null) {
throw new ArgumentNullException("culture");
}
m_compareInfo = culture.CompareInfo;
}
/// <include file='doc\CaseInsensitiveComparer.uex' path='docs/doc[@for="CaseInsensitiveComparer.Default"]/*' />
public static CaseInsensitiveComparer Default
{
get
{
return new CaseInsensitiveComparer();
}
}
// Behaves exactly like Comparer.Default.Compare except that the comparision is case insensitive
// Compares two Objects by calling CompareTo. If a ==
// b,0 is returned. If a implements
// IComparable, a.CompareTo(b) is returned. If a
// doesn't implement IComparable and b does,
// -(b.CompareTo(a)) is returned, otherwise an
// exception is thrown.
//
/// <include file='doc\CaseInsensitiveComparer.uex' path='docs/doc[@for="CaseInsensitiveComparer.Compare"]/*' />
public int Compare(Object a, Object b) {
String sa = a as String;
String sb = b as String;
if (sa != null && sb != null)
return m_compareInfo.Compare(sa, sb, CompareOptions.IgnoreCase);
else
return Comparer.Default.Compare(a,b);
}
}
}
@@ -0,0 +1,80 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: CaseInsensitiveHashCodeProvider
**
**
**
** Purpose: Designed to support hashtables which require
** case-insensitive behavior while still maintaining case,
** this provides an efficient mechanism for getting the
** hashcode of the string ignoring case.
**
** Date: February 13, 2000
**
============================================================*/
namespace System.Collections {
//This class does not contain members and does not need to be serializable
using System;
using System.Collections;
using System.Globalization;
/// <include file='doc\CaseInsensitiveHashCodeProvider.uex' path='docs/doc[@for="CaseInsensitiveHashCodeProvider"]/*' />
[Serializable]
public class CaseInsensitiveHashCodeProvider : IHashCodeProvider {
private TextInfo m_text;
/// <include file='doc\CaseInsensitiveHashCodeProvider.uex' path='docs/doc[@for="CaseInsensitiveHashCodeProvider.CaseInsensitiveHashCodeProvider"]/*' />
public CaseInsensitiveHashCodeProvider() {
m_text = CultureInfo.CurrentCulture.TextInfo;
}
/// <include file='doc\CaseInsensitiveHashCodeProvider.uex' path='docs/doc[@for="CaseInsensitiveHashCodeProvider.CaseInsensitiveHashCodeProvider1"]/*' />
public CaseInsensitiveHashCodeProvider(CultureInfo culture) {
if (culture==null) {
throw new ArgumentNullException("culture");
}
m_text = culture.TextInfo;
}
/// <include file='doc\CaseInsensitiveHashCodeProvider.uex' path='docs/doc[@for="CaseInsensitiveHashCodeProvider.Default"]/*' />
public static CaseInsensitiveHashCodeProvider Default
{
get
{
return new CaseInsensitiveHashCodeProvider();
}
}
/// <include file='doc\CaseInsensitiveHashCodeProvider.uex' path='docs/doc[@for="CaseInsensitiveHashCodeProvider.GetHashCode"]/*' />
public int GetHashCode(Object obj) {
if (obj==null) {
throw new ArgumentNullException("obj");
}
String s = obj as String;
if (s==null) {
return obj.GetHashCode();
}
if (s.IsFastSort()) {
return TextInfo.GetDefaultCaseInsensitiveHashCode(s);
} else {
return m_text.GetCaseInsensitiveHashCode(s);
}
}
}
}
@@ -0,0 +1,211 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
namespace System.Collections {
using System;
// Useful base class for typed read/write collections where items derive from object
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase"]/*' />
[Serializable]
public abstract class CollectionBase : IList {
ArrayList list;
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.InnerList"]/*' />
protected ArrayList InnerList {
get {
if (list == null)
list = new ArrayList();
return list;
}
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.List"]/*' />
protected IList List {
get { return (IList)this; }
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.Count"]/*' />
public int Count {
get {
return list == null ? 0 : list.Count;
}
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.Clear"]/*' />
public void Clear() {
OnClear();
InnerList.Clear();
OnClearComplete();
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.RemoveAt"]/*' />
public void RemoveAt(int index) {
if (index < 0 || index >= InnerList.Count)
throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_Index"));
Object temp = InnerList[index];
OnValidate(temp);
OnRemove(index, temp);
InnerList.RemoveAt(index);
OnRemoveComplete(index, temp);
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.IList.IsReadOnly"]/*' />
bool IList.IsReadOnly {
get { return InnerList.IsReadOnly; }
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.IList.IsFixedSize"]/*' />
bool IList.IsFixedSize {
get { return InnerList.IsFixedSize; }
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.ICollection.IsSynchronized"]/*' />
bool ICollection.IsSynchronized {
get { return InnerList.IsSynchronized; }
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.ICollection.SyncRoot"]/*' />
Object ICollection.SyncRoot {
get { return InnerList.SyncRoot; }
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.ICollection.CopyTo"]/*' />
void ICollection.CopyTo(Array array, int index) {
InnerList.CopyTo(array, index);
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.IList.this"]/*' />
Object IList.this[int index] {
get {
if (index < 0 || index >= InnerList.Count)
throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_Index"));
return InnerList[index];
}
set {
if (index < 0 || index >= InnerList.Count)
throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_Index"));
OnValidate(value);
Object temp = InnerList[index];
OnSet(index, temp, value);
InnerList[index] = value;
try {
OnSetComplete(index, temp, value);
}
catch (Exception) {
InnerList[index] = temp;
throw;
}
}
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.IList.Contains"]/*' />
bool IList.Contains(Object value) {
return InnerList.Contains(value);
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.IList.Add"]/*' />
int IList.Add(Object value) {
OnValidate(value);
OnInsert(InnerList.Count, value);
int index = InnerList.Add(value);
try {
OnInsertComplete(index, value);
}
catch (Exception) {
InnerList.RemoveAt(index);
throw;
}
return index;
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.IList.Remove"]/*' />
void IList.Remove(Object value) {
OnValidate(value);
int index = InnerList.IndexOf(value);
if (index < 0) throw new ArgumentException(Environment.GetResourceString("Arg_RemoveArgNotFound"));
OnRemove(index, value);
InnerList.RemoveAt(index);
OnRemoveComplete(index, value);
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.IList.IndexOf"]/*' />
int IList.IndexOf(Object value) {
return InnerList.IndexOf(value);
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.IList.Insert"]/*' />
void IList.Insert(int index, Object value) {
if (index < 0 || index > InnerList.Count)
throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_Index"));
OnValidate(value);
OnInsert(index, value);
InnerList.Insert(index, value);
try {
OnInsertComplete(index, value);
}
catch (Exception) {
InnerList.RemoveAt(index);
throw;
}
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.GetEnumerator"]/*' />
public IEnumerator GetEnumerator() {
return InnerList.GetEnumerator();
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.OnSet"]/*' />
protected virtual void OnSet(int index, Object oldValue, Object newValue) {
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.OnInsert"]/*' />
protected virtual void OnInsert(int index, Object value) {
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.OnClear"]/*' />
protected virtual void OnClear() {
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.OnRemove"]/*' />
protected virtual void OnRemove(int index, Object value) {
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.OnValidate"]/*' />
protected virtual void OnValidate(Object value) {
if (value == null) throw new ArgumentNullException("value");
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.OnSetComplete"]/*' />
protected virtual void OnSetComplete(int index, Object oldValue, Object newValue) {
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.OnInsertComplete"]/*' />
protected virtual void OnInsertComplete(int index, Object value) {
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.OnClearComplete"]/*' />
protected virtual void OnClearComplete() {
}
/// <include file='doc\CollectionBase.uex' path='docs/doc[@for="CollectionBase.OnRemoveComplete"]/*' />
protected virtual void OnRemoveComplete(int index, Object value) {
}
}
}
@@ -0,0 +1,60 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: Comparer
**
**
**
** Purpose: Default IComparer implementation.
**
** Date: October 9, 1999
**
===========================================================*/
namespace System.Collections {
using System;
/// <include file='doc\Comparer.uex' path='docs/doc[@for="Comparer"]/*' />
[Serializable]
public sealed class Comparer : IComparer
{
/// <include file='doc\Comparer.uex' path='docs/doc[@for="Comparer.Default"]/*' />
public static readonly Comparer Default = new Comparer();
private Comparer() {
}
// Compares two Objects by calling CompareTo. If a ==
// b,0 is returned. If a implements
// IComparable, a.CompareTo(b) is returned. If a
// doesn't implement IComparable and b does,
// -(b.CompareTo(a)) is returned, otherwise an
// exception is thrown.
//
/// <include file='doc\Comparer.uex' path='docs/doc[@for="Comparer.Compare"]/*' />
public int Compare(Object a, Object b) {
if (a == b) return 0;
if (a == null) return -1;
if (b == null) return 1;
IComparable ia = a as IComparable;
if (ia != null)
return ia.CompareTo(b);
IComparable ib = b as IComparable;
if (ib != null)
return -ib.CompareTo(a);
throw new ArgumentException(Environment.GetResourceString("Argument_ImplementIComparable"));
}
}
}
@@ -0,0 +1,196 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
namespace System.Collections {
using System;
// Useful base class for typed read/write collections where items derive from object
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase"]/*' />
[Serializable]
public abstract class DictionaryBase : IDictionary {
Hashtable hashtable;
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.InnerHashtable"]/*' />
protected Hashtable InnerHashtable {
get {
if (hashtable == null)
hashtable = new Hashtable();
return hashtable;
}
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.Dictionary"]/*' />
protected IDictionary Dictionary {
get { return (IDictionary) this; }
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.Count"]/*' />
public int Count {
// to avoid newing inner list if no items are ever added
get { return hashtable == null ? 0 : hashtable.Count; }
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.IDictionary.IsReadOnly"]/*' />
bool IDictionary.IsReadOnly {
get { return InnerHashtable.IsReadOnly; }
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.IDictionary.IsFixedSize"]/*' />
bool IDictionary.IsFixedSize {
get { return InnerHashtable.IsFixedSize; }
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.ICollection.IsSynchronized"]/*' />
bool ICollection.IsSynchronized {
get { return InnerHashtable.IsSynchronized; }
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.IDictionary.Keys"]/*' />
ICollection IDictionary.Keys {
get {
return InnerHashtable.Keys;
}
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.ICollection.SyncRoot"]/*' />
Object ICollection.SyncRoot {
get { return InnerHashtable.SyncRoot; }
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.IDictionary.Values"]/*' />
ICollection IDictionary.Values {
get {
return InnerHashtable.Values;
}
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.CopyTo"]/*' />
public void CopyTo(Array array, int index) {
InnerHashtable.CopyTo(array, index);
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.IDictionary.this"]/*' />
object IDictionary.this[object key] {
get {
OnGet(key, InnerHashtable[key]);
return InnerHashtable[key];
}
set {
OnValidate(key, value);
Object temp = InnerHashtable[key];
OnSet(key, temp, value);
InnerHashtable[key] = value;
try {
OnSetComplete(key, temp, value);
}
catch (Exception) {
InnerHashtable[key] = temp;
throw;
}
}
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.IDictionary.Contains"]/*' />
bool IDictionary.Contains(object key) {
return InnerHashtable.Contains(key);
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.IDictionary.Add"]/*' />
void IDictionary.Add(object key, object value) {
OnValidate(key, value);
OnInsert(key, value);
InnerHashtable.Add(key, value);
try {
OnInsertComplete(key, value);
}
catch (Exception) {
InnerHashtable.Remove(key);
throw;
}
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.Clear"]/*' />
public void Clear() {
OnClear();
InnerHashtable.Clear();
OnClearComplete();
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.IDictionary.Remove"]/*' />
void IDictionary.Remove(object key) {
Object temp = InnerHashtable[key];
OnValidate(key, temp);
OnRemove(key, temp);
InnerHashtable.Remove(key);
OnRemoveComplete(key, temp);
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.GetEnumerator"]/*' />
public IDictionaryEnumerator GetEnumerator() {
return InnerHashtable.GetEnumerator();
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.IEnumerable.GetEnumerator"]/*' />
IEnumerator IEnumerable.GetEnumerator() {
return InnerHashtable.GetEnumerator();
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.OnGet"]/*' />
protected virtual object OnGet(object key, object currentValue) {
return currentValue;
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.OnSet"]/*' />
protected virtual void OnSet(object key, object oldValue, object newValue) {
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.OnInsert"]/*' />
protected virtual void OnInsert(object key, object value) {
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.OnClear"]/*' />
protected virtual void OnClear() {
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.OnRemove"]/*' />
protected virtual void OnRemove(object key, object value) {
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.OnValidate"]/*' />
protected virtual void OnValidate(object key, object value) {
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.OnSetComplete"]/*' />
protected virtual void OnSetComplete(object key, object oldValue, object newValue) {
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.OnInsertComplete"]/*' />
protected virtual void OnInsertComplete(object key, object value) {
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.OnClearComplete"]/*' />
protected virtual void OnClearComplete() {
}
/// <include file='doc\DictionaryBase.uex' path='docs/doc[@for="DictionaryBase.OnRemoveComplete"]/*' />
protected virtual void OnRemoveComplete(object key, object value) {
}
}
}
@@ -0,0 +1,78 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Interface: DictionaryEntry
**
**
**
** Purpose: Return Value for IDictionaryEnumerator::GetEntry
**
** Date: September 20, 1999
**
===========================================================*/
namespace System.Collections {
using System;
// A DictionaryEntry holds a key and a value from a dictionary.
// It is returned by IDictionaryEnumerator::GetEntry().
/// <include file='doc\DictionaryEntry.uex' path='docs/doc[@for="DictionaryEntry"]/*' />
[Serializable()] public struct DictionaryEntry
{
/// <include file='doc\DictionaryEntry.uex' path='docs/doc[@for="DictionaryEntry._key"]/*' />
private Object _key;
/// <include file='doc\DictionaryEntry.uex' path='docs/doc[@for="DictionaryEntry._value"]/*' />
private Object _value;
// Constructs a new DictionaryEnumerator by setting the Key
// and Value fields appropriately.
//
/// <include file='doc\DictionaryEntry.uex' path='docs/doc[@for="DictionaryEntry.DictionaryEntry"]/*' />
public DictionaryEntry(Object key, Object value)
{
if (key==null)
throw new ArgumentNullException("key");
_key = key;
_value = value;
}
/// <include file='doc\DictionaryEntry.uex' path='docs/doc[@for="DictionaryEntry.Key"]/*' />
public Object Key
{
get
{
return _key;
}
set {
if (value == null)
throw new ArgumentNullException("value");
_key = value;
}
}
/// <include file='doc\DictionaryEntry.uex' path='docs/doc[@for="DictionaryEntry.Value"]/*' />
public Object Value
{
get {
return _value;
}
set {
_value = value;
}
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,80 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Interface: ICollection
**
**
**
** Purpose: Base interface for all collections.
**
** Date: June 11, 1999
**
===========================================================*/
namespace System.Collections {
using System;
// Base interface for all collections, defining enumerators, size, and
// synchronization methods.
/// <include file='doc\ICollection.uex' path='docs/doc[@for="ICollection"]/*' />
public interface ICollection : IEnumerable
{
// Interfaces are not serialable
// CopyTo copies a collection into an Array, starting at a particular
// index into the array.
//
/// <include file='doc\ICollection.uex' path='docs/doc[@for="ICollection.CopyTo"]/*' />
void CopyTo(Array array, int index);
// Number of items in the collections.
/// <include file='doc\ICollection.uex' path='docs/doc[@for="ICollection.Count"]/*' />
int Count
{ get; }
// SyncRoot will return an Object to use for synchronization (thread safety).
// In the absense of a GetSynchronized() method on a collection,
// the expected usage for SyncRoot would look like this:
//
//
// ICollection col = ...
// synchronized (col.SyncRoot) {
// // Some operation on the collection, which is now thread safe.
// }
//
//
// The system-provided collections have a method called GetSynchronized()
// which will create a synchronized wrapper for the collection. All access
// to the collection that you want to be thread-safe should go through that
// wrapper collection.
//
// For collections with no publically available underlying store, the expected
// implementation is to simply return this. Note that the this
// pointer may not be sufficient for collections that wrap other collections;
// those should return the underlying collection's SyncRoot property.
/// <include file='doc\ICollection.uex' path='docs/doc[@for="ICollection.SyncRoot"]/*' />
Object SyncRoot
{ get; }
// Is this collection synchronized (i.e., thread-safe)? If you want a synchronized
// collection, you can use SyncRoot as an object to synchronize your collection with.
// If you're using one of the collections in System.Collections, you could call
// GetSynchronized() to get a synchronized wrapper around the underlying
// collection.
/// <include file='doc\ICollection.uex' path='docs/doc[@for="ICollection.IsSynchronized"]/*' />
bool IsSynchronized
{ get; }
}
}
@@ -0,0 +1,43 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Interface: IComparer
**
**
**
** Purpose: Interface for comparing two Objects.
**
** Date: September 25, 1999
**
===========================================================*/
namespace System.Collections {
using System;
// The IComparer interface implements a method that compares two objects. It is
// used in conjunction with the Sort and BinarySearch methods on
// the Array and List classes.
//
// Interfaces are not serializable
/// <include file='doc\IComparer.uex' path='docs/doc[@for="IComparer"]/*' />
public interface IComparer {
// Compares two objects. An implementation of this method must return a
// value less than zero if x is less than y, zero if x is equal to y, or a
// value greater than zero if x is greater than y.
//
/// <include file='doc\IComparer.uex' path='docs/doc[@for="IComparer.Compare"]/*' />
int Compare(Object x, Object y);
}
}
@@ -0,0 +1,88 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Interface: IDictionary
**
**
**
** Purpose: Base interface for all dictionaries.
**
** Date: September 21, 1999
**
===========================================================*/
namespace System.Collections {
using System;
// An IDictionary is a possibly unordered set of key-value pairs.
// Keys can be any non-null object. Values can be any object.
// You can look up a value in an IDictionary via the default indexed
// property, Items.
/// <include file='doc\IDictionary.uex' path='docs/doc[@for="IDictionary"]/*' />
public interface IDictionary : ICollection
{
/// <include file='doc\IDictionary.uex' path='docs/doc[@for="IDictionary.this"]/*' />
// Interfaces are not serializable
// The Item property provides methods to read and edit entries
// in the Dictionary.
Object this[Object key] {
get;
set;
}
// Returns a collections of the keys in this dictionary.
/// <include file='doc\IDictionary.uex' path='docs/doc[@for="IDictionary.Keys"]/*' />
ICollection Keys {
get;
}
// Returns a collections of the values in this dictionary.
/// <include file='doc\IDictionary.uex' path='docs/doc[@for="IDictionary.Values"]/*' />
ICollection Values {
get;
}
// Returns whether this dictionary contains a particular key.
//
/// <include file='doc\IDictionary.uex' path='docs/doc[@for="IDictionary.Contains"]/*' />
bool Contains(Object key);
// Adds a key-value pair to the dictionary.
//
/// <include file='doc\IDictionary.uex' path='docs/doc[@for="IDictionary.Add"]/*' />
void Add(Object key, Object value);
// Removes all pairs from the dictionary.
/// <include file='doc\IDictionary.uex' path='docs/doc[@for="IDictionary.Clear"]/*' />
void Clear();
/// <include file='doc\IDictionary.uex' path='docs/doc[@for="IDictionary.IsReadOnly"]/*' />
bool IsReadOnly
{ get; }
/// <include file='doc\IDictionary.uex' path='docs/doc[@for="IDictionary.IsFixedSize"]/*' />
bool IsFixedSize
{ get; }
// Returns an IDictionaryEnumerator for this dictionary.
/// <include file='doc\IDictionary.uex' path='docs/doc[@for="IDictionary.GetEnumerator"]/*' />
new IDictionaryEnumerator GetEnumerator();
// Removes a particular key from the dictionary.
//
/// <include file='doc\IDictionary.uex' path='docs/doc[@for="IDictionary.Remove"]/*' />
void Remove(Object key);
}
}
@@ -0,0 +1,92 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Interface: IDictionaryEnumerator
**
**
**
** Purpose: Base interface for dictionary enumerators.
**
** Date: September 20, 1999
**
===========================================================*/
namespace System.Collections {
// Interfaces are not serializable
using System;
// This interface represents an enumerator that allows sequential access to the
// elements of a dictionary. Upon creation, an enumerator is conceptually
// positioned before the first element of the enumeration. The first call to the
// MoveNext method brings the first element of the enumeration into view,
// and each successive call to MoveNext brings the next element into
// view until MoveNext returns false, indicating that there are no more
// elements to enumerate. Following each call to MoveNext, the
// Key and Value methods are used to obtain the key and
// value of the element currently in view. The values returned by calls to
// Key and Value are undefined before the first call to
// MoveNext and following a call to MoveNext that returned false.
// Enumerators are typically used in while loops of the form
//
// IDictionaryEnumerator e = ...;
// while (e.MoveNext()) {
// Object key = e.Key;
// Object value = e.Value;
// ...
// }
//
// The IDictionaryEnumerator interface extends the IEnumerator
// inerface and can thus be used as a regular enumerator. The Current
// method of an IDictionaryEnumerator returns a DictionaryEntry containing
// the current key and value pair. However, the GetEntry method will
// return the same DictionaryEntry and avoids boxing the DictionaryEntry (boxing
// is somewhat expensive).
//
/// <include file='doc\IDictionaryEnumerator.uex' path='docs/doc[@for="IDictionaryEnumerator"]/*' />
public interface IDictionaryEnumerator : IEnumerator
{
// Returns the key of the current element of the enumeration. The returned
// value is undefined before the first call to GetNext and following
// a call to GetNext that returned false. Multiple calls to
// GetKey with no intervening calls to GetNext will return
// the same object.
//
/// <include file='doc\IDictionaryEnumerator.uex' path='docs/doc[@for="IDictionaryEnumerator.Key"]/*' />
Object Key {
get;
}
// Returns the value of the current element of the enumeration. The
// returned value is undefined before the first call to GetNext and
// following a call to GetNext that returned false. Multiple calls
// to GetValue with no intervening calls to GetNext will
// return the same object.
//
/// <include file='doc\IDictionaryEnumerator.uex' path='docs/doc[@for="IDictionaryEnumerator.Value"]/*' />
Object Value {
get;
}
// GetBlock will copy dictionary values into the given Array. It will either
// fill up the array, or if there aren't enough elements, it will
// copy as much as possible into the Array. The number of elements
// copied is returned.
//
/// <include file='doc\IDictionaryEnumerator.uex' path='docs/doc[@for="IDictionaryEnumerator.Entry"]/*' />
DictionaryEntry Entry {
get;
}
}
}
@@ -0,0 +1,40 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Interface: IEnumerable
**
**
**
** Purpose: Interface for classes providing IEnumerators
**
** Date: November 8, 1999
**
===========================================================*/
namespace System.Collections {
using System;
using System.Runtime.InteropServices;
// Implement this interface if you need to support VB's foreach semantics.
// Also, COM classes that support an enumerator will also implement this interface.
/// <include file='doc\IEnumerable.uex' path='docs/doc[@for="IEnumerable"]/*' />
public interface IEnumerable
{
// Interfaces are not serializable
// Returns an IEnumerator for this enumerable Object. The enumerator provides
// a simple way to access all the contents of a collection.
/// <include file='doc\IEnumerable.uex' path='docs/doc[@for="IEnumerable.GetEnumerator"]/*' />
IEnumerator GetEnumerator();
}
}
@@ -0,0 +1,65 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Interface: IEnumerator
**
**
**
** Purpose: Base interface for all enumerators.
**
** Date: June 14, 1999
**
===========================================================*/
namespace System.Collections {
using System;
using System.Runtime.InteropServices;
// Base interface for all enumerators, providing a simple approach
// to iterating over a collection.
/// <include file='doc\IEnumerator.uex' path='docs/doc[@for="IEnumerator"]/*' />
public interface IEnumerator
{
// Interfaces are not serializable
// Advances the enumerator to the next element of the enumeration and
// returns a boolean indicating whether an element is available. Upon
// creation, an enumerator is conceptually positioned before the first
// element of the enumeration, and the first call to MoveNext
// brings the first element of the enumeration into view.
//
/// <include file='doc\IEnumerator.uex' path='docs/doc[@for="IEnumerator.MoveNext"]/*' />
bool MoveNext();
// Returns the current element of the enumeration. The returned value is
// undefined before the first call to MoveNext and following a
// call to MoveNext that returned false. Multiple calls to
// GetCurrent with no intervening calls to MoveNext
// will return the same object.
//
/// <include file='doc\IEnumerator.uex' path='docs/doc[@for="IEnumerator.Current"]/*' />
Object Current {
get;
}
// Resets the enumerator to the beginning of the enumeration, starting over.
// The preferred behavior for Reset is to return the exact same enumeration.
// This means if you modify the underlying collection then call Reset, your
// IEnumerator will be invalid, just as it would have been if you had called
// MoveNext or Current.
//
/// <include file='doc\IEnumerator.uex' path='docs/doc[@for="IEnumerator.Reset"]/*' />
void Reset();
}
}
@@ -0,0 +1,40 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Interface: IHashCodeProvider
**
**
**
** Purpose: A bunch of strings.
**
** Date: July 21, 1999
**
===========================================================*/
namespace System.Collections {
using System;
// Provides a mechanism for a hash table user to override the default
// GetHashCode() function on Objects, providing their own hash function.
/// <include file='doc\IHashCodeProvider.uex' path='docs/doc[@for="IHashCodeProvider"]/*' />
public interface IHashCodeProvider
{
// Interfaces are not serializable
// Returns a hash code for the given object.
//
/// <include file='doc\IHashCodeProvider.uex' path='docs/doc[@for="IHashCodeProvider.GetHashCode"]/*' />
int GetHashCode (Object obj);
}
}
+90
View File
@@ -0,0 +1,90 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Interface: IList
**
**
**
** Purpose: Base interface for all Lists.
**
** Date: September 21, 1999
**
===========================================================*/
namespace System.Collections {
using System;
// An IList is an ordered collection of objects. The exact ordering
// is up to the implementation of the list, ranging from a sorted
// order to insertion order.
/// <include file='doc\IList.uex' path='docs/doc[@for="IList"]/*' />
public interface IList : ICollection
{
// Interfaces are not serializable
// The Item property provides methods to read and edit entries in the List.
/// <include file='doc\IList.uex' path='docs/doc[@for="IList.this"]/*' />
Object this[int index] {
get;
set;
}
// Adds an item to the list. The exact position in the list is
// implementation-dependent, so while ArrayList may always insert
// in the last available location, a SortedList most likely would not.
// The return value is the position the new element was inserted in.
/// <include file='doc\IList.uex' path='docs/doc[@for="IList.Add"]/*' />
int Add(Object value);
// Returns whether the list contains a particular item.
/// <include file='doc\IList.uex' path='docs/doc[@for="IList.Contains"]/*' />
bool Contains(Object value);
// Removes all items from the list.
/// <include file='doc\IList.uex' path='docs/doc[@for="IList.Clear"]/*' />
void Clear();
/// <include file='doc\IList.uex' path='docs/doc[@for="IList.IsReadOnly"]/*' />
bool IsReadOnly
{ get; }
/// <include file='doc\IList.uex' path='docs/doc[@for="IList.IsFixedSize"]/*' />
bool IsFixedSize
{
get;
}
// Returns the index of a particular item, if it is in the list.
// Returns -1 if the item isn't in the list.
/// <include file='doc\IList.uex' path='docs/doc[@for="IList.IndexOf"]/*' />
int IndexOf(Object value);
// Inserts value into the list at position index.
// index must be non-negative and less than or equal to the
// number of elements in the list. If index equals the number
// of items in the list, then value is appended to the end.
/// <include file='doc\IList.uex' path='docs/doc[@for="IList.Insert"]/*' />
void Insert(int index, Object value);
// Removes an item from the list.
/// <include file='doc\IList.uex' path='docs/doc[@for="IList.Remove"]/*' />
void Remove(Object value);
// Removes the item at position index.
/// <include file='doc\IList.uex' path='docs/doc[@for="IList.RemoveAt"]/*' />
void RemoveAt(int index);
}
}
+452
View File
@@ -0,0 +1,452 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: Queue
**
**
**
** Purpose: A circular-array implementation of a queue.
**
** Date: October 4, 1999
**
=============================================================================*/
namespace System.Collections {
using System;
// A simple Queue of objects. Internally it is implemented as a circular
// buffer, so Enqueue can be O(n). Dequeue is O(1).
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue"]/*' />
[Serializable()] public class Queue : ICollection, ICloneable {
private Object[] _array;
private int _head; // First valid element in the queue
private int _tail; // Last valid element in the queue
private int _size; // Number of elements.
private int _growFactor; // 100 == 1.0, 130 == 1.3, 200 == 2.0
private int _version;
private const int _MinimumGrow = 4;
private const int _ShrinkThreshold = 32;
// Creates a queue with room for capacity objects. The default initial
// capacity and grow factor are used.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Queue"]/*' />
public Queue()
: this(32, (float)2.0) {
}
// Creates a queue with room for capacity objects. The default grow factor
// is used.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Queue1"]/*' />
public Queue(int capacity)
: this(capacity, (float)2.0) {
}
// Creates a queue with room for capacity objects. When full, the new
// capacity is set to the old capacity * growFactor.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Queue2"]/*' />
public Queue(int capacity, float growFactor) {
if (capacity < 0)
throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (!(growFactor >= 1.0 && growFactor <= 10.0))
throw new ArgumentOutOfRangeException("growFactor", String.Format(Environment.GetResourceString("ArgumentOutOfRange_QueueGrowFactor"), 1, 10));
_array = new Object[capacity];
_head = 0;
_tail = 0;
_size = 0;
_growFactor = (int)(growFactor * 100);
}
// Fills a Queue with the elements of an ICollection. Uses the enumerator
// to get each of the elements.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Queue3"]/*' />
public Queue(ICollection col) : this((col==null ? 32 : col.Count))
{
if (col==null)
throw new ArgumentNullException("col");
IEnumerator en = col.GetEnumerator();
while(en.MoveNext())
Enqueue(en.Current);
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Count"]/*' />
public virtual int Count {
get { return _size; }
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Clone"]/*' />
public virtual Object Clone() {
Queue q = new Queue(_size);
q._size = _size;
Array.Copy(_array, 0, q._array, 0, _size);
q._version = _version;
return q;
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.IsSynchronized"]/*' />
public virtual bool IsSynchronized {
get { return false; }
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.SyncRoot"]/*' />
public virtual Object SyncRoot {
get { return this; }
}
// Removes all Objects from the queue.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Clear"]/*' />
public virtual void Clear() {
if (_head < _tail)
Array.Clear(_array, _head, _size);
else {
Array.Clear(_array, _head, _array.Length - _head);
Array.Clear(_array, 0, _tail);
}
_head = 0;
_tail = 0;
_size = 0;
_version++;
}
// CopyTo copies a collection into an Array, starting at a particular
// index into the array.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.CopyTo"]/*' />
public virtual void CopyTo(Array array, int index)
{
if (array==null)
throw new ArgumentNullException("array");
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
int arrayLen = array.Length;
if (arrayLen - index < _size)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
int numToCopy = (arrayLen-index < _size) ? arrayLen-index : _size;
if (numToCopy==0)
return;
if (_head < _tail) {
Array.Copy(_array, _head, array, index, numToCopy);
} else {
int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy;
Array.Copy(_array, _head, array, index, firstPart);
numToCopy -= firstPart;
Array.Copy(_array, 0, array, index+_array.Length - _head, numToCopy);
}
}
// Adds obj to the tail of the queue.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Enqueue"]/*' />
public virtual void Enqueue(Object obj) {
if (_size == _array.Length) {
int newcapacity = (int)((long)_array.Length * (long)_growFactor / 100);
if (newcapacity < _array.Length + _MinimumGrow) {
newcapacity = _array.Length + _MinimumGrow;
}
SetCapacity(newcapacity);
}
_array[_tail] = obj;
_tail = (_tail + 1) % _array.Length;
_size++;
_version++;
}
// GetEnumerator returns an IEnumerator over this Queue. This
// Enumerator will support removing.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.GetEnumerator"]/*' />
public virtual IEnumerator GetEnumerator()
{
return new QueueEnumerator(this);
}
// Removes the object at the head of the queue and returns it. If the queue
// is empty, this method simply returns null.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Dequeue"]/*' />
public virtual Object Dequeue() {
if (_size == 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EmptyQueue"));
Object removed = _array[_head];
_array[_head] = null;
_head = (_head + 1) % _array.Length;
_size--;
_version++;
return removed;
}
// Returns the object at the head of the queue. The object remains in the
// queue. If the queue is empty, this method throws an
// InvalidOperationException.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Peek"]/*' />
public virtual Object Peek() {
if (_size == 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EmptyQueue"));
return _array[_head];
}
// Returns a synchronized Queue. Returns a synchronized wrapper
// class around the queue - the caller must not use references to the
// original queue.
//
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Synchronized"]/*' />
public static Queue Synchronized(Queue queue)
{
if (queue==null)
throw new ArgumentNullException("queue");
return new SynchronizedQueue(queue);
}
// Returns true if the queue contains at least one object equal to obj.
// Equality is determined using obj.Equals().
//
// Exceptions: ArgumentNullException if obj == null.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Contains"]/*' />
public virtual bool Contains(Object obj) {
int index = _head;
int count = _size;
while (count-- > 0) {
if (obj == null) {
if (_array[index] == null)
return true;
} else if (obj.Equals(_array[index])) {
return true;
}
index = (index + 1) % _array.Length;
}
return false;
}
internal Object GetElement(int i)
{
return _array[(_head + i) % _array.Length];
}
// Iterates over the objects in the queue, returning an array of the
// objects in the Queue, or an empty array if the queue is empty.
// The order of elements in the array is first in to last in, the same
// order produced by successive calls to Dequeue.
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.ToArray"]/*' />
public virtual Object[] ToArray()
{
Object[] arr = new Object[_size];
if (_size==0)
return arr;
if (_head < _tail) {
Array.Copy(_array, _head, arr, 0, _size);
} else {
Array.Copy(_array, _head, arr, 0, _array.Length - _head);
Array.Copy(_array, 0, arr, _array.Length - _head, _tail);
}
return arr;
}
// PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity
// must be >= _size.
private void SetCapacity(int capacity) {
Object[] newarray = new Object[capacity];
if (_size > 0) {
if (_head < _tail) {
Array.Copy(_array, _head, newarray, 0, _size);
} else {
Array.Copy(_array, _head, newarray, 0, _array.Length - _head);
Array.Copy(_array, 0, newarray, _array.Length - _head, _tail);
}
}
_array = newarray;
_head = 0;
_tail = _size;
_version++;
}
/// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.TrimToSize"]/*' />
public virtual void TrimToSize()
{
SetCapacity(_size);
}
// Implements a synchronization wrapper around a queue.
[Serializable()] private class SynchronizedQueue : Queue
{
private Queue _q;
private Object root;
internal SynchronizedQueue(Queue q) {
this._q = q;
root = _q.SyncRoot;
}
public override bool IsSynchronized {
get { return true; }
}
public override Object SyncRoot {
get {
return root;
}
}
public override int Count {
get {
lock (root) {
return _q.Count;
}
}
}
public override void Clear() {
lock (root) {
_q.Clear();
}
}
public override Object Clone() {
lock (root) {
return new SynchronizedQueue((Queue)_q.Clone());
}
}
public override bool Contains(Object obj) {
lock (root) {
return _q.Contains(obj);
}
}
public override void CopyTo(Array array, int arrayIndex) {
lock (root) {
_q.CopyTo(array, arrayIndex);
}
}
public override void Enqueue(Object value) {
lock (root) {
_q.Enqueue(value);
}
}
public override Object Dequeue() {
lock (root) {
return _q.Dequeue();
}
}
public override IEnumerator GetEnumerator() {
lock (root) {
return _q.GetEnumerator();
}
}
public override Object Peek() {
lock (root) {
return _q.Peek();
}
}
public override Object[] ToArray() {
lock (root) {
return _q.ToArray();
}
}
public override void TrimToSize() {
lock (root) {
_q.TrimToSize();
}
}
}
// Implements an enumerator for a Queue. The enumerator uses the
// internal version number of the list to ensure that no modifications are
// made to the list while an enumeration is in progress.
[Serializable()] private class QueueEnumerator : IEnumerator, ICloneable
{
private Queue _q;
private int _index;
private int _version;
private Object currentElement;
internal QueueEnumerator(Queue q) {
_q = q;
_version = _q._version;
_index = 0;
currentElement = _q._array;
if (_q._size == 0)
_index = -1;
}
public Object Clone()
{
return MemberwiseClone();
}
public virtual bool MoveNext() {
if (_version != _q._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
if (_index < 0) {
currentElement = _q._array;
return false;
}
currentElement = _q.GetElement(_index);
_index++;
if (_index == _q._size)
_index = -1;
return true;
}
public virtual Object Current {
get {
if (currentElement == _q._array)
{
if (_index == 0)
throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
else
throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
}
return currentElement;
}
}
public virtual void Reset() {
if (_version != _q._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
if (_q._size == 0)
_index = -1;
else
_index = 0;
currentElement = _q._array;
}
}
}
}
@@ -0,0 +1,63 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
namespace System.Collections {
using System;
// Useful base class for typed readonly collections where items derive from object
/// <include file='doc\ReadOnlyCollectionBase.uex' path='docs/doc[@for="ReadOnlyCollectionBase"]/*' />
[Serializable]
public abstract class ReadOnlyCollectionBase : ICollection {
ArrayList list;
/// <include file='doc\ReadOnlyCollectionBase.uex' path='docs/doc[@for="ReadOnlyCollectionBase.InnerList"]/*' />
protected ArrayList InnerList {
get {
if (list == null)
list = new ArrayList();
return list;
}
}
/// <include file='doc\ReadOnlyCollectionBase.uex' path='docs/doc[@for="ReadOnlyCollectionBase.Count"]/*' />
public int Count {
get { return InnerList.Count; }
}
/// <include file='doc\ReadOnlyCollectionBase.uex' path='docs/doc[@for="ReadOnlyCollectionBase.ICollection.IsSynchronized"]/*' />
bool ICollection.IsSynchronized {
get { return InnerList.IsSynchronized; }
}
/// <include file='doc\ReadOnlyCollectionBase.uex' path='docs/doc[@for="ReadOnlyCollectionBase.ICollection.SyncRoot"]/*' />
object ICollection.SyncRoot {
get { return InnerList.SyncRoot; }
}
/// <include file='doc\ReadOnlyCollectionBase.uex' path='docs/doc[@for="ReadOnlyCollectionBase.ICollection.CopyTo"]/*' />
void ICollection.CopyTo(Array array, int index) {
InnerList.CopyTo(array, index);
}
/// <include file='doc\ReadOnlyCollectionBase.uex' path='docs/doc[@for="ReadOnlyCollectionBase.GetEnumerator"]/*' />
public IEnumerator GetEnumerator() {
return InnerList.GetEnumerator();
}
}
}
@@ -0,0 +1,957 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: SortedList
**
**
**
** Purpose: A sorted dictionary.
**
** Date: September 21, 1999
**
===========================================================*/
namespace System.Collections {
using System;
// The SortedList class implements a sorted list of keys and values. Entries in
// a sorted list are sorted by their keys and are accessible both by key and by
// index. The keys of a sorted list can be ordered either according to a
// specific IComparer implementation given when the sorted list is
// instantiated, or according to the IComparable implementation provided
// by the keys themselves. In either case, a sorted list does not allow entries
// with duplicate keys.
//
// A sorted list internally maintains two arrays that store the keys and
// values of the entries. The capacity of a sorted list is the allocated
// length of these internal arrays. As elements are added to a sorted list, the
// capacity of the sorted list is automatically increased as required by
// reallocating the internal arrays. The capacity is never automatically
// decreased, but users can call either TrimToSize or
// Capacity explicitly.
//
// The GetKeyList and GetValueList methods of a sorted list
// provides access to the keys and values of the sorted list in the form of
// List implementations. The List objects returned by these
// methods are aliases for the underlying sorted list, so modifications
// made to those lists are directly reflected in the sorted list, and vice
// versa.
//
// The SortedList class provides a convenient way to create a sorted
// copy of another dictionary, such as a Hashtable. For example:
//
// Hashtable h = new Hashtable();
// h.Add(...);
// h.Add(...);
// ...
// SortedList s = new SortedList(h);
//
// The last line above creates a sorted list that contains a copy of the keys
// and values stored in the hashtable. In this particular example, the keys
// will be ordered according to the IComparable interface, which they
// all must implement. To impose a different ordering, SortedList also
// has a constructor that allows a specific IComparer implementation to
// be specified.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList"]/*' />
[Serializable()] public class SortedList : IDictionary, ICloneable
{
private Object[] keys;
private Object[] values;
private int _size;
private int version;
private IComparer comparer;
private KeyList keyList;
private ValueList valueList;
private const int _defaultCapacity = 16;
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to 16, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.SortedList"]/*' />
public SortedList() {
keys = new Object[_defaultCapacity];
values = new Object[_defaultCapacity];
comparer = Comparer.Default;
}
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to 16, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.SortedList1"]/*' />
public SortedList(int initialCapacity) {
if (initialCapacity < 0)
throw new ArgumentOutOfRangeException("initialCapacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
keys = new Object[initialCapacity];
values = new Object[initialCapacity];
comparer = Comparer.Default;
}
// Constructs a new sorted list with a given IComparer
// implementation. The sorted list is initially empty and has a capacity of
// zero. Upon adding the first element to the sorted list the capacity is
// increased to 16, and then increased in multiples of two as required. The
// elements of the sorted list are ordered according to the given
// IComparer implementation. If comparer is null, the
// elements are compared to each other using the IComparable
// interface, which in that case must be implemented by the keys of all
// entries added to the sorted list.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.SortedList2"]/*' />
public SortedList(IComparer comparer)
: this() {
if (comparer != null) this.comparer = comparer;
}
// Constructs a new sorted list with a given IComparer
// implementation and a given initial capacity. The sorted list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required. The elements of the sorted list
// are ordered according to the given IComparer implementation. If
// comparer is null, the elements are compared to each other using
// the IComparable interface, which in that case must be implemented
// by the keys of all entries added to the sorted list.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.SortedList3"]/*' />
public SortedList(IComparer comparer, int capacity)
: this(comparer) {
Capacity = capacity;
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the IComparable interface, which must be implemented by the
// keys of all entries in the the given dictionary as well as keys
// subsequently added to the sorted list.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.SortedList4"]/*' />
public SortedList(IDictionary d)
: this(d, null) {
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the given IComparer implementation. If comparer is
// null, the elements are compared to each other using the
// IComparable interface, which in that case must be implemented
// by the keys of all entries in the the given dictionary as well as keys
// subsequently added to the sorted list.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.SortedList5"]/*' />
public SortedList(IDictionary d, IComparer comparer)
: this(comparer, (d != null ? d.Count : 0)) {
if (d==null)
throw new ArgumentNullException("d", Environment.GetResourceString("ArgumentNull_Dictionary"));
d.Keys.CopyTo(keys, 0);
d.Values.CopyTo(values, 0);
Array.Sort(keys, values, comparer);
_size = d.Count;
}
// Adds an entry with the given key and value to this sorted list. An
// ArgumentException is thrown if the key is already present in the sorted list.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.Add"]/*' />
public virtual void Add(Object key, Object value) {
if (key == null) throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
int i = Array.BinarySearch(keys, 0, _size, key, comparer);
if (i >= 0)
throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate__", GetKey(i), key));
Insert(~i, key, value);
}
// Returns the capacity of this sorted list. The capacity of a sorted list
// represents the allocated length of the internal arrays used to store the
// keys and values of the list, and thus also indicates the maximum number
// of entries the list can contain before a reallocation of the internal
// arrays is required.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.Capacity"]/*' />
public virtual int Capacity {
get {
return keys.Length;
}
set {
if (value != keys.Length) {
if (value < _size) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
if (value > 0) {
Object[] newKeys = new Object[value];
Object[] newValues = new Object[value];
if (_size > 0) {
Array.Copy(keys, 0, newKeys, 0, _size);
Array.Copy(values, 0, newValues, 0, _size);
}
keys = newKeys;
values = newValues;
}
else {
keys = new Object[_defaultCapacity];
values = new Object[_defaultCapacity];
}
}
}
}
// Returns the number of entries in this sorted list.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.Count"]/*' />
public virtual int Count {
get {
return _size;
}
}
// Returns a collection representing the keys of this sorted list. This
// method returns the same object as GetKeyList, but typed as an
// ICollection instead of an IList.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.Keys"]/*' />
public virtual ICollection Keys {
get {
return GetKeyList();
}
}
// Returns a collection representing the values of this sorted list. This
// method returns the same object as GetValueList, but typed as an
// ICollection instead of an IList.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.Values"]/*' />
public virtual ICollection Values {
get {
return GetValueList();
}
}
// Is this SortedList read-only?
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.IsReadOnly"]/*' />
public virtual bool IsReadOnly {
get { return false; }
}
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.IsFixedSize"]/*' />
public virtual bool IsFixedSize {
get { return false; }
}
// Is this SortedList synchronized (thread-safe)?
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.IsSynchronized"]/*' />
public virtual bool IsSynchronized {
get { return false; }
}
// Synchronization root for this object.
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.SyncRoot"]/*' />
public virtual Object SyncRoot {
get { return this; }
}
// Removes all entries from this sorted list.
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.Clear"]/*' />
public virtual void Clear() {
version++;
_size = 0;
keys = new Object[_defaultCapacity];
values = new Object[_defaultCapacity];
}
// Makes a virtually identical copy of this SortedList. This is a shallow
// copy. IE, the Objects in the SortedList are not cloned - we copy the
// references to those objects.
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.Clone"]/*' />
public virtual Object Clone()
{
SortedList sl = new SortedList(_size);
Array.Copy(keys, 0, sl.keys, 0, _size);
Array.Copy(values, 0, sl.values, 0, _size);
sl._size = _size;
sl.version = version;
sl.comparer = comparer;
// Don't copy keyList nor valueList.
return sl;
}
// Checks if this sorted list contains an entry with the given key.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.Contains"]/*' />
public virtual bool Contains(Object key) {
return IndexOfKey(key) >= 0;
}
// Checks if this sorted list contains an entry with the given key.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.ContainsKey"]/*' />
public virtual bool ContainsKey(Object key) {
// Yes, this is a SPEC'ed duplicate of Contains().
return IndexOfKey(key) >= 0;
}
// Checks if this sorted list contains an entry with the given value. The
// values of the entries of the sorted list are compared to the given value
// using the Object.Equals method. This method performs a linear
// search and is substantially slower than the Contains
// method.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.ContainsValue"]/*' />
public virtual bool ContainsValue(Object value) {
return IndexOfValue(value) >= 0;
}
// Copies the values in this SortedList to an array.
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.CopyTo"]/*' />
public virtual void CopyTo(Array array, int arrayIndex) {
if (array == null)
throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Array"));
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - arrayIndex < Count)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
for (int i = 0; i<Count; i++) {
DictionaryEntry entry = new DictionaryEntry(keys[i],values[i]);
array.SetValue(entry, i + arrayIndex);
}
}
// Ensures that the capacity of this sorted list is at least the given
// minimum value. If the currect capacity of the list is less than
// min, the capacity is increased to twice the current capacity or
// to min, whichever is larger.
private void EnsureCapacity(int min) {
int newCapacity = keys.Length == 0? 16: keys.Length * 2;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
// Returns the value of the entry at the given index.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.GetByIndex"]/*' />
public virtual Object GetByIndex(int index) {
if (index < 0 || index >= _size)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
return values[index];
}
// Returns an IEnumerator for this sorted list. If modifications
// made to the sorted list while an enumeration is in progress,
// the MoveNext and Remove methods
// of the enumerator will throw an exception.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.IEnumerable.GetEnumerator"]/*' />
IEnumerator IEnumerable.GetEnumerator() {
return new SortedListEnumerator(this, 0, _size, SortedListEnumerator.DictEntry);
}
// Returns an IDictionaryEnumerator for this sorted list. If modifications
// made to the sorted list while an enumeration is in progress,
// the MoveNext and Remove methods
// of the enumerator will throw an exception.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.GetEnumerator"]/*' />
public virtual IDictionaryEnumerator GetEnumerator() {
return new SortedListEnumerator(this, 0, _size, SortedListEnumerator.DictEntry);
}
// Returns the key of the entry at the given index.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.GetKey"]/*' />
public virtual Object GetKey(int index) {
if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
return keys[index];
}
// Returns an IList representing the keys of this sorted list. The
// returned list is an alias for the keys of this sorted list, so
// modifications made to the returned list are directly reflected in the
// underlying sorted list, and vice versa. The elements of the returned
// list are ordered in the same way as the elements of the sorted list. The
// returned list does not support adding, inserting, or modifying elements
// (the Add, AddRange, Insert, InsertRange,
// Reverse, Set, SetRange, and Sort methods
// throw exceptions), but it does allow removal of elements (through the
// Remove and RemoveRange methods or through an enumerator).
// Null is an invalid key value.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.GetKeyList"]/*' />
public virtual IList GetKeyList() {
if (keyList == null) keyList = new KeyList(this);
return keyList;
}
// Returns an IList representing the values of this sorted list. The
// returned list is an alias for the values of this sorted list, so
// modifications made to the returned list are directly reflected in the
// underlying sorted list, and vice versa. The elements of the returned
// list are ordered in the same way as the elements of the sorted list. The
// returned list does not support adding or inserting elements (the
// Add, AddRange, Insert and InsertRange
// methods throw exceptions), but it does allow modification and removal of
// elements (through the Remove, RemoveRange, Set and
// SetRange methods or through an enumerator).
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.GetValueList"]/*' />
public virtual IList GetValueList() {
if (valueList == null) valueList = new ValueList(this);
return valueList;
}
// Returns the value associated with the given key. If an entry with the
// given key is not found, the returned value is null.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.this"]/*' />
public virtual Object this[Object key] {
get {
int i = IndexOfKey(key);
if (i >= 0) return values[i];
return null;
}
set {
if (key == null) throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
int i = Array.BinarySearch(keys, 0, _size, key, comparer);
if (i >= 0) {
values[i] = value;
version++;
return;
}
Insert(~i, key, value);
}
}
// Returns the index of the entry with a given key in this sorted list. The
// key is located through a binary search, and thus the average execution
// time of this method is proportional to Log2(size), where
// size is the size of this sorted list. The returned value is -1 if
// the given key does not occur in this sorted list. Null is an invalid
// key value.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.IndexOfKey"]/*' />
public virtual int IndexOfKey(Object key) {
if (key == null)
throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
int ret = Array.BinarySearch(keys, 0, _size, key, comparer);
return ret >=0 ? ret : -1;
}
// Returns the index of the first occurrence of an entry with a given value
// in this sorted list. The entry is located through a linear search, and
// thus the average execution time of this method is proportional to the
// size of this sorted list. The elements of the list are compared to the
// given value using the Object.Equals method.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.IndexOfValue"]/*' />
public virtual int IndexOfValue(Object value) {
return Array.IndexOf(values, value, 0, _size);
}
// Inserts an entry with a given key and value at a given index.
private void Insert(int index, Object key, Object value) {
if (_size == keys.Length) EnsureCapacity(_size + 1);
if (index < _size) {
Array.Copy(keys, index, keys, index + 1, _size - index);
Array.Copy(values, index, values, index + 1, _size - index);
}
keys[index] = key;
values[index] = value;
_size++;
version++;
}
// Removes the entry at the given index. The size of the sorted list is
// decreased by one.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.RemoveAt"]/*' />
public virtual void RemoveAt(int index) {
if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
_size--;
if (index < _size) {
Array.Copy(keys, index + 1, keys, index, _size - index);
Array.Copy(values, index + 1, values, index, _size - index);
}
keys[_size] = null;
values[_size] = null;
version++;
}
// Removes an entry from this sorted list. If an entry with the specified
// key exists in the sorted list, it is removed. An ArgumentException is
// thrown if the key is null.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.Remove"]/*' />
public virtual void Remove(Object key) {
int i = IndexOfKey(key);
if (i >= 0)
RemoveAt(i);
}
// Sets the value at an index to a given value. The previous value of
// the given entry is overwritten.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.SetByIndex"]/*' />
public virtual void SetByIndex(int index, Object value) {
if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
values[index] = value;
version++;
}
// Returns a thread-safe SortedList.
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.Synchronized"]/*' />
public static SortedList Synchronized(SortedList list) {
if (list==null)
throw new ArgumentNullException("list");
return new SyncSortedList(list);
}
// Sets the capacity of this sorted list to the size of the sorted list.
// This method can be used to minimize a sorted list's memory overhead once
// it is known that no new elements will be added to the sorted list. To
// completely clear a sorted list and release all memory referenced by the
// sorted list, execute the following statements:
//
// sortedList.Clear();
// sortedList.TrimToSize();
//
/// <include file='doc\SortedList.uex' path='docs/doc[@for="SortedList.TrimToSize"]/*' />
public virtual void TrimToSize() {
Capacity = _size;
}
[Serializable()]
private class SyncSortedList : SortedList
{
private SortedList _list;
private Object _root;
internal SyncSortedList(SortedList list) {
_list = list;
_root = list.SyncRoot;
}
public override int Count {
get { lock(_root) { return _list.Count; } }
}
public override Object SyncRoot {
get { return _root; }
}
public override bool IsReadOnly {
get { return _list.IsReadOnly; }
}
public override bool IsFixedSize {
get { return _list.IsFixedSize; }
}
public override bool IsSynchronized {
get { return true; }
}
public override Object this[Object key] {
get {
lock(_root) {
return _list[key];
}
}
set {
lock(_root) {
_list[key] = value;
}
}
}
public override void Add(Object key, Object value) {
lock(_root) {
_list.Add(key, value);
}
}
public override int Capacity {
get{ lock(_root) { return _list.Capacity; } }
}
public override void Clear() {
lock(_root) {
_list.Clear();
}
}
public override Object Clone() {
lock(_root) {
return _list.Clone();
}
}
public override bool Contains(Object key) {
lock(_root) {
return _list.Contains(key);
}
}
public override bool ContainsKey(Object key) {
lock(_root) {
return _list.ContainsKey(key);
}
}
public override bool ContainsValue(Object key) {
lock(_root) {
return _list.ContainsValue(key);
}
}
public override void CopyTo(Array array, int index) {
lock(_root) {
_list.CopyTo(array, index);
}
}
public override Object GetByIndex(int index) {
lock(_root) {
return _list.GetByIndex(index);
}
}
public override IDictionaryEnumerator GetEnumerator() {
lock(_root) {
return _list.GetEnumerator();
}
}
public override Object GetKey(int index) {
lock(_root) {
return _list.GetKey(index);
}
}
public override IList GetKeyList() {
lock(_root) {
return _list.GetKeyList();
}
}
public override IList GetValueList() {
lock(_root) {
return _list.GetValueList();
}
}
public override int IndexOfKey(Object key) {
lock(_root) {
return _list.IndexOfKey(key);
}
}
public override int IndexOfValue(Object value) {
lock(_root) {
return _list.IndexOfValue(value);
}
}
public override void RemoveAt(int index) {
lock(_root) {
_list.RemoveAt(index);
}
}
public override void Remove(Object key) {
lock(_root) {
_list.Remove(key);
}
}
public override void SetByIndex(int index, Object value) {
lock(_root) {
_list.SetByIndex(index, value);
}
}
public override void TrimToSize() {
lock(_root) {
_list.TrimToSize();
}
}
}
[Serializable()] private class SortedListEnumerator : IDictionaryEnumerator, ICloneable
{
private SortedList sortedList;
private Object key;
private Object value;
private int index;
private int startIndex; // Store for Reset.
private int endIndex;
private int version;
private bool current; // Is the current element valid?
private int getObjectRetType; // What should GetObject return?
internal const int Keys = 1;
internal const int Values = 2;
internal const int DictEntry = 3;
internal SortedListEnumerator(SortedList sortedList, int index, int count,
int getObjRetType) {
this.sortedList = sortedList;
this.index = index;
startIndex = index;
endIndex = index + count;
version = sortedList.version;
getObjectRetType = getObjRetType;
current = false;
}
public Object Clone()
{
return MemberwiseClone();
}
public virtual Object Key {
get {
if (version != sortedList.version) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
if (current == false) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
return key;
}
}
public virtual bool MoveNext() {
if (version != sortedList.version) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
if (index < endIndex) {
key = sortedList.keys[index];
value = sortedList.values[index];
index++;
current = true;
return true;
}
key = null;
value = null;
current = false;
return false;
}
public virtual DictionaryEntry Entry {
get {
if (version != sortedList.version) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
if (current == false) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
return new DictionaryEntry(key, value);
}
}
public virtual Object Current {
get {
if (current == false) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
if (getObjectRetType==Keys)
return key;
else if (getObjectRetType==Values)
return value;
else
return new DictionaryEntry(key, value);
}
}
public virtual Object Value {
get {
if (version != sortedList.version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
if (current == false) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
return value;
}
}
public virtual void Reset() {
if (version != sortedList.version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
index = startIndex;
current = false;
key = null;
value = null;
}
}
[Serializable()] private class KeyList : IList
{
private SortedList sortedList;
internal KeyList(SortedList sortedList) {
this.sortedList = sortedList;
}
public virtual int Count {
get { return sortedList._size; }
}
public virtual bool IsReadOnly {
get { return true; }
}
public virtual bool IsFixedSize {
get { return true; }
}
public virtual bool IsSynchronized {
get { return sortedList.IsSynchronized; }
}
public virtual Object SyncRoot {
get { return sortedList.SyncRoot; }
}
public virtual int Add(Object key) {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
// return 0; // suppress compiler warning
}
public virtual void Clear() {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
public virtual bool Contains(Object key) {
return sortedList.Contains(key);
}
public virtual void CopyTo(Array array, int arrayIndex) {
if (array != null && array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
// defer error checking to Array.Copy
Array.Copy(sortedList.keys, 0, array, arrayIndex, sortedList.Count);
}
public virtual void Insert(int index, Object value) {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
public virtual Object this[int index] {
get {
return sortedList.GetKey(index);
}
set {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_KeyCollectionSet"));
}
}
public virtual IEnumerator GetEnumerator() {
return new SortedListEnumerator(sortedList, 0, sortedList.Count, SortedListEnumerator.Keys);
}
public virtual int IndexOf(Object key) {
if (key==null)
throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
int i = Array.BinarySearch(sortedList.keys, 0,
sortedList.Count, key, sortedList.comparer);
if (i >= 0) return i;
return -1;
}
public virtual void Remove(Object key) {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
public virtual void RemoveAt(int index) {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
}
[Serializable()] private class ValueList : IList
{
private SortedList sortedList;
internal ValueList(SortedList sortedList) {
this.sortedList = sortedList;
}
public virtual int Count {
get { return sortedList._size; }
}
public virtual bool IsReadOnly {
get { return true; }
}
public virtual bool IsFixedSize {
get { return true; }
}
public virtual bool IsSynchronized {
get { return sortedList.IsSynchronized; }
}
public virtual Object SyncRoot {
get { return sortedList.SyncRoot; }
}
public virtual int Add(Object key) {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
public virtual void Clear() {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
public virtual bool Contains(Object value) {
return sortedList.ContainsValue(value);
}
public virtual void CopyTo(Array array, int arrayIndex) {
if (array != null && array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
// defer error checking to Array.Copy
Array.Copy(sortedList.values, 0, array, arrayIndex, sortedList.Count);
}
public virtual void Insert(int index, Object value) {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
public virtual Object this[int index] {
get {
return sortedList.GetByIndex(index);
}
set {
sortedList.SetByIndex(index,value);
}
}
public virtual IEnumerator GetEnumerator() {
return new SortedListEnumerator(sortedList, 0, sortedList.Count, SortedListEnumerator.Values);
}
public virtual int IndexOf(Object value) {
return Array.IndexOf(sortedList.values, value, 0, sortedList.Count);
}
public virtual void Remove(Object value) {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
public virtual void RemoveAt(int index) {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_SortedListNestedWrite));
}
}
}
}
+352
View File
@@ -0,0 +1,352 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: Stack
**
**
**
** Purpose: An array implementation of a stack.
**
** Date: October 7, 1999
**
=============================================================================*/
namespace System.Collections {
using System;
// A simple stack of objects. Internally it is implemented as an array,
// so Push can be O(n). Pop is O(1).
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack"]/*' />
[Serializable()] public class Stack : ICollection, ICloneable {
private Object[] _array; // Storage for stack elements
private int _size; // Number of items in the stack.
private int _version; // Used to keep enumerator in sync w/ collection.
private const int _defaultCapacity = 10;
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack"]/*' />
public Stack() {
_array = new Object[_defaultCapacity];
_size = 0;
_version = 0;
}
// Create a stack with a specific initial capacity. The initial capacity
// must be a non-negative number.
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack1"]/*' />
public Stack(int initialCapacity) {
if (initialCapacity < 0)
throw new ArgumentOutOfRangeException("initialCapacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (initialCapacity < _defaultCapacity)
initialCapacity = _defaultCapacity; // Simplify doubling logic in Push.
_array = new Object[initialCapacity];
_size = 0;
_version = 0;
}
// Fills a Stack with the contents of a particular collection. The items are
// pushed onto the stack in the same order they are read by the enumerator.
//
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Stack2"]/*' />
public Stack(ICollection col) : this((col==null ? 32 : col.Count))
{
if (col==null)
throw new ArgumentNullException("col");
IEnumerator en = col.GetEnumerator();
while(en.MoveNext())
Push(en.Current);
}
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Count"]/*' />
public virtual int Count {
get { return _size; }
}
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.IsSynchronized"]/*' />
public virtual bool IsSynchronized {
get { return false; }
}
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.SyncRoot"]/*' />
public virtual Object SyncRoot {
get { return this; }
}
// Removes all Objects from the Stack.
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Clear"]/*' />
public virtual void Clear() {
Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
_size = 0;
_version++;
}
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Clone"]/*' />
public virtual Object Clone() {
Stack s = new Stack(_size);
s._size = _size;
Array.Copy(_array, 0, s._array, 0, _size);
s._version = _version;
return s;
}
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Contains"]/*' />
public virtual bool Contains(Object obj) {
int count = _size;
while (count-- > 0) {
if (obj == null) {
if (_array[count] == null)
return true;
}
else if (obj.Equals(_array[count])) {
return true;
}
}
return false;
}
// Copies the stack into an array.
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.CopyTo"]/*' />
public virtual void CopyTo(Array array, int index) {
if (array==null)
throw new ArgumentNullException("array");
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - index < _size)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
int i = 0;
if (array is Object[]) {
Object[] objArray = (Object[]) array;
while(i < _size) {
objArray[i+index] = _array[_size-i-1];
i++;
}
}
else {
while(i < _size) {
array.SetValue(_array[_size-i-1], i+index);
i++;
}
}
}
// Returns an IEnumerator for this Stack.
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.GetEnumerator"]/*' />
public virtual IEnumerator GetEnumerator() {
return new StackEnumerator(this);
}
// Returns the top object on the stack without removing it. If the stack
// is empty, Peek throws an InvalidOperationException.
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Peek"]/*' />
public virtual Object Peek() {
if (_size==0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EmptyStack"));
return _array[_size-1];
}
// Pops an item from the top of the stack. If the stack is empty, Pop
// throws an InvalidOperationException.
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Pop"]/*' />
public virtual Object Pop() {
if (_size == 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EmptyStack"));
_version++;
Object obj = _array[--_size];
_array[_size] = null; // Free memory quicker.
return obj;
}
// Pushes an item to the top of the stack.
//
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Push"]/*' />
public virtual void Push(Object obj) {
if (_size == _array.Length) {
Object[] newArray = new Object[2*_array.Length];
Array.Copy(_array, 0, newArray, 0, _size);
_array = newArray;
}
_array[_size++] = obj;
_version++;
}
// Returns a synchronized Stack.
//
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Synchronized"]/*' />
public static Stack Synchronized(Stack stack) {
if (stack==null)
throw new ArgumentNullException("stack");
return new SyncStack(stack);
}
// Copies the Stack to an array, in the same order Pop would return the items.
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.ToArray"]/*' />
public virtual Object[] ToArray()
{
Object[] objArray = new Object[_size];
int i = 0;
while(i < _size) {
objArray[i] = _array[_size-i-1];
i++;
}
return objArray;
}
[Serializable()] private class SyncStack : Stack
{
private Stack _s;
private Object _root;
internal SyncStack(Stack stack) {
_s = stack;
_root = stack.SyncRoot;
}
public override bool IsSynchronized {
get { return true; }
}
public override Object SyncRoot {
get {
return _root;
}
}
public override int Count {
get {
lock (_root) {
return _s.Count;
}
}
}
public override bool Contains(Object obj) {
lock (_root) {
return _s.Contains(obj);
}
}
public override Object Clone()
{
lock (_root) {
return new SyncStack((Stack)_s.Clone());
}
}
public override void Clear() {
lock (_root) {
_s.Clear();
}
}
public override void CopyTo(Array array, int arrayIndex) {
lock (_root) {
_s.CopyTo(array, arrayIndex);
}
}
public override void Push(Object value) {
lock (_root) {
_s.Push(value);
}
}
public override Object Pop() {
lock (_root) {
return _s.Pop();
}
}
public override IEnumerator GetEnumerator() {
lock (_root) {
return _s.GetEnumerator();
}
}
public override Object Peek() {
lock (_root) {
return _s.Peek();
}
}
public override Object[] ToArray() {
lock (_root) {
return _s.ToArray();
}
}
}
[Serializable()] private class StackEnumerator : IEnumerator, ICloneable
{
private Stack _stack;
private int _index;
private int _version;
private Object currentElement;
internal StackEnumerator(Stack stack) {
_stack = stack;
_version = _stack._version;
_index = -2;
currentElement = null;
}
public Object Clone()
{
return MemberwiseClone();
}
public virtual bool MoveNext() {
bool retval;
if (_version != _stack._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
if (_index == -2) { // First call to enumerator.
_index = _stack._size-1;
retval = ( _index >= 0);
if (retval)
currentElement = _stack._array[_index];
return retval;
}
if (_index == -1) { // End of enumeration.
return false;
}
retval = (--_index >= 0);
if (retval)
currentElement = _stack._array[_index];
else
currentElement = null;
return retval;
}
public virtual Object Current {
get {
if (_index == -2) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
if (_index == -1) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
return currentElement;
}
}
public virtual void Reset() {
if (_version != _stack._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
_index = -2;
currentElement = null;
}
}
}
}
@@ -0,0 +1,86 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** File: AssemblyHash
**
**
**
** Purpose:
**
** Date: June 4, 1999
**
===========================================================*/
namespace System.Configuration.Assemblies {
using System;
/// <include file='doc\AssemblyHash.uex' path='docs/doc[@for="AssemblyHash"]/*' />
[Serializable()]
public struct AssemblyHash : ICloneable
{
private AssemblyHashAlgorithm _Algorithm;
private byte[] _Value;
/// <include file='doc\AssemblyHash.uex' path='docs/doc[@for="AssemblyHash.Empty"]/*' />
public static readonly AssemblyHash Empty = new AssemblyHash(AssemblyHashAlgorithm.None, null);
/// <include file='doc\AssemblyHash.uex' path='docs/doc[@for="AssemblyHash.AssemblyHash"]/*' />
public AssemblyHash(byte[] value) {
_Algorithm = AssemblyHashAlgorithm.SHA1;
_Value = null;
if (value != null) {
int length = value.Length;
_Value = new byte[length];
Array.Copy(value, _Value, length);
}
}
/// <include file='doc\AssemblyHash.uex' path='docs/doc[@for="AssemblyHash.AssemblyHash1"]/*' />
public AssemblyHash(AssemblyHashAlgorithm algorithm, byte[] value) {
_Algorithm = algorithm;
_Value = null;
if (value != null) {
int length = value.Length;
_Value = new byte[length];
Array.Copy(value, _Value, length);
}
}
// Hash is made up of a byte array and a value from a class of supported
// algorithm types.
/// <include file='doc\AssemblyHash.uex' path='docs/doc[@for="AssemblyHash.Algorithm"]/*' />
public AssemblyHashAlgorithm Algorithm {
get { return _Algorithm; }
set { _Algorithm = value; }
}
/// <include file='doc\AssemblyHash.uex' path='docs/doc[@for="AssemblyHash.GetValue"]/*' />
public byte[] GetValue() {
return _Value;
}
/// <include file='doc\AssemblyHash.uex' path='docs/doc[@for="AssemblyHash.SetValue"]/*' />
public void SetValue(byte[] value) {
_Value = value;
}
/// <include file='doc\AssemblyHash.uex' path='docs/doc[@for="AssemblyHash.Clone"]/*' />
public Object Clone() {
return new AssemblyHash(_Algorithm, _Value);
}
}
}
@@ -0,0 +1,40 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** File: AssemblyHashAlgorithm
**
**
**
** Purpose:
**
** Date: June 4, 1999
**
===========================================================*/
namespace System.Configuration.Assemblies {
using System;
/// <include file='doc\AssemblyHashAlgorithm.uex' path='docs/doc[@for="AssemblyHashAlgorithm"]/*' />
[Serializable]
public enum AssemblyHashAlgorithm
{
/// <include file='doc\AssemblyHashAlgorithm.uex' path='docs/doc[@for="AssemblyHashAlgorithm.None"]/*' />
None = 0,
/// <include file='doc\AssemblyHashAlgorithm.uex' path='docs/doc[@for="AssemblyHashAlgorithm.MD5"]/*' />
MD5 = 0x8003,
/// <include file='doc\AssemblyHashAlgorithm.uex' path='docs/doc[@for="AssemblyHashAlgorithm.SHA1"]/*' />
SHA1 = 0x8004
}
}
@@ -0,0 +1,40 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** File: AssemblyVersionCompatibility
**
**
**
** Purpose: defining the different flavor's assembly version compatibility
**
** Date: June 4, 1999
**
===========================================================*/
namespace System.Configuration.Assemblies {
using System;
/// <include file='doc\AssemblyVersionCompatibility.uex' path='docs/doc[@for="AssemblyVersionCompatibility"]/*' />
[Serializable()]
public enum AssemblyVersionCompatibility
{
/// <include file='doc\AssemblyVersionCompatibility.uex' path='docs/doc[@for="AssemblyVersionCompatibility.SameMachine"]/*' />
SameMachine = 1,
/// <include file='doc\AssemblyVersionCompatibility.uex' path='docs/doc[@for="AssemblyVersionCompatibility.SameProcess"]/*' />
SameProcess = 2,
/// <include file='doc\AssemblyVersionCompatibility.uex' path='docs/doc[@for="AssemblyVersionCompatibility.SameDomain"]/*' />
SameDomain = 3,
}
}
+640
View File
@@ -0,0 +1,640 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: Console
**
**
**
** Purpose: This class provides access to the standard input, standard output
** and standard error streams.
**
** Date: March 25, 1999
**
=============================================================================*/
namespace System {
using System;
using System.IO;
using System.Text;
using System.Globalization;
using System.Security.Permissions;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Provides static fields for console input &; output. Use
// Console.In for input from the standard input stream (stdin),
// Console.Out for output to stdout, and Console.Error
// for output to stderr. If any of those console streams are
// redirected from the command line, these streams will be redirected.
// A program can also redirect its own output or input with the
// SetIn, SetOut, and SetError methods.
//
// The distinction between Console.Out &; Console.Error is useful
// for programs that redirect output to a file or a pipe. Note that
// stdout &; stderr can be output to different files at the same
// time from the DOS command line:
//
// someProgram 1> out 2> err
//
//Contains only static data. Serializable attribute not required.
/// <include file='doc\Console.uex' path='docs/doc[@for="Console"]/*' />
public sealed class Console
{
private Console()
{
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Constructor));
}
private const int _DefaultConsoleBufferSize = 256;
private static TextReader _in;
private static TextWriter _out;
private static TextWriter _error;
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Error"]/*' />
public static TextWriter Error {
get { return _error; }
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.In"]/*' />
public static TextReader In {
get {
// Because most applications don't use stdin, we can delay
// initialize it slightly better startup performance.
if (_in == null) {
lock(typeof(Console)) {
if (_in == null) {
// Set up Console.In
Stream s = OpenStandardInput(_DefaultConsoleBufferSize);
if (s == Stream.Null) {
_in = StreamReader.Null;
}
else {
// To avoid loading about 7 classes, don't call Encoding.GetEncoding(int)
Encoding enc = new CodePageEncoding(GetConsoleCPNative());
_in = TextReader.Synchronized(new StreamReader(s, enc, false, _DefaultConsoleBufferSize));
}
}
}
}
return _in;
}
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Out"]/*' />
public static TextWriter Out {
get { return _out; }
}
static Console() {
// For console apps, the console handles are set to values like 3, 7,
// and 11 OR if you've been created via CreateProcess, possibly -1
// or 0. -1 is definitely invalid, while 0 is probably invalid.
// Also note each handle can independently be bad or good.
// For Windows apps, the console handles are set to values like 3, 7,
// and 11 but are invalid handles - you may not write to them. However,
// you can still spawn a Windows app via CreateProcess and read stdout
// and stderr.
// So, we always need to check each handle independently for validity
// by trying to write or read to it, unless it is -1.
// Delay initialize Console.In until someone uses it.
// Set up Console.Out
Encoding outEnc = null;
Stream s = OpenStandardOutput(_DefaultConsoleBufferSize);
if (s == Stream.Null) {
#if _DEBUG
if (CheckOutputDebug())
_out = MakeDebugOutputTextWriter("Console.Out: ");
else
#endif
_out = TextWriter.Synchronized(StreamWriter.Null);
}
else {
// To avoid loading about 7 classes, don't call Encoding.GetEncoding(int)
outEnc = new CodePageEncoding(GetConsoleOutputCPNative());
StreamWriter stdout = new StreamWriter(s, outEnc, _DefaultConsoleBufferSize);
stdout.AutoFlush = true;
stdout.Closable = !IsStreamAConsole(Win32Native.STD_OUTPUT_HANDLE);
_out = TextWriter.Synchronized(stdout);
}
// Set up Console.Error
s = OpenStandardError(_DefaultConsoleBufferSize);
if (s == Stream.Null) {
#if _DEBUG
if (CheckOutputDebug())
_error = MakeDebugOutputTextWriter("Console.Error: ");
else
#endif
_error = TextWriter.Synchronized(StreamWriter.Null);
}
else {
if (outEnc == null)
outEnc = new CodePageEncoding(GetConsoleOutputCPNative());
StreamWriter stderr = new StreamWriter(s, outEnc, _DefaultConsoleBufferSize);
stderr.AutoFlush = true;
stderr.Closable = !IsStreamAConsole(Win32Native.STD_ERROR_HANDLE);
_error = TextWriter.Synchronized(stderr);
}
}
private static bool IsStreamAConsole(int stdHandleName)
{
// Decide whether the stream is a console device or whether it's a
// file or pipe for purposes of deciding whether we can safely
// disallow closing this stream.
IntPtr handle = Win32Native.GetStdHandle(stdHandleName);
int type = Win32Native.GetFileType(handle) & 0x7FFF;
return (type == Win32Native.FILE_TYPE_CHAR);
}
// This is ONLY used in debug builds. If you have a registry key set,
// it will redirect Console.Out & Error on console-less applications to
// your debugger's output window.
#if _DEBUG
private static bool CheckOutputDebug()
{
const int parameterValueLength = 255;
StringBuilder parameterValue = new StringBuilder(parameterValueLength);
bool rc = Win32Native.FetchConfigurationString(true, "ConsoleSpewToDebugger", parameterValue, parameterValueLength);
if( rc )
{
if(0 != parameterValue.Length)
{
int value = Convert.ToInt32(parameterValue.ToString());
if( 0 != value )
return true;
}
}
return false;
}
#endif
#if _DEBUG
private static TextWriter MakeDebugOutputTextWriter(String streamLabel)
{
TextWriter output = new __DebugOutputTextWriter(streamLabel);
output.WriteLine("Output redirected to debugger from a bit bucket.");
return TextWriter.Synchronized(output);
}
#endif
// This method is only exposed via methods to get at the console.
// We won't use any security checks here.
private static Stream GetStandardFile(int stdHandleName, FileAccess access, int bufferSize) {
IntPtr handle = Win32Native.GetStdHandle(stdHandleName);
// If someone launches a managed process via CreateProcess, stdout
// stderr, & stdin could independently be set to INVALID_HANDLE_VALUE.
if (handle == Win32Native.INVALID_HANDLE_VALUE) {
//BCLDebug.ConsoleError("Console::GetStandardFile for handle "+stdHandleName+" failed, with HRESULT: "+Marshal.GetLastWin32Error()+" Setting it to null.");
return Stream.Null;
}
// Zero appears to not be a valid handle. I haven't gotten GetStdHandle
// to return INVALID_HANDLE_VALUE, as the docs say.
if (handle == IntPtr.Zero) {
//BCLDebug.ConsoleError("Console::GetStandardFile for std handle "+stdHandleName+" succeeded but returned 0. Setting it to null.");
return Stream.Null;
}
// Check whether we can read or write to this handle.
if (stdHandleName != Win32Native.STD_INPUT_HANDLE && 0==ConsoleHandleIsValidNative(handle)) {
//BCLDebug.ConsoleError("Console::ConsoleHandleIsValid for std handle "+stdHandleName+" failed, setting it to a null stream");
return Stream.Null;
}
//BCLDebug.ConsoleError("Console::GetStandardFile for std handle "+stdHandleName+" succeeded, returning handle number "+handle.ToString());
Stream console = new __ConsoleStream(handle, access);
// Do not buffer console streams, or we can get into situations where
// we end up blocking waiting for you to hit enter twice. It was
// a bad idea & generally redundant.
return console;
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.OpenStandardError"]/*' />
public static Stream OpenStandardError() {
return OpenStandardError(_DefaultConsoleBufferSize);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.OpenStandardError1"]/*' />
public static Stream OpenStandardError(int bufferSize) {
return GetStandardFile(Win32Native.STD_ERROR_HANDLE,
FileAccess.Write, bufferSize);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.OpenStandardInput"]/*' />
public static Stream OpenStandardInput() {
return OpenStandardInput(_DefaultConsoleBufferSize);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.OpenStandardInput1"]/*' />
public static Stream OpenStandardInput(int bufferSize) {
return GetStandardFile(Win32Native.STD_INPUT_HANDLE,
FileAccess.Read, bufferSize);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.OpenStandardOutput"]/*' />
public static Stream OpenStandardOutput() {
return OpenStandardOutput(_DefaultConsoleBufferSize);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.OpenStandardOutput1"]/*' />
public static Stream OpenStandardOutput(int bufferSize) {
return GetStandardFile(Win32Native.STD_OUTPUT_HANDLE,
FileAccess.Write, bufferSize);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.SetIn"]/*' />
public static void SetIn(TextReader newIn) {
if (newIn == null)
throw new ArgumentNullException("newIn");
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
newIn = TextReader.Synchronized(newIn);
_in = newIn;
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.SetOut"]/*' />
public static void SetOut(TextWriter newOut) {
if (newOut == null)
throw new ArgumentNullException("newOut");
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
newOut = TextWriter.Synchronized(newOut);
_out = newOut;
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.SetError"]/*' />
public static void SetError(TextWriter newError) {
if (newError == null)
throw new ArgumentNullException("newError");
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
newError = TextWriter.Synchronized(newError);
_error = newError;
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Read"]/*' />
public static int Read()
{
try {
return In.Read();
}
catch (IOException e) {
// Assume that this happened because In was an invalid handle.
if (Marshal.GetHRForException(e) == Win32Native.MakeHRFromErrorCode(Win32Native.ERROR_INVALID_HANDLE)) {
// Set in to something that will give us EOF semantics.
_in = TextReader.Synchronized(StreamReader.Null);
}
else
throw;
}
return -1;
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.ReadLine"]/*' />
public static String ReadLine()
{
try {
return In.ReadLine();
}
catch (IOException e) {
// Assume that this happened because In was an invalid handle.
if (Marshal.GetHRForException(e) == Win32Native.MakeHRFromErrorCode(Win32Native.ERROR_INVALID_HANDLE)) {
// Set in to something that will give us EOF semantics.
_in = TextReader.Synchronized(StreamReader.Null);
}
else
throw;
}
return null;
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine"]/*' />
public static void WriteLine()
{
Out.WriteLine();
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine1"]/*' />
public static void WriteLine(bool value)
{
Out.WriteLine(value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine2"]/*' />
public static void WriteLine(char value)
{
Out.WriteLine(value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine3"]/*' />
public static void WriteLine(char[] buffer)
{
Out.WriteLine(buffer);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine4"]/*' />
public static void WriteLine(char[] buffer, int index, int count)
{
Out.WriteLine(buffer, index, count);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine5"]/*' />
public static void WriteLine(decimal value)
{
Out.WriteLine(value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine6"]/*' />
public static void WriteLine(double value)
{
Out.WriteLine(value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine7"]/*' />
public static void WriteLine(float value)
{
Out.WriteLine(value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine8"]/*' />
public static void WriteLine(int value)
{
Out.WriteLine(value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine9"]/*' />
[CLSCompliant(false)]
public static void WriteLine(uint value)
{
Out.WriteLine(value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine10"]/*' />
public static void WriteLine(long value)
{
Out.WriteLine(value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine11"]/*' />
[CLSCompliant(false)]
public static void WriteLine(ulong value)
{
Out.WriteLine(value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine12"]/*' />
public static void WriteLine(Object value)
{
Out.WriteLine(value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine13"]/*' />
public static void WriteLine(String value)
{
Out.WriteLine(value);
}
//This writes an LPCSTR
// __attribute NonCLSCompliantAttribute()
// public static void WriteLine(byte *value) {
// Out.WriteLine(new String(value));
// }
// __attribute NonCLSCompliantAttribute()
// public static void WriteLine(wchar *value) {
// Out.WriteLine(new String(value));
// }
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine14"]/*' />
public static void WriteLine(String format, Object arg0)
{
Out.WriteLine(format, arg0);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine15"]/*' />
public static void WriteLine(String format, Object arg0, Object arg1)
{
Out.WriteLine(format, arg0, arg1);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine16"]/*' />
public static void WriteLine(String format, Object arg0, Object arg1, Object arg2)
{
Out.WriteLine(format, arg0, arg1, arg2);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine17"]/*' />
[CLSCompliant(false)]
public static void WriteLine(String format, Object arg0, Object arg1, Object arg2,Object arg3, __arglist)
{
Object[] objArgs;
int argCount;
ArgIterator args = new ArgIterator(__arglist);
//+4 to account for the 4 hard-coded arguments at the beginning of the list.
argCount = args.GetRemainingCount() + 4;
objArgs = new Object[argCount];
//Handle the hard-coded arguments
objArgs[0] = arg0;
objArgs[1] = arg1;
objArgs[2] = arg2;
objArgs[3] = arg3;
//Walk all of the args in the variable part of the argument list.
for (int i=4; i<argCount; i++) {
objArgs[i] = TypedReference.ToObject(args.GetNextArg());
}
Out.WriteLine(format, objArgs);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.WriteLine18"]/*' />
public static void WriteLine(String format, params Object[] arg)
{
Out.WriteLine(format, arg);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write"]/*' />
public static void Write(String format, Object arg0)
{
Out.Write(format, arg0);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write1"]/*' />
public static void Write(String format, Object arg0, Object arg1)
{
Out.Write(format, arg0, arg1);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write2"]/*' />
public static void Write(String format, Object arg0, Object arg1, Object arg2)
{
Out.Write(format, arg0, arg1, arg2);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write3"]/*' />
[CLSCompliant(false)]
public static void Write(String format, Object arg0, Object arg1, Object arg2, Object arg3, __arglist)
{
Object[] objArgs;
int argCount;
ArgIterator args = new ArgIterator(__arglist);
//+4 to account for the 4 hard-coded arguments at the beginning of the list.
argCount = args.GetRemainingCount() + 4;
objArgs = new Object[argCount];
//Handle the hard-coded arguments
objArgs[0] = arg0;
objArgs[1] = arg1;
objArgs[2] = arg2;
objArgs[3] = arg3;
//Walk all of the args in the variable part of the argument list.
for (int i=4; i<argCount; i++) {
objArgs[i] = TypedReference.ToObject(args.GetNextArg());
}
Out.Write(format, objArgs);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write4"]/*' />
public static void Write(String format, params Object[] arg)
{
Out.Write(format, arg);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write5"]/*' />
public static void Write(bool value)
{
Out.Write(value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write6"]/*' />
public static void Write(char value)
{
Out.Write(value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write7"]/*' />
public static void Write(char[] buffer)
{
Out.Write(buffer);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write8"]/*' />
public static void Write(char[] buffer, int index, int count)
{
Out.Write(buffer, index, count);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write9"]/*' />
public static void Write(double value)
{
Out.Write (value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write10"]/*' />
public static void Write(decimal value)
{
Out.Write (value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write11"]/*' />
public static void Write(float value)
{
Out.Write (value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write12"]/*' />
public static void Write(int value)
{
Out.Write (value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write13"]/*' />
[CLSCompliant(false)]
public static void Write(uint value)
{
Out.Write (value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write14"]/*' />
public static void Write(long value)
{
Out.Write (value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write15"]/*' />
[CLSCompliant(false)]
public static void Write(ulong value)
{
Out.Write (value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write16"]/*' />
public static void Write(Object value)
{
Out.Write (value);
}
/// <include file='doc\Console.uex' path='docs/doc[@for="Console.Write17"]/*' />
public static void Write(String value)
{
Out.Write (value);
}
// //This writes an LPCSTR
// __attribute NonCLSCompliantAttribute()
// public static void Write(byte *value) {
// Out.Write(new String(value));
// }
// __attribute NonCLSCompliantAttribute()
// public static void Write(wchar *value) {
// Out.Write(new String(value));
// }
// Checks whether stdout or stderr are writable. Do NOT pass
// stdin here.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int ConsoleHandleIsValidNative(IntPtr handle);
// Gets code page for stdin.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int GetConsoleCPNative();
// Gets code page for stdout (and presumably stderr).
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int GetConsoleOutputCPNative();
}
}
+33
View File
@@ -0,0 +1,33 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** File: ContextBoundObject.cs
**
**
** Purpose: Defines the root type for all context bound types
**
** Date: Sep 30, 1999
**
===========================================================*/
namespace System {
using System;
/// <include file='doc\ContextBoundObject.uex' path='docs/doc[@for="ContextBoundObject"]/*' />
[Serializable()]
public abstract class ContextBoundObject : MarshalByRefObject
{
}
}
@@ -0,0 +1,60 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*=============================================================================
**
** Class: ContextMarshalException
**
**
**
** Purpose: Exception class for attempting to pass an instance through a context
** boundary, when the formal type and the instance's marshal style are
** incompatible.
**
** Date: July 6, 1998
**
=============================================================================*/
namespace System {
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System;
using System.Runtime.Serialization;
/// <include file='doc\ContextMarshalException.uex' path='docs/doc[@for="ContextMarshalException"]/*' />
[Serializable()] public class ContextMarshalException : SystemException {
/// <include file='doc\ContextMarshalException.uex' path='docs/doc[@for="ContextMarshalException.ContextMarshalException"]/*' />
public ContextMarshalException()
: base(Environment.GetResourceString("Arg_ContextMarshalException")) {
SetErrorCode(__HResults.COR_E_CONTEXTMARSHAL);
}
/// <include file='doc\ContextMarshalException.uex' path='docs/doc[@for="ContextMarshalException.ContextMarshalException1"]/*' />
public ContextMarshalException(String message)
: base(message) {
SetErrorCode(__HResults.COR_E_CONTEXTMARSHAL);
}
/// <include file='doc\ContextMarshalException.uex' path='docs/doc[@for="ContextMarshalException.ContextMarshalException2"]/*' />
public ContextMarshalException(String message, Exception inner)
: base(message, inner) {
SetErrorCode(__HResults.COR_E_CONTEXTMARSHAL);
}
/// <include file='doc\ContextMarshalException.uex' path='docs/doc[@for="ContextMarshalException.ContextMarshalException3"]/*' />
protected ContextMarshalException(SerializationInfo info, StreamingContext context) : base(info, context) {
}
}
}
@@ -0,0 +1,40 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** File: ContextStaticAttribute.cs
**
**
** Purpose: Custom attribute to indicate that the field should be treated
** as a static relative to a context.
**
**
** Date: Jan 18, 2000
**
===========================================================*/
namespace System {
using System;
using System.Runtime.Remoting;
/// <include file='doc\ContextStaticAttribute.uex' path='docs/doc[@for="ContextStaticAttribute"]/*' />
[AttributeUsage(AttributeTargets.Field, Inherited = false),Serializable]
public class ContextStaticAttribute : Attribute
{
/// <include file='doc\ContextStaticAttribute.uex' path='docs/doc[@for="ContextStaticAttribute.ContextStaticAttribute"]/*' />
public ContextStaticAttribute()
{
}
}
}
File diff suppressed because it is too large Load Diff
+537
View File
@@ -0,0 +1,537 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace System {
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
[Serializable]
internal struct Currency : IFormattable, IComparable
{
// Constant representing the Currency value 0.
public static readonly Currency Zero = new Currency(0);
// Constant representing the Currency value 1.
public static readonly Currency One = new Currency(1);
// Constant representing the Currency value -1.
public static readonly Currency MinusOne = new Currency(-1);
// Constant representing the largest possible Currency value. The
// value of this constant is 922,337,203,685,477.5807.
public static readonly Currency MaxValue = new Currency(0x7FFFFFFFFFFFFFFFL, 0);
// Constant representing the smallest possible Currency value. The
// value of this constant is -922,337,203,685,477.5808.
public static readonly Currency MinValue = new Currency(unchecked((long)0x8000000000000000L), 0);
public static readonly Currency Empty = Zero;
internal const long Scale = 10000;
private const long MinLong = unchecked((long)0x8000000000000000L) / Scale;
private const long MaxLong = 0x7FFFFFFFFFFFFFFFL / Scale;
internal long m_value;
// Constructs a zero Currency.
//public Currency() {
// value = 0;
//}
// Constructs a Currency from an integer value.
//
public Currency(int value) {
m_value = (long)value * Scale;
}
// Constructs a Currency from an unsigned integer value.
//
[CLSCompliant(false)]
public Currency(uint value) {
m_value = (long)value * Scale;
}
// Constructs a Currency from a long value.
//
public Currency(long value) {
if (value < MinLong || value > MaxLong) throw new OverflowException(Environment.GetResourceString("Overflow_Currency"));
m_value = value * Scale;
}
// Constructs a Currency from an unsigned long value.
//
[CLSCompliant(false)]
public Currency(ulong value) {
if (value > (ulong)MaxLong) throw new OverflowException(Environment.GetResourceString("Overflow_Currency"));
m_value = (long)(value * (ulong)Scale);
}
// Constructs a Currency from a float value.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Currency(float value);
// Constructs a Currency from a double value.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Currency(double value);
// Constructs a Currency from a Decimal value.
//
public Currency(Decimal value) {
m_value = Decimal.ToCurrency(value).m_value;
}
// Constructs a Currency from a long value without scaling. The
// ignored parameter exists only to distinguish this constructor
// from the constructor that takes a long. Used only in the System
// package, especially in Variant.
internal Currency(long value, int ignored) {
m_value = value;
}
// Returns the absolute value of the given Currency. If c is
// positive, the result is c. If c is negative, the result
// is -c. If c equals Currency.MinValue, the
// result is Currency.MaxValue.
//
public static Currency Abs(Currency c) {
if (c.m_value >= 0) return c;
if (c.m_value == unchecked((long)0x8000000000000000L)) return Currency.MaxValue;
return new Currency(-c.m_value, 0);
}
// Adds two Currency values.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Currency Add(Currency c1, Currency c2);
// Compares two Currency values, returning an integer that indicates their
// relationship.
//
public static int Compare(Currency c1, Currency c2) {
if (c1.m_value > c2.m_value) return 1;
if (c1.m_value < c2.m_value) return -1;
return 0;
}
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Currency, this method throws an ArgumentException.
//
public int CompareTo(Object value)
{
if (value == null)
return 1;
if (!(value is Currency))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeCurrency"));
return Currency.Compare(this, (Currency)value);
}
// Divides two Currency values, producing a Decimal result.
//
public static Decimal Divide(Currency c1, Currency c2) {
return Decimal.Divide(new Decimal(c1), new Decimal(c2));
}
// Checks if this Currency is equal to a given object. Returns
// true if the given object is a boxed Currency and its value
// is equal to the value of this Currency. Returns false
// otherwise.
//
public override bool Equals(Object value) {
if (value is Currency) {
return m_value == ((Currency)value).m_value;
}
return false;
}
// Compares two Currency values for equality. Returns true if
// the two Currency values are equal, or false if they are
// not equal.
//
public static bool Equals(Currency c1, Currency c2) {
return c1.m_value == c2.m_value;
}
// Rounds a Currency to an integer value. The Currency
// argument is rounded towards negative infinity.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Currency Floor(Currency c);
public static String Format(Currency value, String format) {
return Format(value, format, null);
}
public static String Format(Currency value, String format, NumberFormatInfo info) {
if (info == null) info = NumberFormatInfo.CurrentInfo;
return Number.FormatDecimal(ToDecimal(value), format, info);
}
public String ToString(String format, IFormatProvider provider) {
return Number.FormatDecimal(ToDecimal(this), format, NumberFormatInfo.GetInstance(provider));
}
// Constructs a Currency from a string. The string must consist of an
// optional minus sign ("-") followed by a sequence of digits ("0" - "9").
// The sequence of digits may optionally contain a single decimal point
// (".") character. Leading and trailing whitespace characters are allowed.
//
// FromString uses the invariant NumberFormatInfo, not the
// NumberFormatInfo for the user's current culture. See Parse for that
// functionality.
//
public static Currency FromString(String s) {
return Parse(s, NumberStyles.Currency, NumberFormatInfo.InvariantInfo);
}
// Creates a Currency from an OLE Automation Currency. This method
// applies no scaling to the Currency value, essentially doing a bitwise
// copy.
//
public static Currency FromOACurrency(long cy)
{
return new Currency(cy, 0);
}
// Returns the hash code for this Currency.
//
public override int GetHashCode() {
return (int)m_value ^ (int)(m_value >> 32);
}
// Returns the larger of two Currency values.
//
public static Currency Max(Currency c1, Currency c2) {
return c1.m_value >= c2.m_value? c1: c2;
}
// Returns the smaller of two Currency values.
//
public static Currency Min(Currency c1, Currency c2) {
return c1.m_value <= c2.m_value? c1: c2;
}
// Multiplies two Currency values, producing a Decimal
// result.
//
public static Decimal Multiply(Currency c1, Currency c2) {
return Decimal.Multiply(new Decimal(c1), new Decimal(c2));
}
// Returns the negated value of the given Currency. If c is
// non-zero, the result is -c. If c is zero, the result is
// zero.
//
public static Currency Negate(Currency c) {
if (c.m_value == unchecked((long)0x8000000000000000L)) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum"));
return new Currency(-c.m_value, 0);
}
// Constructs a Currency from a string in a culture-sensitive way.
// The string must consist of an optional minus sign ("-") followed by a
// sequence of digits ("0" - "9"). The sequence of digits may optionally
// contain a single decimal point (".") character. Leading and trailing
// whitespace characters are allowed.
//
public static Currency Parse(String s) {
return Parse(s, NumberStyles.Currency, null);
}
public static Currency Parse(String s, NumberStyles style) {
return Parse(s, style, null);
}
public static Currency Parse(String s, NumberStyles style, NumberFormatInfo info) {
if (info == null) info = NumberFormatInfo.CurrentInfo;
return Decimal.ToCurrency(Number.ParseDecimal(s, style, info));
}
// Rounds a Currency value to a given number of decimal places. The value
// given by c is rounded to the number of decimal places given by
// decimals. The decimals argument must be an integer between
// 0 and 4 inclusive.
//
// The operation Currency.Round(c, dec) conceptually
// corresponds to evaluating Currency.Truncate(c *
// 10dec + delta) / 10dec, where
// delta is 0.5 for positive values of c and -0.5 for
// negative values of c.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Currency Round(Currency c, int decimals);
// Subtracts two Currency values.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Currency Subtract(Currency c1, Currency c2);
// Creates an OLE Automation Currency from a Currency instance. This
// method applies no scaling to the Currency value, essentially doing
// a bitwise copy.
//
public long ToOACurrency()
{
return m_value;
}
// Converts a Currency to a Decimal.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Decimal ToDecimal(Currency c);
// Converts a Currency to a double. Since a double has fewer
// significant digits than a Currency, this operation may produce
// round-off errors.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double ToDouble(Currency c);
// Converts a Currency to an integer. The Currency value is
// rounded towards zero to the nearest integer value, and the result of
// this operation is returned as an integer.
//
public static int ToInt32(Currency c) {
// Done this way to avoid truncation from Cy to int - roundoff error.
if (c.m_value < Scale*Int32.MinValue || c.m_value > Scale*Int32.MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
return (int) (c.m_value / Scale);
}
// Converts a Currency to a long. The Currency value is
// rounded towards zero to the nearest integer value, and the result of
// this operation is returned as a long.
//
public static long ToInt64(Currency c) {
return c.m_value / Scale;
}
// Converts a Currency to a float. Since a float has fewer
// significant digits than a Currency, this operation may produce
// round-off errors.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float ToSingle(Currency c);
// Converts this Currency to a string. The resulting string consists
// of an optional minus sign ("-") followed to a sequence of digits ("0" -
// "9"), optionally followed by a decimal point (".") and another sequence
// of digits.
//
public override String ToString() {
return ToString(null, NumberFormatInfo.InvariantInfo);
}
// Converts a Currency to a string. The resulting string consists of
// an optional minus sign ("-") followed to a sequence of digits ("0" -
// "9"), optionally followed by a decimal point (".") and another sequence
// of digits.
//
public static String ToString(Currency c) {
return Format(c, null, NumberFormatInfo.InvariantInfo);
}
// Converts a Currency to an unsigned 32 bit integer. The
// Currency value is rounded towards zero to the nearest
// integer value, and the result of this operation is returned as
// a UInt32.
//
[CLSCompliant(false)]
public static uint ToUInt32(Currency c) {
// Done this way to avoid truncation from Cy to int - roundoff error.
if (c.m_value < UInt32.MinValue || c.m_value > Scale*UInt32.MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_UInt32"));
return (uint) (c.m_value / Scale);
}
// Converts a Currency to an unsigned 64 bit int. The
// Currency value is rounded towards zero to the nearest
// integer value, and the result of this operation is returned as
// a UInt64.
//
[CLSCompliant(false)]
public static ulong ToUInt64(Currency c) {
if (c.m_value < 0)
throw new OverflowException(Environment.GetResourceString("Overflow_UInt64"));
return (ulong) (c.m_value / Scale);
}
// Truncates a Currency to an integer value. The Currency
// argument is rounded towards zero to the nearest integer value,
// corresponding to removing all digits after the decimal point.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Currency Truncate(Currency c);
public static implicit operator Currency(byte value) {
return new Currency(value);
}
[CLSCompliant(false)]
public static implicit operator Currency(sbyte value) {
return new Currency(value);
}
public static implicit operator Currency(short value) {
return new Currency(value);
}
public static implicit operator Currency(char value) {
return new Currency(value);
}
public static implicit operator Currency(int value) {
return new Currency(value);
}
[CLSCompliant(false)]
public static implicit operator Currency(uint value) {
return new Currency(value);
}
public static explicit operator Currency(long value) {
return new Currency(value);
}
[CLSCompliant(false)]
public static explicit operator Currency(ulong value) {
return new Currency(value);
}
public static explicit operator Currency(float value) {
return new Currency(value);
}
public static explicit operator Currency(double value) {
return new Currency(value);
}
public static explicit operator Currency(Decimal value) {
return Decimal.ToCurrency(value);
}
public static explicit operator byte(Currency value) {
if (value < Byte.MinValue || value > Byte.MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_Byte"));
return (byte) ToInt32(value);
}
[CLSCompliant(false)]
public static explicit operator sbyte(Currency value) {
if (value < (short)SByte.MinValue || value > (short)SByte.MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_SByte"));
return (sbyte) ToInt32(value);
}
public static explicit operator short(Currency value) {
if (value < Int16.MinValue || value > Int16.MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_Int16"));
return (short) ToInt32(value);
}
[CLSCompliant(false)]
public static explicit operator ushort(Currency value) {
if ((long)value < (long)UInt16.MinValue || (long)value > (long)UInt16.MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_UInt16"));
return (ushort) ToInt32(value);
}
public static explicit operator int(Currency value) {
return ToInt32(value);
}
public static explicit operator long(Currency value) {
return ToInt64(value);
}
public static explicit operator float(Currency value) {
return ToSingle(value);
}
public static explicit operator double(Currency value) {
return ToDouble(value);
}
public static Currency operator +(Currency c) {
return c;
}
public static Currency operator -(Currency c) {
return Negate(c);
}
public static Currency operator +(Currency c1, Currency c2) {
return Add(c1, c2);
}
public static Currency operator ++(Currency c) {
return Add(c, One);
}
public static Currency operator --(Currency c) {
return Subtract(c, One);
}
public static Currency operator -(Currency c1, Currency c2) {
return Subtract(c1, c2);
}
public static Currency operator *(Currency c1, Currency c2) {
return (Currency) Multiply(c1, c2);
}
public static Currency operator /(Currency c1, Currency c2) {
return (Currency) Divide(c1, c2);
}
public static bool operator ==(Currency c1, Currency c2) {
return c1.m_value == c2.m_value;
}
public static bool operator !=(Currency c1, Currency c2) {
return c1.m_value != c2.m_value;
}
public static bool operator <(Currency c1, Currency c2) {
return c1.m_value < c2.m_value;
}
public static bool operator <=(Currency c1, Currency c2) {
return c1.m_value <= c2.m_value;
}
public static bool operator >(Currency c1, Currency c2) {
return c1.m_value > c2.m_value;
}
public static bool operator >=(Currency c1, Currency c2) {
return c1.m_value >= c2.m_value;
}
/* private static bool operator equals(Currency c1, Currency c2) {
return c1.m_value == c2.m_value;
}
private static int operator compare(Currency c1, Currency c2) {
if (c1.m_value > c2.m_value) return 1;
if (c1.m_value < c2.m_value) return -1;
return 0;
}*/
}
}
+246
View File
@@ -0,0 +1,246 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: CurrentTimeZone
**
**
**
** Purpose:
** This class represents the current system timezone. It is
** the only meaningful implementation of the TimeZone class
** available in this version.
**
** The only TimeZone that we support in version 1 is the
** CurrentTimeZone as determined by the system timezone.
**
** Date: March 20, 2001
**
============================================================*/
namespace System {
using System;
using System.Text;
using System.Threading;
using System.Collections;
using System.Globalization;
using System.Runtime.CompilerServices;
//
// Currently, this is the only supported timezone.
// The values of the timezone is from the current system timezone setting in the
// control panel.
//
[Serializable()]
internal class CurrentSystemTimeZone : TimeZone {
//
private const long TicksPerMillisecond = 10000;
private const long TicksPerSecond = TicksPerMillisecond * 1000;
private const long TicksPerMinute = TicksPerSecond * 60;
private static Hashtable m_CachedDaylightChanges = new Hashtable();
// Standard offset in ticks to the Universal time if
// no daylight saving is in used.
// E.g. the offset for PST (Pacific Standard time) should be -8 * 60 * 60 * 1000 * 10000.
// (1 millisecond = 10000 ticks)
/// <include file='doc\TimeZone.uex' path='docs/doc[@for="TimeZone.ticksOffset"]/*' />
private long m_ticksOffset;
private String m_standardName;
private String m_daylightName;
internal CurrentSystemTimeZone() {
m_ticksOffset = nativeGetTimeZoneMinuteOffset() * TicksPerMinute;
m_standardName = null;
m_daylightName = null;
}
/// <include file='doc\TimeZone.uex' path='docs/doc[@for="CurrentSystemTimeZone.StandardName"]/*' />
public override String StandardName {
get {
if (m_standardName == null) {
m_standardName = nativeGetStandardName();
}
return (m_standardName);
}
}
/// <include file='doc\TimeZone.uex' path='docs/doc[@for="CurrentSystemTimeZone.DaylightName"]/*' />
public override String DaylightName {
get {
if (m_daylightName == null) {
m_daylightName = nativeGetDaylightName();
if (m_daylightName == null) {
m_daylightName = this.StandardName;
}
}
return (m_daylightName);
}
}
internal long GetUtcOffsetFromUniversalTime(DateTime time) {
// Get the daylight changes for the year of the specified time.
DaylightTime daylightTime = GetDaylightChanges(time.Year);
// This is the UTC offset for the time (which is based on Universal time), but it is calculated according to local timezone rule.
long utcOffset = TimeZone.CalculateUtcOffset(time, daylightTime).Ticks + m_ticksOffset;
long ticks = time.Ticks;
if (daylightTime.Delta.Ticks != 0) {
// This timezone uses daylight saving rules.
if (m_ticksOffset < 0) {
// This deals with GMT-XX timezones (e.g. Pacific Standard time).
if ((ticks >= daylightTime.Start.Ticks + daylightTime.Delta.Ticks) && (ticks < daylightTime.Start.Ticks - m_ticksOffset)) {
return (utcOffset - daylightTime.Delta.Ticks);
}
if ((ticks >= daylightTime.End.Ticks) && (ticks < daylightTime.End.Ticks - m_ticksOffset)) {
return (utcOffset + daylightTime.Delta.Ticks);
}
} else {
// This deals with GMT+XX timezones.
if ((ticks >= daylightTime.Start.Ticks - m_ticksOffset) && (ticks < daylightTime.Start.Ticks + daylightTime.Delta.Ticks)) {
return (utcOffset + daylightTime.Delta.Ticks);
}
if ((ticks >= daylightTime.End.Ticks - m_ticksOffset) && (ticks < daylightTime.End.Ticks)) {
return (utcOffset - daylightTime.Delta.Ticks);
}
}
}
return (utcOffset);
}
public override DateTime ToLocalTime(DateTime time) {
return (new DateTime(time.Ticks + GetUtcOffsetFromUniversalTime(time)));
}
public override DaylightTime GetDaylightChanges(int year) {
if (year < 1 || year > 9999) {
throw new ArgumentOutOfRangeException("year", String.Format(Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, 9999));
}
Object objYear = (Object)year;
if (!m_CachedDaylightChanges.Contains(objYear)) {
BCLDebug.Log("Getting TimeZone information for: " + objYear);
lock (typeof(CurrentSystemTimeZone)) {
if (!m_CachedDaylightChanges.Contains(objYear)) {
//
// rawData is an array of 17 short (16 bit) numbers.
// The first 8 numbers contains the
// year/month/day/dayOfWeek/hour/minute/second/millisecond for the starting time of daylight saving time.
// The next 8 numbers contains the
// year/month/day/dayOfWeek/hour/minute/second/millisecond for the ending time of daylight saving time.
// The last short number is the delta to the standard offset in minutes.
//
short[] rawData = nativeGetDaylightChanges();
if (rawData == null) {
//
// If rawData is null, it means that daylight saving time is not used
// in this timezone. So keep currentDaylightChanges as the empty array.
//
m_CachedDaylightChanges.Add(objYear, new DaylightTime(DateTime.MinValue, DateTime.MinValue, TimeSpan.Zero));
} else {
DateTime start;
DateTime end;
TimeSpan delta;
//
// Store the start of daylight saving time.
//
start = GetDayOfWeek( year, rawData[1], rawData[2],
rawData[3],
rawData[4], rawData[5], rawData[6], rawData[7]);
//
// Store the end of daylight saving time.
//
end = GetDayOfWeek( year, rawData[9], rawData[10],
rawData[11],
rawData[12], rawData[13], rawData[14], rawData[15]);
delta = new TimeSpan(rawData[16] * TicksPerMinute);
DaylightTime currentDaylightChanges = new DaylightTime(start, end, delta);
m_CachedDaylightChanges.Add(objYear, currentDaylightChanges);
}
}
}
}
DaylightTime result = (DaylightTime)m_CachedDaylightChanges[objYear];
return result;
}
public override TimeSpan GetUtcOffset(DateTime time) {
return new TimeSpan(TimeZone.CalculateUtcOffset(time, GetDaylightChanges(time.Year)).Ticks + m_ticksOffset);
}
//
// Return the (numberOfSunday)th day of week in a particular year/month.
//
private static DateTime GetDayOfWeek(int year, int month, int targetDayOfWeek, int numberOfSunday, int hour, int minute, int second, int millisecond) {
DateTime time;
if (numberOfSunday <= 4) {
//
// Get the (numberOfSunday)th Sunday.
//
time = new DateTime(year, month, 1, hour, minute, second, millisecond);
int dayOfWeek = (int)time.DayOfWeek;
int delta = targetDayOfWeek - dayOfWeek;
if (delta < 0) {
delta += 7;
}
delta += 7 * (numberOfSunday - 1);
if (delta > 0) {
time = time.AddDays(delta);
}
} else {
//
// If numberOfSunday is greater than 4, we will get the last sunday.
//
Calendar cal = GregorianCalendar.GetDefaultInstance();
time = new DateTime(year, month, cal.GetDaysInMonth(year, month), hour, minute, second, millisecond);
// This is the day of week for the last day of the month.
int dayOfWeek = (int)time.DayOfWeek;
int delta = dayOfWeek - targetDayOfWeek;
if (delta < 0) {
delta += 7;
}
if (delta > 0) {
time = time.AddDays(-delta);
}
}
return (time);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int nativeGetTimeZoneMinuteOffset();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static String nativeGetDaylightName();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static String nativeGetStandardName();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static short[] nativeGetDaylightChanges();
} // class CurrentSystemTimeZone
}
File diff suppressed because it is too large Load Diff
+46
View File
@@ -0,0 +1,46 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: DayOfWeek
**
**
**
** Purpose: Enum for the day of the week.
**
** Date: November 28, 2000
**
============================================================*/
namespace System {
/// <include file='doc\DayOfWeek.uex' path='docs/doc[@for="DayOfWeek"]/*' />
[Serializable]
public enum DayOfWeek {
/// <include file='doc\DayOfWeek.uex' path='docs/doc[@for="DayOfWeek.Sunday "]/*' />
Sunday = 0,
/// <include file='doc\DayOfWeek.uex' path='docs/doc[@for="DayOfWeek.Monday "]/*' />
Monday = 1,
/// <include file='doc\DayOfWeek.uex' path='docs/doc[@for="DayOfWeek.Tuesday "]/*' />
Tuesday = 2,
/// <include file='doc\DayOfWeek.uex' path='docs/doc[@for="DayOfWeek.Wednesday "]/*' />
Wednesday = 3,
/// <include file='doc\DayOfWeek.uex' path='docs/doc[@for="DayOfWeek.Thursday "]/*' />
Thursday = 4,
/// <include file='doc\DayOfWeek.uex' path='docs/doc[@for="DayOfWeek.Friday "]/*' />
Friday = 5,
/// <include file='doc\DayOfWeek.uex' path='docs/doc[@for="DayOfWeek.Saturday "]/*' />
Saturday = 6,
}
}
+153
View File
@@ -0,0 +1,153 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
////////////////////////////////////////////////////////////////////////////////
// Void
// This class represents a Missing Variant
////////////////////////////////////////////////////////////////////////////////
namespace System {
using System;
using System.Runtime.Remoting;
using System.Runtime.Serialization;
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull"]/*' />
[Serializable()] public sealed class DBNull : ISerializable, IConvertible {
//Package private constructor
private DBNull(){
}
private DBNull(SerializationInfo info, StreamingContext context) {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DBNullSerial"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.Value"]/*' />
public static readonly DBNull Value = new DBNull();
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.GetObjectData"]/*' />
public void GetObjectData(SerializationInfo info, StreamingContext context) {
UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.NullUnity, null, null);
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.ToString"]/*' />
public override String ToString() {
return String.Empty;
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.ToString1"]/*' />
public String ToString(IFormatProvider provider) {
return String.Empty;
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.GetTypeCode"]/*' />
public TypeCode GetTypeCode() {
return TypeCode.DBNull;
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToBoolean"]/*' />
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToChar"]/*' />
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToSByte"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
sbyte IConvertible.ToSByte(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToByte"]/*' />
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToInt16"]/*' />
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToUInt16"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
ushort IConvertible.ToUInt16(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToInt32"]/*' />
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToUInt32"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
uint IConvertible.ToUInt32(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToInt64"]/*' />
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToUInt64"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
ulong IConvertible.ToUInt64(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToSingle"]/*' />
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToDouble"]/*' />
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToDecimal"]/*' />
/// <internalonly/>
decimal IConvertible.ToDecimal(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToDateTime"]/*' />
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToType"]/*' />
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider) {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
+981
View File
@@ -0,0 +1,981 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace System {
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// Implements the Decimal data type. The Decimal data type can
// represent values ranging from -79,228,162,514,264,337,593,543,950,335 to
// 79,228,162,514,264,337,593,543,950,335 with 28 significant digits. The
// Decimal data type is ideally suited to financial calculations that
// require a large number of significant digits and no round-off errors.
//
// The finite set of values of type Decimal are of the form m
// / 10e, where m is an integer such that
// -296 <; m <; 296, and e is an integer
// between 0 and 28 inclusive.
//
// Contrary to the float and double data types, decimal
// fractional numbers such as 0.1 can be represented exactly in the
// Decimal representation. In the float and double
// representations, such numbers are often infinite fractions, making those
// representations more prone to round-off errors.
//
// The Decimal class implements widening conversions from the
// ubyte, char, short, int, and long types
// to Decimal. These widening conversions never loose any information
// and never throw exceptions. The Decimal class also implements
// narrowing conversions from Decimal to ubyte, char,
// short, int, and long. These narrowing conversions round
// the Decimal value towards zero to the nearest integer, and then
// converts that integer to the destination type. An OverflowException
// is thrown if the result is not within the range of the destination type.
//
// The Decimal class provides a widening conversion from
// Currency to Decimal. This widening conversion never loses any
// information and never throws exceptions. The Currency class provides
// a narrowing conversion from Decimal to Currency. This
// narrowing conversion rounds the Decimal to four decimals and then
// converts that number to a Currency. An OverflowException
// is thrown if the result is not within the range of the Currency type.
//
// The Decimal class provides narrowing conversions to and from the
// float and double types. A conversion from Decimal to
// float or double may loose precision, but will not loose
// information about the overall magnitude of the numeric value, and will never
// throw an exception. A conversion from float or double to
// Decimal throws an OverflowException if the value is not within
// the range of the Decimal type.
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal"]/*' />
[StructLayout(LayoutKind.Sequential)]
[Serializable()]
public struct Decimal : IFormattable, IComparable, IConvertible
{
// Sign mask for the flags field. A value of zero in this bit indicates a
// positive Decimal value, and a value of one in this bit indicates a
// negative Decimal value.
//
// Look at OleAut's DECIMAL_NEG constant to check for negative values
// in native code.
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.SignMask"]/*' />
private const int SignMask = unchecked((int)0x80000000);
// Scale mask for the flags field. This byte in the flags field contains
// the power of 10 to divide the Decimal value by. The scale byte must
// contain a value between 0 and 28 inclusive.
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.ScaleMask"]/*' />
private const int ScaleMask = 0x00FF0000;
// Number of bits scale is shifted by.
private const int ScaleShift = 16;
// Constant representing the Decimal value 0.
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Zero"]/*' />
public const Decimal Zero = 0m;
// Constant representing the Decimal value 1.
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.One"]/*' />
public const Decimal One = 1m;
// Constant representing the Decimal value -1.
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.MinusOne"]/*' />
public const Decimal MinusOne = -1m;
// Constant representing the largest possible Decimal value. The value of
// this constant is 79,228,162,514,264,337,593,543,950,335.
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.MaxValue"]/*' />
public const Decimal MaxValue = 79228162514264337593543950335m;
// Constant representing the smallest possible Decimal value. The value of
// this constant is -79,228,162,514,264,337,593,543,950,335.
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.MinValue"]/*' />
public const Decimal MinValue = -79228162514264337593543950335m;
// The lo, mid, hi, and flags fields contain the representation of the
// Decimal value. The lo, mid, and hi fields contain the 96-bit integer
// part of the Decimal. Bits 0-15 (the lower word) of the flags field are
// unused and must be zero; bits 16-23 contain must contain a value between
// 0 and 28, indicating the power of 10 to divide the 96-bit integer part
// by to produce the Decimal value; bits 24-30 are unused and must be zero;
// and finally bit 31 indicates the sign of the Decimal value, 0 meaning
// positive and 1 meaning negative.
//
// NOTE: Do not change the order in which these fields are declared. The
// native methods in this class rely on this particular order.
private int flags;
private int hi;
private int lo;
private int mid;
// Constructs a zero Decimal.
//public Decimal() {
// lo = 0;
// mid = 0;
// hi = 0;
// flags = 0;
//}
// Constructs a Decimal from an integer value.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Decimal"]/*' />
public Decimal(int value) {
if (value >= 0) {
flags = 0;
}
else {
flags = SignMask;
value = -value;
}
lo = value;
mid = 0;
hi = 0;
}
// Constructs a Decimal from an unsigned integer value.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Decimal1"]/*' />
[CLSCompliant(false)]
public Decimal(uint value) {
flags = 0;
lo = (int) value;
mid = 0;
hi = 0;
}
// Constructs a Decimal from a long value.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Decimal2"]/*' />
public Decimal(long value) {
if (value >= 0) {
flags = 0;
}
else {
flags = SignMask;
value = -value;
}
lo = (int)value;
mid = (int)(value >> 32);
hi = 0;
}
// Constructs a Decimal from an unsigned long value.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Decimal3"]/*' />
[CLSCompliant(false)]
public Decimal(ulong value) {
flags = 0;
lo = (int)value;
mid = (int)(value >> 32);
hi = 0;
}
// Constructs a Decimal from a float value.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Decimal4"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Decimal(float value);
// Constructs a Decimal from a double value.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Decimal5"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Decimal(double value);
// Constructs a Decimal from a Currency value.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Decimal6"]/*' />
internal Decimal(Currency value) {
Decimal temp = Currency.ToDecimal(value);
this.lo = temp.lo;
this.mid = temp.mid;
this.hi = temp.hi;
this.flags = temp.flags;
}
// Don't remove these 2 methods below. They are required by the fx when the are dealing with Currency in their
// databases
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.ToOACurrency"]/*' />
public static long ToOACurrency(Decimal value)
{
return new Currency(value).ToOACurrency();
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.FromOACurrency"]/*' />
public static Decimal FromOACurrency(long cy)
{
return Currency.ToDecimal(Currency.FromOACurrency(cy));
}
// Constructs a Decimal from an integer array containing a binary
// representation. The bits argument must be a non-null integer
// array with four elements. bits[0], bits[1], and
// bits[2] contain the low, middle, and high 32 bits of the 96-bit
// integer part of the Decimal. bits[3] contains the scale factor
// and sign of the Decimal: bits 0-15 (the lower word) are unused and must
// be zero; bits 16-23 must contain a value between 0 and 28, indicating
// the power of 10 to divide the 96-bit integer part by to produce the
// Decimal value; bits 24-30 are unused and must be zero; and finally bit
// 31 indicates the sign of the Decimal value, 0 meaning positive and 1
// meaning negative.
//
// Note that there are several possible binary representations for the
// same numeric value. For example, the value 1 can be represented as {1,
// 0, 0, 0} (integer value 1 with a scale factor of 0) and equally well as
// {1000, 0, 0, 0x30000} (integer value 1000 with a scale factor of 3).
// The possible binary representations of a particular value are all
// equally valid, and all are numerically equivalent.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Decimal7"]/*' />
public Decimal(int[] bits) {
if (bits==null)
throw new ArgumentNullException("bits");
if (bits.Length == 4) {
int f = bits[3];
if ((f & ~(SignMask | ScaleMask)) == 0 && (f & ScaleMask) <= (28 << 16)) {
lo = bits[0];
mid = bits[1];
hi = bits[2];
flags = f;
return;
}
}
throw new ArgumentException(Environment.GetResourceString("Arg_DecBitCtor"));
}
// Constructs a Decimal from its constituent parts.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Decimal8"]/*' />
public Decimal(int lo, int mid, int hi, bool isNegative, byte scale) {
if (scale > 28)
throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_DecimalScale"));
this.lo = lo;
this.mid = mid;
this.hi = hi;
this.flags = ((int)scale) << 16;
if (isNegative)
this.flags |= SignMask;
}
// Constructs a Decimal from its constituent parts.
private Decimal(int lo, int mid, int hi, int flags) {
this.lo = lo;
this.mid = mid;
this.hi = hi;
this.flags = flags;
}
// Returns the absolute value of the given Decimal. If d is
// positive, the result is d. If d is negative, the result
// is -d.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Abs"]/*' />
internal static Decimal Abs(Decimal d) {
return new Decimal(d.lo, d.mid, d.hi, d.flags & ~SignMask);
}
// Adds two Decimal values.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Add"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Decimal Add(Decimal d1, Decimal d2);
// Compares two Decimal values, returning an integer that indicates their
// relationship.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Compare"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int Compare(Decimal d1, Decimal d2);
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Decimal, this method throws an ArgumentException.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.CompareTo"]/*' />
public int CompareTo(Object value)
{
if (value == null)
return 1;
if (!(value is Decimal))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDecimal"));
return Decimal.Compare(this, (Decimal)value);
}
// Divides two Decimal values.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Divide"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Decimal Divide(Decimal d1, Decimal d2);
// Checks if this Decimal is equal to a given object. Returns true
// if the given object is a boxed Decimal and its value is equal to the
// value of this Decimal. Returns false otherwise.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Equals"]/*' />
public override bool Equals(Object value) {
if (value is Decimal) {
return Compare(this, (Decimal)value) == 0;
}
return false;
}
// Returns the hash code for this Decimal.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.GetHashCode"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern override int GetHashCode();
// Compares two Decimal values for equality. Returns true if the two
// Decimal values are equal, or false if they are not equal.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Equals1"]/*' />
public static bool Equals(Decimal d1, Decimal d2) {
return Compare(d1, d2) == 0;
}
// Rounds a Decimal to an integer value. The Decimal argument is rounded
// towards negative infinity.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Floor"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Decimal Floor(Decimal d);
// Converts this Decimal to a string. The resulting string consists of an
// optional minus sign ("-") followed to a sequence of digits ("0" - "9"),
// optionally followed by a decimal point (".") and another sequence of
// digits.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.ToString"]/*' />
public override String ToString() {
return ToString(null, null);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.ToString1"]/*' />
public String ToString(String format) {
return ToString(format, null);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.ToString2"]/*' />
public String ToString(String format, IFormatProvider provider) {
return Number.FormatDecimal(this, format, NumberFormatInfo.GetInstance(provider));
}
// Converts a string to a Decimal. The string must consist of an optional
// minus sign ("-") followed by a sequence of digits ("0" - "9"). The
// sequence of digits may optionally contain a single decimal point (".")
// character. Leading and trailing whitespace characters are allowed.
// Parse also allows a currency symbol, a trailing negative sign, and
// parentheses in the number.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Parse"]/*' />
public static Decimal Parse(String s) {
return Parse(s, NumberStyles.Number, null);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Parse1"]/*' />
public static Decimal Parse(String s, NumberStyles style) {
return Parse(s, style, null);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Parse2"]/*' />
public static Decimal Parse(String s, IFormatProvider provider) {
NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
return Number.ParseDecimal(s, NumberStyles.Number, info);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Parse3"]/*' />
public static Decimal Parse(String s, NumberStyles style, IFormatProvider provider) {
NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
return Number.ParseDecimal(s, style, info);
}
// Returns a binary representation of a Decimal. The return value is an
// integer array with four elements. Elements 0, 1, and 2 contain the low,
// middle, and high 32 bits of the 96-bit integer part of the Decimal.
// Element 3 contains the scale factor and sign of the Decimal: bits 0-15
// (the lower word) are unused; bits 16-23 contain a value between 0 and
// 28, indicating the power of 10 to divide the 96-bit integer part by to
// produce the Decimal value; bits 24-30 are unused; and finally bit 31
// indicates the sign of the Decimal value, 0 meaning positive and 1
// meaning negative.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.GetBits"]/*' />
public static int[] GetBits(Decimal d) {
return new int[] {d.lo, d.mid, d.hi, d.flags};
}
internal static void GetBytes(Decimal d, byte [] buffer) {
BCLDebug.Assert((buffer != null && buffer.Length >= 16), "[GetBytes]buffer != null && buffer.Length >= 16");
buffer[0] = (byte) d.lo;
buffer[1] = (byte) (d.lo >> 8);
buffer[2] = (byte) (d.lo >> 16);
buffer[3] = (byte) (d.lo >> 24);
buffer[4] = (byte) d.mid;
buffer[5] = (byte) (d.mid >> 8);
buffer[6] = (byte) (d.mid >> 16);
buffer[7] = (byte) (d.mid >> 24);
buffer[8] = (byte) d.hi;
buffer[9] = (byte) (d.hi >> 8);
buffer[10] = (byte) (d.hi >> 16);
buffer[11] = (byte) (d.hi >> 24);
buffer[12] = (byte) d.flags;
buffer[13] = (byte) (d.flags >> 8);
buffer[14] = (byte) (d.flags >> 16);
buffer[15] = (byte) (d.flags >> 24);
}
internal static decimal ToDecimal(byte [] buffer) {
int lo = ((int)buffer[0]) | ((int)buffer[1] << 8) | ((int)buffer[2] << 16) | ((int)buffer[3] << 24);
int mid = ((int)buffer[4]) | ((int)buffer[5] << 8) | ((int)buffer[6] << 16) | ((int)buffer[7] << 24);
int hi = ((int)buffer[8]) | ((int)buffer[9] << 8) | ((int)buffer[10] << 16) | ((int)buffer[11] << 24);
int flags = ((int)buffer[12]) | ((int)buffer[13] << 8) | ((int)buffer[14] << 16) | ((int)buffer[15] << 24);
return new Decimal(lo,mid,hi,flags);
}
// Returns the larger of two Decimal values.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Max"]/*' />
internal static Decimal Max(Decimal d1, Decimal d2) {
return Compare(d1, d2) >= 0? d1: d2;
}
// Returns the smaller of two Decimal values.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Min"]/*' />
internal static Decimal Min(Decimal d1, Decimal d2) {
return Compare(d1, d2) < 0? d1: d2;
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Remainder"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Decimal Remainder(Decimal d1, Decimal d2);
// Multiplies two Decimal values.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Multiply"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Decimal Multiply(Decimal d1, Decimal d2);
// Returns the negated value of the given Decimal. If d is non-zero,
// the result is -d. If d is zero, the result is zero.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Negate"]/*' />
public static Decimal Negate(Decimal d) {
return new Decimal(d.lo, d.mid, d.hi, d.flags ^ SignMask);
}
// Rounds a Decimal value to a given number of decimal places. The value
// given by d is rounded to the number of decimal places given by
// decimals. The decimals argument must be an integer between
// 0 and 28 inclusive.
//
// The operation Decimal.Round(d, dec) conceptually
// corresponds to evaluating Decimal.Truncate(d *
// 10dec + delta) / 10dec, where
// delta is 0.5 for positive values of d and -0.5 for
// negative values of d.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Round"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Decimal Round(Decimal d, int decimals);
// Subtracts two Decimal values.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Subtract"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Decimal Subtract(Decimal d1, Decimal d2);
// Converts a Decimal to an unsigned byte. The Decimal value is rounded
// towards zero to the nearest integer value, and the result of this
// operation is returned as a byte.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.ToByte"]/*' />
public static byte ToByte(Decimal value) {
uint temp = ToUInt32(value);
if (temp < Byte.MinValue || temp > Byte.MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_Byte"));
return (byte)temp;
}
// Converts a Decimal to a signed byte. The Decimal value is rounded
// towards zero to the nearest integer value, and the result of this
// operation is returned as a byte.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.ToSByte"]/*' />
[CLSCompliant(false)]
public static sbyte ToSByte(Decimal value) {
int temp = ToInt32(value);
if (temp < SByte.MinValue || temp > SByte.MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_SByte"));
return (sbyte)temp;
}
// Converts a Decimal to a short. The Decimal value is
// rounded towards zero to the nearest integer value, and the result of
// this operation is returned as a short.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.ToInt16"]/*' />
public static short ToInt16(Decimal value) {
int temp = ToInt32(value);
if (temp < Int16.MinValue || temp > Int16.MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_Int16"));
return (short)temp;
}
// Converts a Decimal to a Currency. Since a Currency
// has fewer significant digits than a Decimal, this operation may
// produce round-off errors.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.ToCurrency"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Currency ToCurrency(Decimal d);
// Converts a Decimal to a double. Since a double has fewer significant
// digits than a Decimal, this operation may produce round-off errors.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.ToDouble"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double ToDouble(Decimal d);
// Converts a Decimal to an integer. The Decimal value is rounded towards
// zero to the nearest integer value, and the result of this operation is
// returned as an integer.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.ToInt32"]/*' />
public static int ToInt32(Decimal d) {
if ((d.flags & ScaleMask) != 0) d = Truncate(d);
if (d.hi == 0 && d.mid == 0) {
int i = d.lo;
if ((d.flags & SignMask) == 0) {
if (i >= 0) return i;
}
else {
i = -i;
if (i <= 0) return i;
}
}
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
// Converts a Decimal to a long. The Decimal value is rounded towards zero
// to the nearest integer value, and the result of this operation is
// returned as a long.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.ToInt64"]/*' />
public static long ToInt64(Decimal d) {
if ((d.flags & ScaleMask) != 0) d = Truncate(d);
if (d.hi == 0) {
long l = d.lo & 0xFFFFFFFFL | (long)d.mid << 32;
if ((d.flags & SignMask) == 0) {
if (l >= 0) return l;
}
else {
l = -l;
if (l <= 0) return l;
}
}
throw new OverflowException(Environment.GetResourceString("Overflow_Int64"));
}
// Converts a Decimal to an ushort. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as an ushort.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.ToUInt16"]/*' />
[CLSCompliant(false)]
public static ushort ToUInt16(Decimal value) {
uint temp = ToUInt32(value);
if (temp < UInt16.MinValue || temp > UInt16.MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_UInt16"));
return (ushort)temp;
}
// Converts a Decimal to an unsigned integer. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as an unsigned integer.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.ToUInt32"]/*' />
[CLSCompliant(false)]
public static uint ToUInt32(Decimal d) {
if ((d.flags & ScaleMask) != 0) d = Truncate(d);
if (d.hi == 0 && d.mid == 0) {
uint i = (uint) d.lo;
if ((d.flags & SignMask) == 0 || i == 0)
return i;
}
throw new OverflowException(Environment.GetResourceString("Overflow_UInt32"));
}
// Converts a Decimal to an unsigned long. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as a long.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.ToUInt64"]/*' />
[CLSCompliant(false)]
public static ulong ToUInt64(Decimal d) {
if ((d.flags & ScaleMask) != 0) d = Truncate(d);
if (d.hi == 0) {
ulong l = ((ulong)(uint)d.lo) | ((ulong)(uint)d.mid << 32);
if ((d.flags & SignMask) == 0 || l == 0)
return l;
}
throw new OverflowException(Environment.GetResourceString("Overflow_UInt64"));
}
// Converts a Decimal to a float. Since a float has fewer significant
// digits than a Decimal, this operation may produce round-off errors.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.ToSingle"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float ToSingle(Decimal d);
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.ToString3"]/*' />
public String ToString(IFormatProvider provider) {
return ToString(null, provider);
}
// Truncates a Decimal to an integer value. The Decimal argument is rounded
// towards zero to the nearest integer value, corresponding to removing all
// digits after the decimal point.
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.Truncate"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Decimal Truncate(Decimal d);
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorDecimal"]/*' />
public static implicit operator Decimal(byte value) {
return new Decimal(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorDecimal1"]/*' />
[CLSCompliant(false)]
public static implicit operator Decimal(sbyte value) {
return new Decimal(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorDecimal2"]/*' />
public static implicit operator Decimal(short value) {
return new Decimal(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorDecimal3"]/*' />
[CLSCompliant(false)]
public static implicit operator Decimal(ushort value) {
return new Decimal(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorDecimal4"]/*' />
public static implicit operator Decimal(char value) {
return new Decimal(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorDecimal5"]/*' />
public static implicit operator Decimal(int value) {
return new Decimal(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorDecimal6"]/*' />
[CLSCompliant(false)]
public static implicit operator Decimal(uint value) {
return new Decimal(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorDecimal7"]/*' />
public static implicit operator Decimal(long value) {
return new Decimal(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorDecimal8"]/*' />
[CLSCompliant(false)]
public static implicit operator Decimal(ulong value) {
return new Decimal(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorDecimal9"]/*' />
public static explicit operator Decimal(float value) {
return new Decimal(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorDecimal10"]/*' />
public static explicit operator Decimal(double value) {
return new Decimal(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorbyte"]/*' />
public static explicit operator byte(Decimal value) {
return ToByte(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorsbyte"]/*' />
[CLSCompliant(false)]
public static explicit operator sbyte(Decimal value) {
return ToSByte(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorchar"]/*' />
public static explicit operator char(Decimal value) {
return (char)ToUInt16(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorshort"]/*' />
public static explicit operator short(Decimal value) {
return ToInt16(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorushort"]/*' />
[CLSCompliant(false)]
public static explicit operator ushort(Decimal value) {
return ToUInt16(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorint"]/*' />
public static explicit operator int(Decimal value) {
return ToInt32(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatoruint"]/*' />
[CLSCompliant(false)]
public static explicit operator uint(Decimal value) {
return ToUInt32(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorlong"]/*' />
public static explicit operator long(Decimal value) {
return ToInt64(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorulong"]/*' />
[CLSCompliant(false)]
public static explicit operator ulong(Decimal value) {
return ToUInt64(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorfloat"]/*' />
public static explicit operator float(Decimal value) {
return ToSingle(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatordouble"]/*' />
public static explicit operator double(Decimal value) {
return ToDouble(value);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorADD1"]/*' />
public static Decimal operator +(Decimal d) {
return d;
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorSUB1"]/*' />
public static Decimal operator -(Decimal d) {
return Negate(d);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorINC"]/*' />
public static Decimal operator ++(Decimal d) {
return Add(d, One);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorDEC"]/*' />
public static Decimal operator --(Decimal d) {
return Subtract(d, One);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorADD2"]/*' />
public static Decimal operator +(Decimal d1, Decimal d2) {
return Add(d1, d2);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorSUB2"]/*' />
public static Decimal operator -(Decimal d1, Decimal d2) {
return Subtract(d1, d2);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorMUL"]/*' />
public static Decimal operator *(Decimal d1, Decimal d2) {
return Multiply(d1, d2);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorDIV"]/*' />
public static Decimal operator /(Decimal d1, Decimal d2) {
return Divide(d1, d2);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorMOD"]/*' />
public static Decimal operator %(Decimal d1, Decimal d2) {
return Remainder(d1, d2);
}
/*private static bool operator equals(Decimal d1, Decimal d2) {
return Compare(d1, d2) == 0;
}
private static int operator compare(Decimal d1, Decimal d2) {
int c = Compare(d1, d2);
if (c < 0) return -1;
if (c > 0) return 1;
return 0;
}*/
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorEQ"]/*' />
public static bool operator ==(Decimal d1, Decimal d2) {
return Compare(d1, d2) == 0;
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorNE"]/*' />
public static bool operator !=(Decimal d1, Decimal d2) {
return Compare(d1, d2) != 0;
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorLT"]/*' />
public static bool operator <(Decimal d1, Decimal d2) {
return Compare(d1, d2) < 0;
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorLE"]/*' />
public static bool operator <=(Decimal d1, Decimal d2) {
return Compare(d1, d2) <= 0;
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorGT"]/*' />
public static bool operator >(Decimal d1, Decimal d2) {
return Compare(d1, d2) > 0;
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.operatorGE"]/*' />
public static bool operator >=(Decimal d1, Decimal d2) {
return Compare(d1, d2) >= 0;
}
//
// IValue implementation
//
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.GetTypeCode"]/*' />
public TypeCode GetTypeCode() {
return TypeCode.Decimal;
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.IConvertible.ToBoolean"]/*' />
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider) {
return Convert.ToBoolean(this);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.IConvertible.ToChar"]/*' />
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider) {
throw new InvalidCastException(String.Format(Environment.GetResourceString("InvalidCast_FromTo"), "Decimal", "Char"));
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.IConvertible.ToSByte"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
sbyte IConvertible.ToSByte(IFormatProvider provider) {
return Convert.ToSByte(this);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.IConvertible.ToByte"]/*' />
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider) {
return Convert.ToByte(this);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.IConvertible.ToInt16"]/*' />
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider) {
return Convert.ToInt16(this);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.IConvertible.ToUInt16"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
ushort IConvertible.ToUInt16(IFormatProvider provider) {
return Convert.ToUInt16(this);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.IConvertible.ToInt32"]/*' />
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider) {
return Convert.ToInt32(this);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.IConvertible.ToUInt32"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
uint IConvertible.ToUInt32(IFormatProvider provider) {
return Convert.ToUInt32(this);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.IConvertible.ToInt64"]/*' />
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider) {
return Convert.ToInt64(this);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.IConvertible.ToUInt64"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
ulong IConvertible.ToUInt64(IFormatProvider provider) {
return Convert.ToUInt64(this);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.IConvertible.ToSingle"]/*' />
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider) {
return Convert.ToSingle(this);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.IConvertible.ToDouble"]/*' />
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider) {
return Convert.ToDouble(this);
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.IConvertible.ToDecimal"]/*' />
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider) {
return this;
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.IConvertible.ToDateTime"]/*' />
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider) {
throw new InvalidCastException(String.Format(Environment.GetResourceString("InvalidCast_FromTo"), "Decimal", "DateTime"));
}
/// <include file='doc\Decimal.uex' path='docs/doc[@for="Decimal.IConvertible.ToType"]/*' />
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider) {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
File diff suppressed because it is too large Load Diff
+399
View File
@@ -0,0 +1,399 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace System {
using System;
using System.Reflection;
using System.Threading;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate"]/*' />
[Serializable()]
public abstract class Delegate : ICloneable, ISerializable
{
// _method is the MethodInfo representing the target, this is set by
// InternalCreate.
private IntPtr _methodPtr;
// _target is the object we will invoke on
private Object _target;
private RuntimeMethodInfo _method = null;
// In the case of a static method passed to a delegate, this field stores
// whatever _methodPtr would have stored: and _methodPtr points to a
// small thunk which removes the "this" pointer before going on
// to _methodPtrAux.
private IntPtr _methodPtrAux = IntPtr.Zero;
// This constructor is called from the class generated by the
// compiler generated code
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.Delegate"]/*' />
protected Delegate(Object target,String method)
{
if (target == null)
throw new ArgumentNullException("target");
if (method == null)
throw new ArgumentNullException("method");
InternalCreate(target,method,false);
}
// This constructor is called from a class to generate a
// delegate based upon a static method name and the Type object
// for the class defining the method.
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.Delegate1"]/*' />
protected Delegate(Type target,String method)
{
if (target == null)
throw new ArgumentNullException("target");
if (!(target is RuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "target");
if (method == null)
throw new ArgumentNullException("method");
InternalCreateStatic((RuntimeType)target,method);
}
// Protect the default constructor so you can't build a delegate
private Delegate() {}
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.DynamicInvoke"]/*' />
public Object DynamicInvoke(Object[] args)
{
return DynamicInvokeImpl(args);
}
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.DynamicInvokeImpl"]/*' />
protected virtual Object DynamicInvokeImpl(Object[] args)
{
if (_method == null)
_method = InternalFindMethodInfo();
// Use internal version of invoke to avoid access check (performed
// during delegate creation).
return _method.InternalInvoke(_target,BindingFlags.Default,null,args,null,false);
}
// equals returns true IIF the delegate is not null and has the
// same target, method and invocation list as this object
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.Equals"]/*' />
public override bool Equals(Object obj)
{
if (obj != null && obj is Delegate) {
Delegate d = (Delegate) obj;
if (IsStatic()) {
if (_methodPtrAux==d._methodPtrAux) {
return true;
}
} else {
if (d._target == _target && Method.Equals(d.Method)) {
return true;
}
}
}
return false;
}
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.GetHashCode"]/*' />
public override int GetHashCode()
{
if (IsStatic())
return unchecked((int)((long)this._methodPtrAux));
else
return unchecked((int)((long)this._methodPtr));
}
// Combine creates a new delegate based upon the contents of the
// delegates passed in.
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.Combine"]/*' />
public static Delegate Combine(Delegate a, Delegate b)
{
// boundry conditions -- if either (or both) delegates is null
// return the other.
if (a == null)
return b;
if (b == null)
return a;
// Verify that the types are the same...
if (a.GetType() != b.GetType())
throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTypeMis"));
return a.CombineImpl(b);
}
// This method creates a new delegate based upon the passed
// array of delegates.
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.Combine1"]/*' />
public static Delegate Combine(Delegate[] delegates)
{
if (delegates == null || delegates.Length == 0)
return null;
Delegate d = delegates[0];
for (int i = 1; i < delegates.Length; i++)
d = Combine(d,delegates[i]);
return d;
}
// Return an array of delegates that represent the invocation list.
// This is basically THIS for a Delegate. MulticastDelegates may
// have multiple members.
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.GetInvocationList"]/*' />
public virtual Delegate[] GetInvocationList() {
Delegate[] d = new Delegate[1];
d[0] = this;
return d;
}
// This routine will return the method
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.Method"]/*' />
public MethodInfo Method
{
get {
if (_method == null)
_method = InternalFindMethodInfo();
return _method;
}
}
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.GetMethodImpl"]/*' />
protected virtual MethodInfo GetMethodImpl()
{
return Method;
}
// This routine will return the target
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.Target"]/*' />
public Object Target
{
get {return IsStatic() ? null : _target;}
}
//A quick test to see if this is a delegate to a static method.
private bool IsStatic() {
if (_target is Delegate) {
return true;
}
return false;
}
// This will remove the value delegate from the source delegate
// if it found.
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.Remove"]/*' />
public static Delegate Remove(Delegate source, Delegate value)
{
if (source == null)
return null;
if (value == null)
return source;
return source.RemoveImpl(value);
}
// This is an internal routine that is called to do the combine. We
// use this to do the combine because the Combine routines are static
// final methods. In Delegate, this simply throws a MulticastNotSupportedException
// error. Multicast delegate must implement this.
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.CombineImpl"]/*' />
protected virtual Delegate CombineImpl(Delegate d)
{
throw new MulticastNotSupportedException(Environment.GetResourceString("Multicast_Combine"));
}
// This is an internal routine that is called to do the remove. We use this
// to do the remove because Remove is a static final method. Here we simply
// make sure that d is equal to this and return null or this.
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.RemoveImpl"]/*' />
protected virtual Delegate RemoveImpl(Delegate d)
{
if (_target == d._target && Method.Equals(d.Method))
//if (_target == d._target && _methodPtr == d._methodPtr)
return null;
else
return this;
}
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.Clone"]/*' />
public virtual Object Clone()
{
return MemberwiseClone();
}
// Create a new delegate given a delegate class, an object and the
// name of a method.
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.CreateDelegate"]/*' />
public static Delegate CreateDelegate(Type type,Object target,String method) {
if (type == null)
throw new ArgumentNullException("type");
if (!(type is RuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type");
if (target == null)
throw new ArgumentNullException("target");
if (method == null)
throw new ArgumentNullException("method");
Type c = type.BaseType;
if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type");
Delegate d = InternalAlloc((RuntimeType)type);
d.InternalCreate(target,method,false);
return d;
}
// Create a new delegate given a delegate class, an object and the
// name of a method.
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.CreateDelegate3"]/*' />
public static Delegate CreateDelegate(Type type,Object target,String method,bool ignoreCase) {
if (type == null)
throw new ArgumentNullException("type");
if (!(type is RuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type");
if (target == null)
throw new ArgumentNullException("target");
if (method == null)
throw new ArgumentNullException("method");
Type c = type.BaseType;
if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type");
Delegate d = InternalAlloc((RuntimeType)type);
d.InternalCreate(target,method,ignoreCase);
return d;
}
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.CreateDelegate1"]/*' />
public static Delegate CreateDelegate(Type type, Type target, String method) {
if (type == null)
throw new ArgumentNullException("type");
if (!(type is RuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type");
if (target == null)
throw new ArgumentNullException("target");
if (!(target is RuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "target");
if (method == null)
throw new ArgumentNullException("method");
Type c = type.BaseType;
if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type");
Delegate d = InternalAlloc((RuntimeType)type);
d.InternalCreateStatic((RuntimeType)target,method);
return d;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void NeverCallThis(Object target, IntPtr slot);
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.CreateDelegate2"]/*' />
public static Delegate CreateDelegate(Type type,MethodInfo method) {
// Validate the parameters.
if (type == null)
throw new ArgumentNullException("type");
if (!(type is RuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "type");
if (method == null)
throw new ArgumentNullException("method");
if (!(method is RuntimeMethodInfo))
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "method");
Type c = type.BaseType;
if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type");
if (!method.IsStatic)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeStatic"),"method");
// Find the Invoke method
MethodInfo m = type.GetMethod("Invoke");
if (m == null)
throw new InvalidProgramException("Didn't find Delegate Invoke method.");
if (!(m is RuntimeMethodInfo))
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "type.Invoke");
// Initialize the method...
Delegate d = InternalAlloc((RuntimeType)type);
d.InternalCreateMethod((RuntimeMethodInfo)m,(RuntimeMethodInfo)method);
return d;
}
// Big cheat to get the internal delegate.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static Delegate InternalAlloc(RuntimeType type);
// This method is the internal native method that initializes the
// the delegate. It will initialize all of the internal fields
// above.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void InternalCreate(Object target, String method, bool ignoreCase);
// Internal create for a static method
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void InternalCreateStatic(RuntimeType target, String method);
// Internal create for a static method
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void InternalCreateMethod(RuntimeMethodInfo invokeMeth,RuntimeMethodInfo targetMethod);
// Internal method to get the reflection method info
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern RuntimeMethodInfo InternalFindMethodInfo();
// InternalCreateMethod will create a delegate based upon the MethodInfo..
// The method must be static
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.operatorEQ"]/*' />
public static bool operator ==(Delegate d1, Delegate d2) {
if ((Object)d1 == null)
return (Object)d2 == null;
return d1.Equals(d2);
}
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.operatorNE"]/*' />
public static bool operator != (Delegate d1, Delegate d2) {
if ((Object)d1 == null)
return (Object)d2 != null;
return !d1.Equals(d2);
}
//
// Implementation of ISerializable
//
/// <include file='doc\Delegate.uex' path='docs/doc[@for="Delegate.GetObjectData"]/*' />
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
if (!IsStatic()) {
DelegateSerializationHolder.GetDelegateSerializationInfo(info, this.GetType(), _target, Method, 0);
} else {
DelegateSerializationHolder.GetDelegateSerializationInfo(info, this.GetType(), null, Method, 0);
}
}
//
// This is just designed to prevent compiler warnings.
// This field is used from native, but we need to prevent the compiler warnings.
//
#if _DEBUG
private void DontTouchThis() {
_methodPtr = IntPtr.Zero;
_target = null;
}
#endif
}
}
@@ -0,0 +1,264 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: DelegateSerializationHolder
**
**
**
** Purpose: Holds a delegate for purposes of serialization since
** they need to be internally allocated and can't be allocated with
** FormatterServices.GetUninitializedObject;
**
** Date: October 3, 1999
**
============================================================*/
namespace System {
using System;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Serialization;
[Serializable()]
internal class DelegateSerializationHolder : IObjectReference, ISerializable {
internal DelegateEntry m_delegateEntry;
// Used for MulticastDelegate
internal static DelegateEntry GetDelegateSerializationInfo(SerializationInfo info, Type delegateType, Object target, MethodInfo method, int targetIndex)
{
Message.DebugOut("Inside GetDelegateSerializationInfo \n");
if (method==null) {
throw new ArgumentNullException("method");
}
BCLDebug.Assert(!(target is Delegate),"!(target is Delegate)");
BCLDebug.Assert(info!=null, "[DelegateSerializationHolder.GetDelegateSerializationInfo]info!=null");
Type c = delegateType.BaseType;
if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate))) {
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type");
}
DelegateEntry de = new DelegateEntry(
delegateType.FullName,
delegateType.Module.Assembly.FullName,
target,
method.ReflectedType.Module.Assembly.FullName,
method.ReflectedType.FullName,
method.Name
);
if (info.MemberCount == 0)
{
info.SetType(typeof(DelegateSerializationHolder));
info.AddValue("Delegate",de,typeof(DelegateEntry));
}
// target can be an object so it needs to be added to the info, or else a fixup is needed
// when deserializing, and the fixup will occur too late. If it is added directly to the
// info then the rules of deserialization will guarantee that it will be available when
// needed
if (target != null)
{
String targetName = "target"+targetIndex;
info.AddValue(targetName, de.target);
de.target = targetName;
}
return de;
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DelegateSerHolderSerial"));
}
internal DelegateSerializationHolder(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException("info");
}
bool bNewWire = true;
try
{
m_delegateEntry = (DelegateEntry)info.GetValue("Delegate", typeof(DelegateEntry));
}
catch(Exception)
{
// Old wire format
m_delegateEntry = OldDelegateWireFormat(info, context);
bNewWire = false;
}
if (bNewWire)
{
// retrieve the targets
DelegateEntry deiter = m_delegateEntry;
while (deiter != null)
{
if (deiter.target != null)
{
string stringTarget = deiter.target as string; //need test to pass older wire format
if (stringTarget != null)
deiter.target = info.GetValue(stringTarget, typeof(Object));
}
deiter= deiter.delegateEntry;
}
}
}
private DelegateEntry OldDelegateWireFormat(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException("info");
}
String delegateType = info.GetString("DelegateType");
String delegateAssembly = info.GetString("DelegateAssembly");
Object target = info.GetValue("Target", typeof(Object));
String targetTypeAssembly = info.GetString("TargetTypeAssembly");
String targetTypeName = info.GetString("TargetTypeName");
String methodName = info.GetString("MethodName");
return new DelegateEntry(delegateType, delegateAssembly, target, targetTypeAssembly, targetTypeName, methodName);
}
public virtual Object GetRealObject(StreamingContext context)
{
Delegate root = GetDelegate(m_delegateEntry);
MulticastDelegate mdroot = root as MulticastDelegate;
if (mdroot != null)
{
DelegateEntry de = m_delegateEntry.Entry;
MulticastDelegate previous = mdroot;
while (de != null)
{
Delegate newdelegate = GetDelegate(de);
MulticastDelegate current = newdelegate as MulticastDelegate;
if (current != null)
{
previous.Previous = current;
previous = current;
de = de.Entry;
}
else
{
break;
}
}
}
return root;
}
private Delegate GetDelegate(DelegateEntry de)
{
Delegate d;
if (de.methodName==null || de.methodName.Length==0) {
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
}
Assembly assem = FormatterServices.LoadAssemblyFromString(de.assembly);
if (assem==null) {
BCLDebug.Trace("SER", "[DelegateSerializationHolder.ctor]: Unable to find assembly for TargetType: ", de.assembly);
throw new SerializationException(String.Format(Environment.GetResourceString("Serialization_AssemblyNotFound"), de.assembly));
}
Type type = assem.GetTypeInternal(de.type, false, false, false);
assem = FormatterServices.LoadAssemblyFromString(de.targetTypeAssembly);
if (assem==null) {
BCLDebug.Trace("SER", "[DelegateSerializationHolder.ctor]: Unable to find assembly for TargetType: ", de.targetTypeAssembly);
throw new SerializationException(String.Format(Environment.GetResourceString("Serialization_AssemblyNotFound"), de.targetTypeAssembly));
}
Type targetType = assem.GetTypeInternal(de.targetTypeName, false, false, false);
if (de.target==null && targetType==null) {
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
}
if (type==null) {
BCLDebug.Trace("SER","[DelegateSerializationHolder.GetRealObject]Missing Type");
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
}
if (targetType==null) {
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
}
Object target = null;
if (de.target!=null) { //We have a delegate to a non-static object
target = RemotingServices.CheckCast(de.target, targetType);
d=Delegate.CreateDelegate(type, target, de.methodName);
} else {
//For a static delegate
d=Delegate.CreateDelegate(type, targetType, de.methodName);
}
// We will refuse to create delegates to methods that are non-public.
MethodInfo mi = d.Method;
if (mi != null)
{
if (!mi.IsPublic)
{
throw new SerializationException(
Environment.GetResourceString("Serialization_RefuseNonPublicDelegateCreation"));
}
}
return d;
}
[Serializable]
internal class DelegateEntry
{
internal String type;
internal String assembly;
internal Object target;
internal String targetTypeAssembly;
internal String targetTypeName;
internal String methodName;
internal DelegateEntry delegateEntry;
internal DelegateEntry(String type, String assembly, Object target, String targetTypeAssembly, String targetTypeName, String methodName)
{
this.type = type;
this.assembly = assembly;
this.target = target;
this.targetTypeAssembly = targetTypeAssembly;
this.targetTypeName = targetTypeName;
this.methodName = methodName;
}
internal DelegateEntry Entry
{
get{return delegateEntry;}
set{delegateEntry = value;}
}
}
}
}
+115
View File
@@ -0,0 +1,115 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace System.Diagnostics {
using System;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
// Class which handles code asserts. Asserts are used to explicitly protect
// assumptions made in the code. In general if an assert fails, it indicates
// a program bug so is immediately called to the attention of the user.
// Only static data members, does not need to be marked with the serializable attribute
/// <include file='doc\Assert.uex' path='docs/doc[@for="Assert"]/*' />
internal class Assert
{
private static AssertFilter[] ListOfFilters = null;
private static int iNumOfFilters = 0;
private static int iFilterArraySize = 0;
private static AssertFilter DefFil = new DefaultFilter();
// AddFilter adds a new assert filter. This replaces the current
// filter, unless the filter returns FailContinue.
//
/// <include file='doc\Assert.uex' path='docs/doc[@for="Assert.AddFilter"]/*' />
public static void AddFilter(AssertFilter filter)
{
if (iFilterArraySize <= iNumOfFilters)
{
AssertFilter[] newFilterArray = new AssertFilter [iFilterArraySize+2];
if (iNumOfFilters > 0)
Array.Copy(ListOfFilters, newFilterArray, iNumOfFilters);
iFilterArraySize += 2;
ListOfFilters = newFilterArray;
}
ListOfFilters [iNumOfFilters++] = filter;
}
// Called when an assertion is being made.
//
/// <include file='doc\Assert.uex' path='docs/doc[@for="Assert.Check"]/*' />
public static void Check(bool condition, String conditionString, String message)
{
if (!condition)
{
Fail (conditionString, message);
}
}
/// <include file='doc\Assert.uex' path='docs/doc[@for="Assert.Fail"]/*' />
public static void Fail(String conditionString, String message)
{
// get the stacktrace
StackTrace st = new StackTrace();
// Run through the list of filters backwards (the last filter in the list
// is the default filter. So we're guaranteed that there will be atleast
// one filter to handle the assert.
int iTemp = iNumOfFilters;
while (iTemp > 0)
{
AssertFilters iResult = ListOfFilters [--iTemp].AssertFailure (conditionString, message, st);
if (iResult == AssertFilters.FailDebug)
{
if (Debugger.IsAttached == true)
Debugger.Break();
else
{
if (Debugger.Launch() == false)
{
throw new InvalidOperationException(
Environment.GetResourceString("InvalidOperation_DebuggerLaunchFailed"));
}
}
break;
}
else if (iResult == AssertFilters.FailTerminate)
Environment.Exit(-1);
else if (iResult == AssertFilters.FailIgnore)
break;
// If none of the above, it means that the Filter returned FailContinue.
// So invoke the next filter.
}
}
// Called when an assertion fails.
//
/// <include file='doc\Assert.uex' path='docs/doc[@for="Assert.ShowDefaultAssertDialog"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static int ShowDefaultAssertDialog(String conditionString, String message);
}
}
@@ -0,0 +1,56 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace System.Diagnostics {
using System;
// A Filter is used to decide whether an assert failure
// should terminate the program (or invoke the debugger).
// Typically this is done by popping up a dialog & asking the user.
//
// The default filter brings up a simple Win32 dialog with 3 buttons.
[Serializable()]
abstract internal class AssertFilter
{
// Called when an assert fails. This should be overridden with logic which
// determines whether the program should terminate or not. Typically this
// is done by asking the user.
//
abstract public AssertFilters AssertFailure(String condition, String message,
StackTrace location);
}
// No data, does not need to be marked with the serializable attribute
internal class DefaultFilter : AssertFilter
{
internal DefaultFilter()
{
Assert.AddFilter (this);
}
public override AssertFilters AssertFailure(String condition, String message,
StackTrace location)
{
// .
return (AssertFilters) Assert.ShowDefaultAssertDialog (condition, message);
}
}
}
@@ -0,0 +1,34 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace System.Diagnostics {
/*
* FailDebug indicates the debugger should be invoked
* FailIgnore indicates the failure should be ignored & the
* program continued
* FailTerminate indicates that the program should be terminated
* FailContinue indicates that no decision is made -
* the previous Filter should be invoked
*/
using System;
[Serializable()]
internal enum AssertFilters
{
FailDebug = 0,
FailIgnore = 1,
FailTerminate = 2,
FailContinueFilter = 3,
}
}
@@ -0,0 +1,37 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
using System;
namespace System.Diagnostics {
/// <include file='doc\ConditionalAttribute.uex' path='docs/doc[@for="ConditionalAttribute"]/*' />
[AttributeUsage(AttributeTargets.Method, AllowMultiple=true), Serializable]
public sealed class ConditionalAttribute : Attribute
{
/// <include file='doc\ConditionalAttribute.uex' path='docs/doc[@for="ConditionalAttribute.ConditionalAttribute"]/*' />
public ConditionalAttribute(String conditionString)
{
m_conditionString = conditionString;
}
/// <include file='doc\ConditionalAttribute.uex' path='docs/doc[@for="ConditionalAttribute.ConditionString"]/*' />
public String ConditionString {
get {
return m_conditionString;
}
}
private String m_conditionString;
}
}
+131
View File
@@ -0,0 +1,131 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
// The Debugger class is a part of the System.Diagnostics package
// and is used for communicating with a debugger.
namespace System.Diagnostics {
using System;
using System.IO;
using System.Collections;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
// No data, does not need to be marked with the serializable attribute
/// <include file='doc\Debugger.uex' path='docs/doc[@for="Debugger"]/*' />
public sealed class Debugger
{
// Break causes a breakpoint to be signalled to an attached debugger. If no debugger
// is attached, the user is asked if he wants to attach a debugger. If yes, then the
// debugger is launched.
/// <include file='doc\Debugger.uex' path='docs/doc[@for="Debugger.Break"]/*' />
public static void Break()
{
if (!IsDebuggerAttached())
{
// Try and demand UIPermission. This is done in a try block because if this
// fails we want to be able to silently eat the exception and just return so
// that the call to Break does not possibly cause an unhandled exception.
try
{
new UIPermission(PermissionState.Unrestricted).Demand();
}
// If we enter this block, we do not have permission to break into the debugger
// and so we just return.
catch (SecurityException)
{
return;
}
}
// Causing a break is now allowed.
BreakInternal();
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void BreakInternal();
// Launch launches & attaches a debugger to the process. If a debugger is already attached,
// nothing happens.
//
/// <include file='doc\Debugger.uex' path='docs/doc[@for="Debugger.Launch"]/*' />
public static bool Launch()
{
if (IsDebuggerAttached())
return (true);
// Try and demand UIPermission. This is done in a try block because if this
// fails we want to be able to silently eat the exception and just return so
// that the call to Break does not possibly cause an unhandled exception.
try
{
new UIPermission(PermissionState.Unrestricted).Demand();
}
// If we enter this block, we do not have permission to break into the debugger
// and so we just return.
catch (SecurityException)
{
return (false);
}
// Causing the debugger to launch is now allowed.
return (LaunchInternal());
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool LaunchInternal();
// Returns whether or not a debugger is attached to the process.
//
/// <include file='doc\Debugger.uex' path='docs/doc[@for="Debugger.IsAttached"]/*' />
public static bool IsAttached
{
get { return IsDebuggerAttached(); }
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool IsDebuggerAttached();
// Constants representing the importance level of messages to be logged.
//
// An attached debugger can enable or disable which messages will
// actually be reported to the user through the COM+ debugger
// services API. This info is communicated to the runtime so only
// desired events are actually reported to the debugger.
//
// Constant representing the default category
/// <include file='doc\Debugger.uex' path='docs/doc[@for="Debugger.DefaultCategory"]/*' />
public static readonly String DefaultCategory = null;
// Posts a message for the attached debugger. If there is no
// debugger attached, has no effect. The debugger may or may not
// report the message depending on its settings.
/// <include file='doc\Debugger.uex' path='docs/doc[@for="Debugger.Log"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void Log(int level, String category, String message);
// Checks to see if an attached debugger has logging enabled
//
/// <include file='doc\Debugger.uex' path='docs/doc[@for="Debugger.IsLogging"]/*' />
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern bool IsLogging();
}
}
@@ -0,0 +1,82 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*============================================================
**
** Class: DebuggerAttributes
**
**
**
** Purpose: Attributes for debugger
**
** Date: Feb 01, 2000
**
===========================================================*/
namespace System.Diagnostics {
/// <include file='doc\DebuggerAttributes.uex' path='docs/doc[@for="DebuggerStepThroughAttribute"]/*' />
[Serializable, AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
public sealed class DebuggerStepThroughAttribute : Attribute
{
/// <include file='doc\DebuggerAttributes.uex' path='docs/doc[@for="DebuggerStepThroughAttribute.DebuggerStepThroughAttribute"]/*' />
public DebuggerStepThroughAttribute () {}
}
/// <include file='doc\DebuggerAttributes.uex' path='docs/doc[@for="DebuggerHiddenAttribute"]/*' />
[Serializable, AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
public sealed class DebuggerHiddenAttribute : Attribute
{
/// <include file='doc\DebuggerAttributes.uex' path='docs/doc[@for="DebuggerHiddenAttribute.DebuggerHiddenAttribute"]/*' />
public DebuggerHiddenAttribute () {}
}
// Attribute class used by the compiler to mark modules.
// If present, then debugging information for everything in the
// assembly was generated by the compiler, and will be preserved
// by the Runtime so that the debugger can provide full functionality
// in the case of JIT attach. If not present, then the compiler may
// or may not have included debugging information, and the Runtime
// won't preserve the debugging info, which will make debugging after
// a JIT attach difficult.
/// <include file='doc\DebuggerAttributes.uex' path='docs/doc[@for="DebuggableAttribute"]/*' />
[AttributeUsage(AttributeTargets.Assembly|AttributeTargets.Module, AllowMultiple = false)]
public sealed class DebuggableAttribute : Attribute
{
bool m_isJITTrackingEnabled;
bool m_isJITOptimizerDisabled;
/// <include file='doc\DebuggerAttributes.uex' path='docs/doc[@for="DebuggableAttribute.DebuggableAttribute"]/*' />
public DebuggableAttribute(bool isJITTrackingEnabled,
bool isJITOptimizerDisabled)
{
m_isJITTrackingEnabled = isJITTrackingEnabled;
m_isJITOptimizerDisabled = isJITOptimizerDisabled;
}
/// <include file='doc\DebuggerAttributes.uex' path='docs/doc[@for="DebuggableAttribute.IsJITTrackingEnabled"]/*' />
public bool IsJITTrackingEnabled
{
get { return m_isJITTrackingEnabled; }
}
/// <include file='doc\DebuggerAttributes.uex' path='docs/doc[@for="DebuggableAttribute.IsJITOptimizerDisabled"]/*' />
public bool IsJITOptimizerDisabled
{
get { return m_isJITOptimizerDisabled; }
}
}
}
+330
View File
@@ -0,0 +1,330 @@
// ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace System.Diagnostics {
using System.Runtime.Remoting;
using System;
using System.IO;
using System.Collections;
using System.Runtime.CompilerServices;
using Encoding = System.Text.Encoding;
// LogMessageEventHandlers are triggered when a message is generated which is
// "on" per its switch.
//
// By default, the debugger (if attached) is the only event handler.
// There is also a "built-in" console device which can be enabled
// programatically, by registry (specifics....) or environment
// variables.
[Serializable()]
internal delegate void LogMessageEventHandler(LoggingLevels level, LogSwitch category,
String message,
StackTrace location);
// LogSwitchLevelHandlers are triggered when the level of a LogSwitch is modified
// NOTE: These are NOT triggered when the log switch setting is changed from the
// attached debugger.
//
[Serializable()]
internal delegate void LogSwitchLevelHandler(LogSwitch ls, LoggingLevels newLevel);
/// <include file='doc\log.uex' path='docs/doc[@for="Log"]/*' />
internal class Log
{
// Switches allow relatively fine level control of which messages are
// actually shown. Normally most debugging messages are not shown - the
// user will typically enable those which are relevant to what is being
// investigated.
//
// An attached debugger can enable or disable which messages will
// actually be reported to the user through the COM+ debugger
// services API. This info is communicated to the runtime so only
// desired events are actually reported to the debugger.
internal static Hashtable m_Hashtable;
private static bool m_fConsoleDeviceEnabled;
private static Stream[] m_rgStream;
private static int m_iNumOfStreamDevices;
private static int m_iStreamArraySize;
//private static StreamWriter pConsole;
internal static int iNumOfSwitches;
//private static int iNumOfMsgHandlers;
//private static int iMsgHandlerArraySize;
private static LogMessageEventHandler _LogMessageEventHandler;
private static LogSwitchLevelHandler _LogSwitchLevelHandler;
// Constant representing the global switch
/// <include file='doc\log.uex' path='docs/doc[@for="Log.GlobalSwitch"]/*' />
public static readonly LogSwitch GlobalSwitch;
static Log()
{
m_Hashtable = new Hashtable();
m_fConsoleDeviceEnabled = false;
m_rgStream = null;
m_iNumOfStreamDevices = 0;
m_iStreamArraySize = 0;
//pConsole = null;
//iNumOfMsgHandlers = 0;
//iMsgHandlerArraySize = 0;
// allocate the GlobalSwitch object
GlobalSwitch = new LogSwitch ("Global", "Global Switch for this log");
GlobalSwitch.MinimumLevel = LoggingLevels.ErrorLevel;
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.AddOnLogMessage"]/*' />
public static void AddOnLogMessage(LogMessageEventHandler handler)
{
_LogMessageEventHandler =
(LogMessageEventHandler) MulticastDelegate.Combine(_LogMessageEventHandler, handler);
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.RemoveOnLogMessage"]/*' />
public static void RemoveOnLogMessage(LogMessageEventHandler handler)
{
_LogMessageEventHandler =
(LogMessageEventHandler) MulticastDelegate.Remove(_LogMessageEventHandler, handler);
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.AddOnLogSwitchLevel"]/*' />
public static void AddOnLogSwitchLevel(LogSwitchLevelHandler handler)
{
_LogSwitchLevelHandler =
(LogSwitchLevelHandler) MulticastDelegate.Combine(_LogSwitchLevelHandler, handler);
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.RemoveOnLogSwitchLevel"]/*' />
public static void RemoveOnLogSwitchLevel(LogSwitchLevelHandler handler)
{
_LogSwitchLevelHandler =
(LogSwitchLevelHandler) MulticastDelegate.Remove(_LogSwitchLevelHandler, handler);
}
internal static void InvokeLogSwitchLevelHandlers (LogSwitch ls, LoggingLevels newLevel)
{
if (_LogSwitchLevelHandler != null)
_LogSwitchLevelHandler(ls, newLevel);
}
// Property to Enable/Disable ConsoleDevice. Enabling the console device
// adds the console device as a log output, causing any
// log messages which make it through filters to be written to the
// application console. The console device is enabled by default if the
// ??? registry entry or ??? environment variable is set.
/// <include file='doc\log.uex' path='docs/doc[@for="Log.IsConsoleEnabled"]/*' />
public static bool IsConsoleEnabled
{
get { return m_fConsoleDeviceEnabled; }
set { m_fConsoleDeviceEnabled = value; }
}
// AddStream uses the given stream to create and add a new log
// device. Any log messages which make it through filters will be written
// to the stream.
//
/// <include file='doc\log.uex' path='docs/doc[@for="Log.AddStream"]/*' />
public static void AddStream(Stream stream)
{
if (stream==null)
throw new ArgumentNullException("stream");
if (m_iStreamArraySize <= m_iNumOfStreamDevices)
{
// increase array size in chunks of 4
Stream[] newArray = new Stream [m_iStreamArraySize+4];
// copy the old array objects into the new one.
if (m_iNumOfStreamDevices > 0)
Array.Copy(m_rgStream, newArray, m_iNumOfStreamDevices);
m_iStreamArraySize += 4;
m_rgStream = newArray;
}
m_rgStream [m_iNumOfStreamDevices++] = stream;
}
// Generates a log message. If its switch (or a parent switch) allows the
// level for the message, it is "broadcast" to all of the log
// devices.
//
/// <include file='doc\log.uex' path='docs/doc[@for="Log.LogMessage"]/*' />
public static void LogMessage(LoggingLevels level, String message)
{
LogMessage (level, GlobalSwitch, message);
}
// Generates a log message. If its switch (or a parent switch) allows the
// level for the message, it is "broadcast" to all of the log
// devices.
//
/// <include file='doc\log.uex' path='docs/doc[@for="Log.LogMessage1"]/*' />
public static void LogMessage(LoggingLevels level, LogSwitch logswitch, String message)
{
if (logswitch == null)
throw new ArgumentNullException ("LogSwitch");
if (level < 0)
throw new ArgumentOutOfRangeException("level", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
// Is logging for this level for this switch enabled?
if (logswitch.CheckLevel (level) == true)
{
// Send message for logging
// first send it to the debugger
Debugger.Log ((int) level, logswitch.strName, message);
// Send to the console device
if (m_fConsoleDeviceEnabled)
{
Console.Write(message);
}
// Send it to the streams
for (int i=0; i<m_iNumOfStreamDevices; i++)
{
StreamWriter sw = new StreamWriter(m_rgStream[i]);
sw.Write(message);
sw.Flush();
}
}
}
/*
* Following are convenience entry points; all go through Log()
* Note that the (Switch switch, String message) variations
* are preferred.
*/
/// <include file='doc\log.uex' path='docs/doc[@for="Log.Trace"]/*' />
public static void Trace(LogSwitch logswitch, String message)
{
LogMessage (LoggingLevels.TraceLevel0, logswitch, message);
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.Trace1"]/*' />
public static void Trace(String switchname, String message)
{
LogSwitch ls;
ls = LogSwitch.GetSwitch (switchname);
LogMessage (LoggingLevels.TraceLevel0, ls, message);
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.Trace2"]/*' />
public static void Trace(String message)
{
LogMessage (LoggingLevels.TraceLevel0, GlobalSwitch, message);
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.Status"]/*' />
public static void Status(LogSwitch logswitch, String message)
{
LogMessage (LoggingLevels.StatusLevel0, logswitch, message);
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.Status1"]/*' />
public static void Status(String switchname, String message)
{
LogSwitch ls;
ls = LogSwitch.GetSwitch (switchname);
LogMessage (LoggingLevels.StatusLevel0, ls, message);
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.Status2"]/*' />
public static void Status(String message)
{
LogMessage (LoggingLevels.StatusLevel0, GlobalSwitch, message);
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.Warning"]/*' />
public static void Warning(LogSwitch logswitch, String message)
{
LogMessage (LoggingLevels.WarningLevel, logswitch, message);
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.Warning1"]/*' />
public static void Warning(String switchname, String message)
{
LogSwitch ls;
ls = LogSwitch.GetSwitch (switchname);
LogMessage (LoggingLevels.WarningLevel, ls, message);
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.Warning2"]/*' />
public static void Warning(String message)
{
LogMessage (LoggingLevels.WarningLevel, GlobalSwitch, message);
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.Error"]/*' />
public static void Error(LogSwitch logswitch, String message)
{
LogMessage (LoggingLevels.ErrorLevel, logswitch, message);
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.Error1"]/*' />
public static void Error(String switchname, String message)
{
LogSwitch ls;
ls = LogSwitch.GetSwitch (switchname);
LogMessage (LoggingLevels.ErrorLevel, ls, message);
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.Error2"]/*' />
public static void Error(String message)
{
LogMessage (LoggingLevels.ErrorLevel, GlobalSwitch, message);
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.Panic"]/*' />
public static void Panic(LogSwitch logswitch, String message)
{
LogMessage (LoggingLevels.PanicLevel, logswitch, message);
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.Panic1"]/*' />
public static void Panic(String switchname, String message)
{
LogSwitch ls;
ls = LogSwitch.GetSwitch (switchname);
LogMessage (LoggingLevels.PanicLevel, ls, message);
}
/// <include file='doc\log.uex' path='docs/doc[@for="Log.Panic2"]/*' />
public static void Panic(String message)
{
LogMessage (LoggingLevels.PanicLevel, GlobalSwitch, message);
}
// Native method to inform the EE about the creation of a new LogSwitch
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void AddLogSwitch(LogSwitch logSwitch);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ModifyLogSwitch (int iNewLevel, String strSwitchName, String strParentName);
}
}

Some files were not shown because too many files have changed in this diff Show More