+2007-10-19 Marek Habersack <mhabersack@novell.com>
+
+ * scripts/Makefile.am (scripts_2_0): added mconfig to the list
+
2007-10-09 Wade Berrier <wberrier@novell.com>
* configure.in: Split up the mono version that goes into Consts.cs
+2007-10-17 Atsushi Enomoto <atsushi@ximian.com>
+
+ * web.config, machine.config: moved webSerices section from former
+ to latter.
+
2007-09-05 Atsushi Enomoto <atsushi@ximian.com>
* machine.config : added WCF sectionGroups.
</strongNames>
<system.web>
+ <webServices>
+ <protocols>
+ <add name="HttpSoap"/>
+ <add name="HttpSoap12"/>
+ <add name="HttpPost"/>
+ <add name="HttpGet"/>
+ <add name="Documentation"/>
+ </protocols>
+ <conformanceWarnings>
+ <add name="BasicProfile1_1"/>
+ </conformanceWarnings>
+ <wsdlHelpGenerator href="DefaultWsdlHelpGenerator.aspx" />
+ </webServices>
+
<membership>
<providers>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" applicationName="/" connectionStringName="LocalSqlServer" />
uiculture="en-US" />
-->
<sessionState mode="InProc" />
- <webServices>
- <protocols>
- <add name="HttpSoap"/>
- <add name="HttpSoap12"/>
- <add name="HttpPost"/>
- <add name="HttpGet"/>
- <add name="Documentation"/>
- </protocols>
- <conformanceWarnings>
- <add name="BasicProfile1_1"/>
- </conformanceWarnings>
- <wsdlHelpGenerator href="DefaultWsdlHelpGenerator.aspx" />
- </webServices>
<pages>
<namespaces>
<add namespace="System" />
Author: Dietmar Maurer (dietmar@ximian.com)
(C) 2001 Ximian, Inc.
-
+(C) 2007 Novell, Inc.
+
+[ 2007 extensions based on posts from Paolo Molaro ]
+
Howto trigger JIT compilation
=============================
instruction in the caller, so that it directly calls the JIT compiled code
next time.
-Implementation for x86
+Implementation Details
======================
+Mono 1.2.6 has quite a few improvements in this area compared to mono
+1.2.5 which was released just a few weeks ago. I'll try to detail the
+major changes below.
+
+The first change is related to how the memory for the specific
+trampolines is allocated: this is executable memory so it is not
+allocated with malloc, but with a custom allocator, called Mono Code
+Manager. Since the code manager is used primarily for methods, it
+allocates chunks of memory that are aligned to multiples of 8 or 16
+bytes depending on the architecture: this allows the cpu to fetch the
+instructions faster. But the specific trampolines are not performance
+critical (we'll spend lots of time JITting the method anyway), so they
+can tolerate a smaller alignment. Considering the fact that most
+trampolines are allocated one after the other and that in most
+architectures they are 10 or 12 bytes, this change alone saved about
+25% of the memory used (they used to be aligned up to 16 bytes).
+
+To give a rough idea of how many trampolines are generated I'll give a
+few examples:
+
+ * MonoDevelop startup creates about 21 thousand trampolines
+ * IronPython 2.0 running a benchmark creates about 17 thousand trampolines
+ * an "hello, world" style program about 800
+
+This change in the first case saved more than 80 KB of memory (plus
+about the same because reviewing the code allowed me to fix also a
+related overallocation issue).
+
+So reducing the size of the trampolines is great, but it's really not
+possible to reduce them much further in size, if at all. The next step
+is trying just not to create them.
+
+There are two primary ways a trampoline is generated: a direct call to
+the method is made or a virtual table slot is filled with a trampoline
+for the case when the method is invoked using a virtual call. I'll
+note here than in both cases, after compiling the method, the magic
+trampoline will do the needed changes so that the trampoline is not
+executed again, but execution goes directly to the newly compiled
+code. In one case the callsite is changed so that the branch or call
+instruction will transfer control to the new address. In the virtual
+call case the magic trampoline will change the virtual table slot
+directly.
+
+The sequence of instructions used by the JIT to implement a virtual
+call are well-known and the magic trampoline (inspecting the registers
+and the code sequence) can easily get the virtual table slot that was
+used for the invocation. The idea here then is: if we know the virtual
+table slot we know also the method that is supposed to be compiled and
+executed, since each vtable slot is assigned a unique method by the
+class loader. This simple fact allows us to use a completely generic
+trampoline in the virtual table slots, avoiding the creation of many
+method-specific trampolines.
+
+In the cases above, the number of generated trampolines goes from
+21000 to 7700 for MonoDevelop (saving 160 KB of memory), from 17000 to
+5400 for the IronPython case and from 800 to 150 for the hello world
+case.
+
+
+Implementation for x86/x86-64
+=============================
+
+Usually code looks like this:
+
+ mov <some address>, %r11
+ call *0xfffffffc(%rax)
+
+First, the first call instruction can go directly to the compiled
+address or to a trampoline.
+
+If it goes to a trampoline, on amd64 it looks as the one above (on x86
+it is different). Currently the trampoline is not modified, but it will
+be in the future. On x86 the trampoline looks like:
+
+ push constant
+ jmp generic_trampoline
+
+Note that constant can be a MonoMethod*, but it's not necessarily so
+(these are the recent changes: this constant can be -1 or -2, the first
+for the case of interface calls, the second for virtual calls).
+
+Other architectures are similar in the semantics, but different in the
+details.
+
+The above is what happens for virtual calls.
+
+For interfaces call 3 things can happen:
+
+ 1) the calls goes directly to the method address.
+
+ 2) it goes to a trampoline as described above.
+
+ 3) it goes into an IMT collision resolution stub: this is a
+ chunk of code that, based on the constant put inside the
+ imt_register above, will perform a jump to the correct
+ vtable slot for the interface method.
+
+Note that the vtable slot itself could then contain a trampoline.
+
+Some functions that are used here:
+
emit-x86.c (arch_create_jit_trampoline): return the JIT trampoline function
emit-x86.c (x86_magic_trampoline): contains the code to detect the caller and
emit-x86.c (arch_compile_method): JIT compile a method
+Call Sites
+==========
+
+There are 3 basic different kinds of call sites:
+
+ 1) normal calls:
+ call relative_displacement
+
+ 2) virtual calls:
+ call *positive_offset(%register)
+
+ 3) interface calls:
+ mov constant, %imt_register
+ call *negative_offset(%register)
+
+The above is what happens on x86 and amd64, with different values of
+%imt_register for each arch (this register is a constant, but it could
+change with different mono builds, it should be likely one of
+constants the runtime comunicates to the debugger). %register can
+change depending on the callsite based on the register allocator
+choices. Note that the constant for the interface calls won't
+necessarily be a MonoMethod address: this could change in the future
+to a simple number.
+
+In all the 3 cases the JIT trampolines will need to inspect the call
+site, but only in the first case the call site will be changed.
+2007-10-23 Marek Habersack <mhabersack@novell.com>
+
+ * mconfig.1: added
+
+ * Makefile.am (man_MANS): added mconfig.1
+
+2007-10-17 Sebastien Pouliot <sebastien@ximian.com>
+
+ * sn.1: Fix help for -T / -t as this shows the public key token
+ (and not the public key).
+
2007-08-31 Sebastien Pouliot <sebastien@ximian.com>
* permview.1: add documentation for the -xml option now available
cert2spc.1 cilc.1 genxs.1 wsdl.1 disco.1 soapsuds.1 makecert.1 \
chktrust.1 setreg.1 sn.1 secutil.1 signcode.1 certmgr.1 monop.1 xsd.1 gacutil.1 \
macpack.1 mkbundle.1 dtd2xsd.1 permview.1 prj2make.1 mono-service.1 mono-shlib-cop.1 \
- al.1 mozroots.1 mono-xmltool.1 sgen.1 httpcfg.1 vbnc.1 resgen.1 monolinker.1
+ al.1 mozroots.1 mono-xmltool.1 sgen.1 httpcfg.1 vbnc.1 resgen.1 monolinker.1 mconfig.1
EXTRA_DIST = $(man_MANS)
--- /dev/null
+.TH Mono "mconfig"
+.SH NAME
+mconfig, \- Utility for modifying .NET configuration files
+.SH SYNOPSIS
+.B mconfig [options] command [command_parameters]
+.SH DESCRIPTION
+mconfig can be used to edit .NET configuration files, by adding "features"
+(that is sets of xml statements) defined in one of the config files read
+by mconfig. The config file can also define layouts of default configuration
+files, which may be useful for bootstrapping your .NET projects.
+.SH OPTIONS
+.TP
+.B -c <config_file>, --config=<config_file>
+Read the specified config file after reading the other, preconfigured, config
+files for the utility. Settings in the specified file override those found in
+the other configuration locations.
+.TP
+.B -t {any | web | application}, --target={any | web | application}
+Features and default configuration files defined in the mconfig config file(s)
+can be assigned to one of the three targets - \fIweb\fR (for ASP.NET features/config files),
+\fIapplication\fR - for .NET applications, \fIany\fR - applicable in both of the previous
+targets. Defaults to \fIany\fR.
+.TP
+.B -C, --list-configs
+List all the default configuration file names that are defined in the mconfig
+configuration files.
+.TP
+.B -F, --list-features
+List all the features that are defined in the mconfig configuration files and
+which can be added to your existing (or new) .NET configuration files.
+.TP
+.B -?, -h, --help
+Show a summary usage screen.
+.TP
+.B -v, --version
+Show the mconfig version
+.SH COMMANDS
+.TP
+.B {addfeature, af} <feature_name> [config_file_path]
+Adds the feature named \fI<feature_name>\fR to the specified config file. If
+\fI[config_file_path]\fR is omitted, the name of the output configuration file
+will be chosen based on the selected target (see the \fI-t\fR option). The \fIweb\fR
+target outputs configuration to file named \fIWeb.config\fR, and the \fIapplication\fR
+target outputs to file named \fIapplication.exe.config\fR. The \fIany\fR target does not
+have a default output file.
+
+If the specified config file exists, the feature will be injected into it at the locations
+specified by mconfig configuration. If the target config file does not exist, it will be created
+and will contain only the specified feature and all its dependencies.
+.TP
+.B {defaultconfig, dc} [config_name [target_directory]]
+Generates a default config file using the configuration entry named \fI[config_name]\fR and outputs
+the resulting configuration file to the directory given by the \fI[target_directory]\fR option.
+If \fI[config_name]\fR is omitted, it defaults to \fIWeb.config\fR for the \fIweb\fR target and
+\fIapplication\fR target. The \fIany\fR target does not specify any default output configuration
+name. If the \fI[target_directory]\fR parameter is omitted, it defaults to the current directory.
+
+Name of the output config file created in \fI[target_directory]\fR is given in the config file
+layout definition.
+.PP
+.SH FILES
+Config files are read in the order given below. Each subsequent file may override settings found
+in the files read before it.
+.TP
+.B $prefix/etc/mono/mconfig/config.xml
+.Sp
+The default configuration file, distributed with mconfig. \fI$prefix\fR is the mconfig installation
+prefix specified on the compilation time.
+.TP
+.B $config_dir/mconfig/config.xml
+.Sp
+$config_dir is the directory specified in the \fIXDG_CONFIG_HOME\fR environment variable or,
+ if it is empty, in the \fI.config\fR directory located in the user's home directory. This file
+is not distributed with Mono.
+.TP
+.B ./mconfig.xml
+.Sp
+Local configuration file which can contain per-application settings.
+.SH SEE ALSO
+mconfig.config (5)
+.SH AUTHOR
+Written by Marek Habersack
+.SH COPYRIGHT
+Copyright (C) 2007 Novell, Inc (http://www.novell.com)
+.SH MAILING LISTS
+Visit http://lists.ximian.com/mailman/listinfo/mono-devel-list for details.
+.SH WEB SITE
+Visit: http://www.mono-project.com for details
Re-sign the specified assembly using the specified strongname container.
.TP
.I "-t file"
-Show the public key from the specified file.
+Show the public key token from the specified file.
.TP
.I "-tp file"
Show the public key and the public key token from the specified file.
.TP
.I "-T assembly"
-Show the public key from the specified assembly.
+Show the public key token from the specified assembly.
.TP
.I "-Tp assembly"
Show the public key and the public key token from the specified assembly.
+2007-10-22 Geoff Norton <gnorton@novell.com>
+
+ * Makefile: Add a reference to System.Configuration.dll in NET 2.0
+
2007-10-11 Carlos Alberto Cortez <calberto.cortez@gmail.com>
* System.Windows.Forms_test.dll.sources: Added DragEventArgsTest.cs.
@System.Windows.Forms.dll.resources \
-debug -nowarn:618,612,809
+ifeq (net_2_0, $(PROFILE))
+LIB_MCS_FLAGS += /r:System.Configuration.dll
+endif
+
RESX_RESOURCES = \
resources/System.Windows.Forms.resources \
resources/System.Windows.Forms.en.resources \
<Reference Include="System">
<Name>System</Name>
</Reference>
+ <Reference Include="System.configuration" />
<Reference Include="System.Data">
<Name>System.Data</Name>
</Reference>
<Compile Include="System.Windows.Forms.RTF\StyleType.cs" />
<Compile Include="System.Windows.Forms.RTF\TextMap.cs" />
<Compile Include="System.Windows.Forms.RTF\TokenClass.cs" />
- <Compile Include="System.Windows.Forms.Theming\Default\RadioButtonPainter.cs" />
- <Compile Include="System.Windows.Forms.WebBrowserDialogs\AlertCheck.cs" />
- <Compile Include="System.Windows.Forms.WebBrowserDialogs\ConfirmCheck.cs" />
- <Compile Include="System.Windows.Forms.WebBrowserDialogs\Prompt.cs" />
- <Compile Include="System.Windows.Forms.WebBrowserDialogs\Generic.cs" />
<Compile Include="System.Windows.Forms\AccessibleEvents.cs" />
<Compile Include="System.Windows.Forms\AccessibleNavigation.cs" />
<Compile Include="System.Windows.Forms\AccessibleObject.cs" />
<Compile Include="System.Windows.Forms\BindingManagerDataErrorEventArgs.cs" />
<Compile Include="System.Windows.Forms\BindingManagerDataErrorEventHandler.cs" />
<Compile Include="System.Windows.Forms\BindingMemberInfo.cs" />
- <Compile Include="System.Windows.Forms\BindingNavigator.cs" />
- <Compile Include="System.Windows.Forms\BindingSource.cs" />
+ <Compile Include="System.Windows.Forms\BindingNavigator.cs">
+ </Compile>
+ <Compile Include="System.Windows.Forms\BindingSource.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\BindingsCollection.cs" />
<Compile Include="System.Windows.Forms\BootMode.cs" />
<Compile Include="System.Windows.Forms\Border3DSide.cs" />
<Compile Include="System.Windows.Forms\Border3DStyle.cs" />
<Compile Include="System.Windows.Forms\BorderStyle.cs" />
<Compile Include="System.Windows.Forms\BoundsSpecified.cs" />
- <Compile Include="System.Windows.Forms\Button.cs" />
- <Compile Include="System.Windows.Forms\ButtonBase.cs" />
+ <Compile Include="System.Windows.Forms\Button.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\ButtonBase.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\ButtonBorderStyle.cs" />
<Compile Include="System.Windows.Forms\ButtonRenderer.cs" />
<Compile Include="System.Windows.Forms\ButtonState.cs" />
<Compile Include="System.Windows.Forms\CaptionButton.cs" />
<Compile Include="System.Windows.Forms\CategoryGridEntry.cs" />
<Compile Include="System.Windows.Forms\CharacterCasing.cs" />
- <Compile Include="System.Windows.Forms\CheckBox.cs" />
+ <Compile Include="System.Windows.Forms\CheckBox.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\CheckBoxRenderer.cs" />
<Compile Include="System.Windows.Forms\CheckState.cs" />
- <Compile Include="System.Windows.Forms\CheckedListBox.cs" />
+ <Compile Include="System.Windows.Forms\CheckedListBox.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\Clipboard.cs" />
<Compile Include="System.Windows.Forms\CloseReason.cs" />
<Compile Include="System.Windows.Forms\ColorDepth.cs" />
- <Compile Include="System.Windows.Forms\ColorDialog.cs" />
+ <Compile Include="System.Windows.Forms\ColorDialog.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\ColumnClickEventArgs.cs" />
<Compile Include="System.Windows.Forms\ColumnClickEventHandler.cs" />
- <Compile Include="System.Windows.Forms\ColumnHeader.cs" />
+ <Compile Include="System.Windows.Forms\ColumnHeader.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\ColumnHeaderAutoResizeStyle.cs" />
<Compile Include="System.Windows.Forms\ColumnHeaderConverter.cs" />
<Compile Include="System.Windows.Forms\ColumnHeaderStyle.cs" />
<Compile Include="System.Windows.Forms\ColumnWidthChangedEventHandler.cs" />
<Compile Include="System.Windows.Forms\ColumnWidthChangingEventArgs.cs" />
<Compile Include="System.Windows.Forms\ColumnWidthChangingEventHandler.cs" />
- <Compile Include="System.Windows.Forms\ComboBox.cs" />
+ <Compile Include="System.Windows.Forms\ComboBox.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\ComboBoxRenderer.cs" />
<Compile Include="System.Windows.Forms\ComboBoxStyle.cs" />
- <Compile Include="System.Windows.Forms\CommonDialog.cs" />
+ <Compile Include="System.Windows.Forms\CommonDialog.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\ComponentModel.cs" />
- <Compile Include="System.Windows.Forms\ContainerControl.cs" />
+ <Compile Include="System.Windows.Forms\ContainerControl.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\ContentsResizedEventArgs.cs" />
<Compile Include="System.Windows.Forms\ContentsResizedEventHandler.cs" />
- <Compile Include="System.Windows.Forms\ContextMenu.cs" />
- <Compile Include="System.Windows.Forms\ContextMenuStrip.cs" />
- <Compile Include="System.Windows.Forms\Control.cs" />
+ <Compile Include="System.Windows.Forms\ContextMenu.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\ContextMenuStrip.cs">
+ </Compile>
+ <Compile Include="System.Windows.Forms\Control.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\ControlBindingsCollection.cs" />
<Compile Include="System.Windows.Forms\ControlEventArgs.cs" />
<Compile Include="System.Windows.Forms\ControlEventHandler.cs" />
<Compile Include="System.Windows.Forms\CursorConverter.cs" />
<Compile Include="System.Windows.Forms\Cursors.cs" />
<Compile Include="System.Windows.Forms\DataFormats.cs" />
- <Compile Include="System.Windows.Forms\DataGrid.cs" />
- <Compile Include="System.Windows.Forms\DataGridBoolColumn.cs" />
+ <Compile Include="System.Windows.Forms\DataGrid.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\DataGridBoolColumn.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\DataGridCell.cs" />
- <Compile Include="System.Windows.Forms\DataGridColumnStyle.cs" />
+ <Compile Include="System.Windows.Forms\DataGridColumnStyle.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\DataGridLineStyle.cs" />
<Compile Include="System.Windows.Forms\DataGridParentRowsLabelStyle.cs" />
<Compile Include="System.Windows.Forms\DataGridPreferredColumnWidthTypeConverter.cs" />
- <Compile Include="System.Windows.Forms\DataGridTableStyle.cs" />
- <Compile Include="System.Windows.Forms\DataGridTextBox.cs" />
- <Compile Include="System.Windows.Forms\DataGridTextBoxColumn.cs" />
- <Compile Include="System.Windows.Forms\DataGridView.cs" />
+ <Compile Include="System.Windows.Forms\DataGridTableStyle.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\DataGridTextBox.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\DataGridTextBoxColumn.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\DataGridView.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\DataGridViewAdvancedBorderStyle.cs" />
<Compile Include="System.Windows.Forms\DataGridViewAdvancedCellBorderStyle.cs" />
<Compile Include="System.Windows.Forms\DataGridViewAutoSizeColumnMode.cs" />
<Compile Include="System.Windows.Forms\DataGridViewComboBoxCell.cs" />
<Compile Include="System.Windows.Forms\DataGridViewComboBoxColumn.cs" />
<Compile Include="System.Windows.Forms\DataGridViewComboBoxDisplayStyle.cs" />
- <Compile Include="System.Windows.Forms\DataGridViewComboBoxEditingControl.cs" />
+ <Compile Include="System.Windows.Forms\DataGridViewComboBoxEditingControl.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\DataGridViewContentAlignment.cs" />
<Compile Include="System.Windows.Forms\DataGridViewDataErrorContexts.cs" />
<Compile Include="System.Windows.Forms\DataGridViewDataErrorEventArgs.cs" />
<Compile Include="System.Windows.Forms\DataGridViewSortCompareEventHandler.cs" />
<Compile Include="System.Windows.Forms\DataGridViewTextBoxCell.cs" />
<Compile Include="System.Windows.Forms\DataGridViewTextBoxColumn.cs" />
- <Compile Include="System.Windows.Forms\DataGridViewTextBoxEditingControl.cs" />
+ <Compile Include="System.Windows.Forms\DataGridViewTextBoxEditingControl.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\DataGridViewTopLeftHeaderCell.cs" />
<Compile Include="System.Windows.Forms\DataGridViewTriState.cs" />
<Compile Include="System.Windows.Forms\DataObject.cs" />
<Compile Include="System.Windows.Forms\DateBoldEventHandler.cs" />
<Compile Include="System.Windows.Forms\DateRangeEventArgs.cs" />
<Compile Include="System.Windows.Forms\DateRangeEventHandler.cs" />
- <Compile Include="System.Windows.Forms\DateTimePicker.cs" />
+ <Compile Include="System.Windows.Forms\DateTimePicker.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\DateTimePickerFormat.cs" />
<Compile Include="System.Windows.Forms\Day.cs" />
<Compile Include="System.Windows.Forms\DialogResult.cs" />
<Compile Include="System.Windows.Forms\DockingAttribute.cs" />
<Compile Include="System.Windows.Forms\DockStyle.cs" />
<Compile Include="System.Windows.Forms\DockingBehavior.cs" />
- <Compile Include="System.Windows.Forms\DomainUpDown.cs" />
+ <Compile Include="System.Windows.Forms\DomainUpDown.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\DragAction.cs" />
<Compile Include="System.Windows.Forms\DragDropEffects.cs" />
<Compile Include="System.Windows.Forms\DragEventArgs.cs" />
<Compile Include="System.Windows.Forms\DrawTreeNodeEventHandler.cs" />
<Compile Include="System.Windows.Forms\ErrorBlinkStyle.cs" />
<Compile Include="System.Windows.Forms\ErrorIconAlignment.cs" />
- <Compile Include="System.Windows.Forms\ErrorProvider.cs" />
+ <Compile Include="System.Windows.Forms\ErrorProvider.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\FeatureSupport.cs" />
- <Compile Include="System.Windows.Forms\FileDialog.cs" />
+ <Compile Include="System.Windows.Forms\FileDialog.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\FileDialogCustomPlace.cs" />
+ <Compile Include="System.Windows.Forms\FileDialogCustomPlacesCollection.cs" />
<Compile Include="System.Windows.Forms\FixedPanel.cs" />
- <Compile Include="System.Windows.Forms\FixedSizeTextBox.cs" />
+ <Compile Include="System.Windows.Forms\FixedSizeTextBox.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\FlatButtonAppearance.cs" />
<Compile Include="System.Windows.Forms\FlatStyle.cs" />
<Compile Include="System.Windows.Forms\FlowDirection.cs" />
- <Compile Include="System.Windows.Forms\FlowLayoutPanel.cs" />
+ <Compile Include="System.Windows.Forms\FlowLayoutPanel.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\FlowLayoutSettings.cs" />
- <Compile Include="System.Windows.Forms\FolderBrowserDialog.cs" />
- <Compile Include="System.Windows.Forms\FontDialog.cs" />
- <Compile Include="System.Windows.Forms\Form.cs" />
+ <Compile Include="System.Windows.Forms\FolderBrowserDialog.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\FontDialog.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\Form.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\FormBorderStyle.cs" />
<Compile Include="System.Windows.Forms\FormClosedEventArgs.cs" />
<Compile Include="System.Windows.Forms\FormClosedEventHandler.cs" />
<Compile Include="System.Windows.Forms\GridItemType.cs" />
<Compile Include="System.Windows.Forms\GridTableStylesCollection.cs" />
<Compile Include="System.Windows.Forms\GridTablesFactory.cs" />
- <Compile Include="System.Windows.Forms\GroupBox.cs" />
+ <Compile Include="System.Windows.Forms\GroupBox.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\GroupBoxRenderer.cs" />
- <Compile Include="System.Windows.Forms\HScrollBar.cs" />
+ <Compile Include="System.Windows.Forms\HScrollBar.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\HandledMouseEventArgs.cs" />
<Compile Include="System.Windows.Forms\Help.cs" />
<Compile Include="System.Windows.Forms\HelpEventArgs.cs" />
<Compile Include="System.Windows.Forms\HelpEventHandler.cs" />
<Compile Include="System.Windows.Forms\HelpNavigator.cs" />
- <Compile Include="System.Windows.Forms\HelpProvider.cs" />
+ <Compile Include="System.Windows.Forms\HelpProvider.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\HorizontalAlignment.cs" />
<Compile Include="System.Windows.Forms\HScrollProperties.cs" />
<Compile Include="System.Windows.Forms\HtmlDocument.cs" />
<Compile Include="System.Windows.Forms\ImageIndexConverter.cs" />
<Compile Include="System.Windows.Forms\ImageKeyConverter.cs" />
<Compile Include="System.Windows.Forms\ImageLayout.cs" />
- <Compile Include="System.Windows.Forms\ImageList.cs" />
+ <Compile Include="System.Windows.Forms\ImageList.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\ImageListConverter.cs" />
<Compile Include="System.Windows.Forms\ImageListStreamer.cs" />
<Compile Include="System.Windows.Forms\ImeMode.cs" />
- <Compile Include="System.Windows.Forms\ImplicitHScrollBar.cs" />
- <Compile Include="System.Windows.Forms\ImplicitVScrollBar.cs" />
+ <Compile Include="System.Windows.Forms\ImplicitHScrollBar.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\ImplicitVScrollBar.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\InputLanguage.cs" />
<Compile Include="System.Windows.Forms\InputLanguageChangedEventArgs.cs" />
<Compile Include="System.Windows.Forms\InputLanguageChangedEventHandler.cs" />
<Compile Include="System.Windows.Forms\KeyboardLayouts.cs" />
<Compile Include="System.Windows.Forms\Keys.cs" />
<Compile Include="System.Windows.Forms\KeysConverter.cs" />
- <Compile Include="System.Windows.Forms\Label.cs" />
+ <Compile Include="System.Windows.Forms\Label.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\LabelEditEventArgs.cs" />
<Compile Include="System.Windows.Forms\LabelEditEventHandler.cs" />
- <Compile Include="System.Windows.Forms\LabelEditTextBox.cs" />
+ <Compile Include="System.Windows.Forms\LabelEditTextBox.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\LayoutEngine.cs" />
<Compile Include="System.Windows.Forms\LayoutEventArgs.cs" />
<Compile Include="System.Windows.Forms\LayoutEventHandler.cs" />
<Compile Include="System.Windows.Forms\LayoutSettings.cs" />
<Compile Include="System.Windows.Forms\LeftRightAlignment.cs" />
+ <Compile Include="System.Windows.Forms\Line.cs" />
+ <Compile Include="System.Windows.Forms\LineTag.cs" />
<Compile Include="System.Windows.Forms\LinkArea.cs" />
<Compile Include="System.Windows.Forms\LinkBehavior.cs" />
<Compile Include="System.Windows.Forms\LinkClickedEventArgs.cs" />
<Compile Include="System.Windows.Forms\LinkClickedEventHandler.cs" />
<Compile Include="System.Windows.Forms\LinkConverter.cs" />
- <Compile Include="System.Windows.Forms\LinkLabel.cs" />
+ <Compile Include="System.Windows.Forms\LinkLabel.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\LinkLabelLinkClickedEventArgs.cs" />
<Compile Include="System.Windows.Forms\LinkLabelLinkClickedEventHandler.cs" />
<Compile Include="System.Windows.Forms\LinkState.cs" />
<Compile Include="System.Windows.Forms\ListBindingConverter.cs" />
<Compile Include="System.Windows.Forms\ListBindingHelper.cs" />
- <Compile Include="System.Windows.Forms\ListBox.cs" />
- <Compile Include="System.Windows.Forms\ListControl.cs" />
+ <Compile Include="System.Windows.Forms\ListBox.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\ListControl.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\ListControlConvertEventArgs.cs" />
<Compile Include="System.Windows.Forms\ListControlConvertEventHandler.cs" />
- <Compile Include="System.Windows.Forms\ListView.cs" />
+ <Compile Include="System.Windows.Forms\ListView.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\ListViewAlignment.cs" />
<Compile Include="System.Windows.Forms\ListViewGroup.cs" />
<Compile Include="System.Windows.Forms\ListViewGroupCollection.cs" />
<Compile Include="System.Windows.Forms\ListViewItemSelectionChangedEventArgs.cs" />
<Compile Include="System.Windows.Forms\ListViewItemSelectionChangedEventHandler.cs" />
<Compile Include="System.Windows.Forms\ListViewItemStates.cs" />
- <Compile Include="System.Windows.Forms\ListViewVirtualItems.cs" />
<Compile Include="System.Windows.Forms\ListViewVirtualItemsSelectionRangeChangedEventArgs.cs" />
<Compile Include="System.Windows.Forms\ListViewVirtualItemsSelectionRangeChangedEventHandler.cs" />
<Compile Include="System.Windows.Forms\MWFCategoryAttribute.cs" />
<Compile Include="System.Windows.Forms\MWFDescriptionAttribute.cs" />
- <Compile Include="System.Windows.Forms\MainMenu.cs" />
+ <Compile Include="System.Windows.Forms\MainMenu.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\MaskFormat.cs" />
<Compile Include="System.Windows.Forms\MaskInputRejectedEventArgs.cs" />
<Compile Include="System.Windows.Forms\MaskInputRejectedEventHandler.cs" />
- <Compile Include="System.Windows.Forms\MaskedTextBox.cs" />
- <Compile Include="System.Windows.Forms\MdiClient.cs" />
+ <Compile Include="System.Windows.Forms\MaskedTextBox.cs">
+ </Compile>
+ <Compile Include="System.Windows.Forms\MdiClient.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\MdiControlStrip.cs" />
<Compile Include="System.Windows.Forms\MdiLayout.cs" />
<Compile Include="System.Windows.Forms\MdiWindowManager.cs" />
<Compile Include="System.Windows.Forms\MeasureItemEventArgs.cs" />
<Compile Include="System.Windows.Forms\MeasureItemEventHandler.cs" />
- <Compile Include="System.Windows.Forms\Menu.cs" />
- <Compile Include="System.Windows.Forms\MenuAPI.cs" />
+ <Compile Include="System.Windows.Forms\Menu.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\MenuAPI.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\MenuGlyph.cs" />
- <Compile Include="System.Windows.Forms\MenuItem.cs" />
+ <Compile Include="System.Windows.Forms\MenuItem.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\MenuMerge.cs" />
- <Compile Include="System.Windows.Forms\MenuStrip.cs" />
+ <Compile Include="System.Windows.Forms\MenuStrip.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\MergeAction.cs" />
<Compile Include="System.Windows.Forms\Message.cs" />
<Compile Include="System.Windows.Forms\MessageBox.cs" />
<Compile Include="System.Windows.Forms\MethodInvoker.cs" />
<Compile Include="System.Windows.Forms\Mime.cs" />
<Compile Include="System.Windows.Forms\MimeIcon.cs" />
- <Compile Include="System.Windows.Forms\MonthCalendar.cs" />
+ <Compile Include="System.Windows.Forms\MonthCalendar.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\MouseButtons.cs" />
<Compile Include="System.Windows.Forms\MouseEventArgs.cs" />
<Compile Include="System.Windows.Forms\MouseEventHandler.cs" />
<Compile Include="System.Windows.Forms\NavigateEventHandler.cs" />
<Compile Include="System.Windows.Forms\NodeLabelEditEventArgs.cs" />
<Compile Include="System.Windows.Forms\NodeLabelEditEventHandler.cs" />
- <Compile Include="System.Windows.Forms\NotifyIcon.cs" />
- <Compile Include="System.Windows.Forms\NumericTextBox.cs" />
- <Compile Include="System.Windows.Forms\NumericUpDown.cs" />
+ <Compile Include="System.Windows.Forms\NotifyIcon.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\NumericTextBox.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\NumericUpDown.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\NumericUpDownAcceleration.cs" />
<Compile Include="System.Windows.Forms\NumericUpDownAccelerationCollection.cs" />
<Compile Include="System.Windows.Forms\OSFeature.cs" />
<Compile Include="System.Windows.Forms\OSXStructs.cs" />
<Compile Include="System.Windows.Forms\OpacityConverter.cs" />
- <Compile Include="System.Windows.Forms\OpenFileDialog.cs" />
+ <Compile Include="System.Windows.Forms\OpenFileDialog.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\OpenTreeNodeEnumerator.cs" />
<Compile Include="System.Windows.Forms\Orientation.cs" />
<Compile Include="System.Windows.Forms\OwnerDrawPropertyBag.cs" />
<Compile Include="System.Windows.Forms\Padding.cs" />
<Compile Include="System.Windows.Forms\PaddingConverter.cs" />
- <Compile Include="System.Windows.Forms\PageSetupDialog.cs" />
+ <Compile Include="System.Windows.Forms\PageSetupDialog.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\PaintEventArgs.cs" />
<Compile Include="System.Windows.Forms\PaintEventHandler.cs" />
- <Compile Include="System.Windows.Forms\Panel.cs" />
- <Compile Include="System.Windows.Forms\PictureBox.cs" />
+ <Compile Include="System.Windows.Forms\Panel.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\PictureBox.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\PictureBoxSizeMode.cs" />
<Compile Include="System.Windows.Forms\PopupEventArgs.cs" />
<Compile Include="System.Windows.Forms\PopupEventHandler.cs" />
<Compile Include="System.Windows.Forms\PreviewKeyDownEventArgs.cs" />
<Compile Include="System.Windows.Forms\PreviewKeyDownEventHandler.cs" />
<Compile Include="System.Windows.Forms\PrintControllerWithStatusDialog.cs" />
- <Compile Include="System.Windows.Forms\PrintDialog.cs" />
- <Compile Include="System.Windows.Forms\PrintPreviewControl.cs" />
- <Compile Include="System.Windows.Forms\PrintPreviewDialog.cs" />
+ <Compile Include="System.Windows.Forms\PrintDialog.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\PrintPreviewControl.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\PrintPreviewDialog.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\ProfessionalColors.cs" />
<Compile Include="System.Windows.Forms\ProfessionalColorTable.cs" />
- <Compile Include="System.Windows.Forms\ProgressBar.cs" />
+ <Compile Include="System.Windows.Forms\ProgressBar.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\ProgressBarRenderer.cs" />
<Compile Include="System.Windows.Forms\ProgressBarStyle.cs" />
<Compile Include="System.Windows.Forms\PropertiesTab.cs" />
- <Compile Include="System.Windows.Forms\PropertyGrid.cs" />
+ <Compile Include="System.Windows.Forms\PropertyGrid.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\PropertyGridCommands.cs" />
- <Compile Include="System.Windows.Forms\PropertyGridTextBox.cs" />
- <Compile Include="System.Windows.Forms\PropertyGridView.cs" />
+ <Compile Include="System.Windows.Forms\PropertyGridTextBox.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\PropertyGridView.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\PropertyManager.cs" />
<Compile Include="System.Windows.Forms\PropertySort.cs" />
<Compile Include="System.Windows.Forms\PropertyTabChangedEventArgs.cs" />
<Compile Include="System.Windows.Forms\QueryContinueDragEventHandler.cs" />
<Compile Include="System.Windows.Forms\QuestionEventArgs.cs" />
<Compile Include="System.Windows.Forms\QuestionEventHandler.cs" />
- <Compile Include="System.Windows.Forms\RadioButton.cs" />
+ <Compile Include="System.Windows.Forms\RadioButton.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\RadioButtonRenderer.cs" />
<Compile Include="System.Windows.Forms\RelatedCurrencyManager.cs" />
<Compile Include="System.Windows.Forms\RelatedImageListAttribute.cs" />
<Compile Include="System.Windows.Forms\RelatedPropertyManager.cs" />
<Compile Include="System.Windows.Forms\RetrieveVirtualItemEventArgs.cs" />
<Compile Include="System.Windows.Forms\RetrieveVirtualItemEventHandler.cs" />
- <Compile Include="System.Windows.Forms\RichTextBox.cs" />
+ <Compile Include="System.Windows.Forms\RichTextBox.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\RichTextBoxFinds.cs" />
<Compile Include="System.Windows.Forms\RichTextBoxLanguageOptions.cs" />
<Compile Include="System.Windows.Forms\RichTextBoxScrollBars.cs" />
<Compile Include="System.Windows.Forms\RightToLeft.cs" />
<Compile Include="System.Windows.Forms\RootGridEntry.cs" />
<Compile Include="System.Windows.Forms\RowStyle.cs" />
- <Compile Include="System.Windows.Forms\SaveFileDialog.cs" />
+ <Compile Include="System.Windows.Forms\SaveFileDialog.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\Screen.cs" />
<Compile Include="System.Windows.Forms\ScreenOrientation.cs" />
- <Compile Include="System.Windows.Forms\ScrollBar.cs" />
+ <Compile Include="System.Windows.Forms\ScrollBar.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\ScrollBarRenderer.cs" />
<Compile Include="System.Windows.Forms\ScrollBars.cs" />
<Compile Include="System.Windows.Forms\ScrollButton.cs" />
<Compile Include="System.Windows.Forms\ScrollEventType.cs" />
<Compile Include="System.Windows.Forms\ScrollOrientation.cs" />
<Compile Include="System.Windows.Forms\ScrollProperties.cs" />
- <Compile Include="System.Windows.Forms\ScrollableControl.cs" />
+ <Compile Include="System.Windows.Forms\ScrollableControl.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\SearchDirectionHint.cs" />
<Compile Include="System.Windows.Forms\SearchForVirtualItemEventArgs.cs" />
<Compile Include="System.Windows.Forms\SearchForVirtualItemEventHandler.cs" />
<Compile Include="System.Windows.Forms\SelectionRangeConverter.cs" />
<Compile Include="System.Windows.Forms\SendKeys.cs" />
<Compile Include="System.Windows.Forms\Shortcut.cs" />
- <Compile Include="System.Windows.Forms\SizeGrip.cs" />
+ <Compile Include="System.Windows.Forms\SizeGrip.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\SizeGripStyle.cs" />
<Compile Include="System.Windows.Forms\SizeType.cs" />
<Compile Include="System.Windows.Forms\SortOrder.cs" />
- <Compile Include="System.Windows.Forms\SplitContainer.cs" />
- <Compile Include="System.Windows.Forms\Splitter.cs" />
+ <Compile Include="System.Windows.Forms\SplitContainer.cs">
+ </Compile>
+ <Compile Include="System.Windows.Forms\Splitter.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\SplitterCancelEventArgs.cs" />
<Compile Include="System.Windows.Forms\SplitterCancelEventHandler.cs" />
<Compile Include="System.Windows.Forms\SplitterEventArgs.cs" />
<Compile Include="System.Windows.Forms\SplitterEventHandler.cs" />
- <Compile Include="System.Windows.Forms\SplitterPanel.cs" />
- <Compile Include="System.Windows.Forms\StatusBar.cs" />
+ <Compile Include="System.Windows.Forms\SplitterPanel.cs">
+ </Compile>
+ <Compile Include="System.Windows.Forms\StatusBar.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\StatusBarDrawItemEventArgs.cs" />
<Compile Include="System.Windows.Forms\StatusBarDrawItemEventHandler.cs" />
- <Compile Include="System.Windows.Forms\StatusBarPanel.cs" />
+ <Compile Include="System.Windows.Forms\StatusBarPanel.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\StatusBarPanelAutoSize.cs" />
<Compile Include="System.Windows.Forms\StatusBarPanelBorderStyle.cs" />
<Compile Include="System.Windows.Forms\StatusBarPanelClickEventArgs.cs" />
<Compile Include="System.Windows.Forms\StatusBarPanelClickEventHandler.cs" />
<Compile Include="System.Windows.Forms\StatusBarPanelStyle.cs" />
- <Compile Include="System.Windows.Forms\StatusStrip.cs" />
+ <Compile Include="System.Windows.Forms\StatusStrip.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\StructFormat.cs" />
<Compile Include="System.Windows.Forms\SystemInformation.cs" />
<Compile Include="System.Windows.Forms\SystemParameter.cs" />
<Compile Include="System.Windows.Forms\TabAlignment.cs" />
<Compile Include="System.Windows.Forms\TabAppearance.cs" />
- <Compile Include="System.Windows.Forms\TabControl.cs" />
+ <Compile Include="System.Windows.Forms\TabControl.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\TabControlAction.cs" />
<Compile Include="System.Windows.Forms\TabControlCancelEventArgs.cs" />
<Compile Include="System.Windows.Forms\TabControlCancelEventHandler.cs" />
<Compile Include="System.Windows.Forms\TabControlEventArgs.cs" />
<Compile Include="System.Windows.Forms\TabControlEventHandler.cs" />
<Compile Include="System.Windows.Forms\TabDrawMode.cs" />
- <Compile Include="System.Windows.Forms\TabPage.cs" />
+ <Compile Include="System.Windows.Forms\TabPage.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\TabRenderer.cs" />
<Compile Include="System.Windows.Forms\TabSizeMode.cs" />
<Compile Include="System.Windows.Forms\TableLayoutCellPaintEventArgs.cs" />
<Compile Include="System.Windows.Forms\TableLayoutCellPaintEventHandler.cs" />
<Compile Include="System.Windows.Forms\TableLayoutColumnStyleCollection.cs" />
<Compile Include="System.Windows.Forms\TableLayoutControlCollection.cs" />
- <Compile Include="System.Windows.Forms\TableLayoutPanel.cs" />
+ <Compile Include="System.Windows.Forms\TableLayoutPanel.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\TableLayoutPanelCellBorderStyle.cs" />
<Compile Include="System.Windows.Forms\TableLayoutPanelCellPosition.cs" />
<Compile Include="System.Windows.Forms\TableLayoutPanelGrowStyle.cs" />
<Compile Include="System.Windows.Forms\TableLayoutSettings.cs" />
<Compile Include="System.Windows.Forms\TableLayoutStyle.cs" />
<Compile Include="System.Windows.Forms\TableLayoutStyleCollection.cs" />
- <Compile Include="System.Windows.Forms\TextBox.cs" />
- <Compile Include="System.Windows.Forms\TextBoxBase.cs" />
+ <Compile Include="System.Windows.Forms\TextBox.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\TextBoxBase.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\TextBoxRenderer.cs" />
+ <Compile Include="System.Windows.Forms\TextBoxTextRenderer.cs" />
<Compile Include="System.Windows.Forms\TextControl.cs" />
<Compile Include="System.Windows.Forms\TextDataFormat.cs" />
<Compile Include="System.Windows.Forms\TextFormatFlags.cs" />
<Compile Include="System.Windows.Forms\ThemeGtk.cs" />
<Compile Include="System.Windows.Forms\ThemeNice.cs" />
<Compile Include="System.Windows.Forms\ThemeWin32Classic.cs" />
- <Compile Include="System.Windows.Forms\ThreadExceptionDialog.cs" />
+ <Compile Include="System.Windows.Forms\ThreadExceptionDialog.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\TickStyle.cs" />
- <Compile Include="System.Windows.Forms\Timer.cs" />
- <Compile Include="System.Windows.Forms\ToolBar.cs" />
+ <Compile Include="System.Windows.Forms\Timer.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\ToolBar.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\ToolBarAppearance.cs" />
- <Compile Include="System.Windows.Forms\ToolBarButton.cs" />
+ <Compile Include="System.Windows.Forms\ToolBarButton.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\ToolBarButtonClickEventArgs.cs" />
<Compile Include="System.Windows.Forms\ToolBarButtonClickEventHandler.cs" />
<Compile Include="System.Windows.Forms\ToolBarButtonStyle.cs" />
<Compile Include="System.Windows.Forms\ToolBarTextAlign.cs" />
- <Compile Include="System.Windows.Forms\ToolStrip.cs" />
+ <Compile Include="System.Windows.Forms\ToolStrip.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\ToolStripArrowRenderEventArgs.cs" />
<Compile Include="System.Windows.Forms\ToolStripArrowRenderEventHandler.cs" />
- <Compile Include="System.Windows.Forms\ToolStripButton.cs" />
- <Compile Include="System.Windows.Forms\ToolStripComboBox.cs" />
- <Compile Include="System.Windows.Forms\ToolStripContainer.cs" />
- <Compile Include="System.Windows.Forms\ToolStripContentPanel.cs" />
+ <Compile Include="System.Windows.Forms\ToolStripButton.cs">
+ </Compile>
+ <Compile Include="System.Windows.Forms\ToolStripComboBox.cs">
+ </Compile>
+ <Compile Include="System.Windows.Forms\ToolStripContainer.cs">
+ </Compile>
+ <Compile Include="System.Windows.Forms\ToolStripContentPanel.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\ToolStripContentPanelRenderEventArgs.cs" />
<Compile Include="System.Windows.Forms\ToolStripContentPanelRenderEventHandler.cs" />
- <Compile Include="System.Windows.Forms\ToolStripControlHost.cs" />
- <Compile Include="System.Windows.Forms\ToolStripDropDown.cs" />
- <Compile Include="System.Windows.Forms\ToolStripDropDownButton.cs" />
+ <Compile Include="System.Windows.Forms\ToolStripControlHost.cs">
+ </Compile>
+ <Compile Include="System.Windows.Forms\ToolStripDropDown.cs">
+ </Compile>
+ <Compile Include="System.Windows.Forms\ToolStripDropDownButton.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\ToolStripDropDownCloseReason.cs" />
<Compile Include="System.Windows.Forms\ToolStripDropDownClosedEventArgs.cs" />
<Compile Include="System.Windows.Forms\ToolStripDropDownClosedEventHandler.cs" />
<Compile Include="System.Windows.Forms\ToolStripDropDownClosingEventArgs.cs" />
<Compile Include="System.Windows.Forms\ToolStripDropDownClosingEventHandler.cs" />
<Compile Include="System.Windows.Forms\ToolStripDropDownDirection.cs" />
- <Compile Include="System.Windows.Forms\ToolStripDropDownItem.cs" />
+ <Compile Include="System.Windows.Forms\ToolStripDropDownItem.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\ToolStripDropDownItemAccessibleObject.cs" />
- <Compile Include="System.Windows.Forms\ToolStripDropDownMenu.cs" />
+ <Compile Include="System.Windows.Forms\ToolStripDropDownMenu.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\ToolStripGripDisplayStyle.cs" />
<Compile Include="System.Windows.Forms\ToolStripGripRenderEventArgs.cs" />
<Compile Include="System.Windows.Forms\ToolStripGripRenderEventHandler.cs" />
<Compile Include="System.Windows.Forms\ToolStripGripStyle.cs" />
- <Compile Include="System.Windows.Forms\ToolStripItem.cs" />
+ <Compile Include="System.Windows.Forms\ToolStripItem.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\ToolStripItemAlignment.cs" />
<Compile Include="System.Windows.Forms\ToolStripItemClickedEventArgs.cs" />
<Compile Include="System.Windows.Forms\ToolStripItemClickedEventHandler.cs" />
<Compile Include="System.Windows.Forms\ToolStripItemRenderEventHandler.cs" />
<Compile Include="System.Windows.Forms\ToolStripItemTextRenderEventArgs.cs" />
<Compile Include="System.Windows.Forms\ToolStripItemTextRenderEventHandler.cs" />
- <Compile Include="System.Windows.Forms\ToolStripLabel.cs" />
+ <Compile Include="System.Windows.Forms\ToolStripLabel.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\ToolStripLayoutStyle.cs" />
<Compile Include="System.Windows.Forms\ToolStripManager.cs" />
<Compile Include="System.Windows.Forms\ToolStripManagerRenderMode.cs" />
- <Compile Include="System.Windows.Forms\ToolStripMenuItem.cs" />
- <Compile Include="System.Windows.Forms\ToolStripOverflow.cs" />
- <Compile Include="System.Windows.Forms\ToolStripOverflowButton.cs" />
- <Compile Include="System.Windows.Forms\ToolStripPanel.cs" />
+ <Compile Include="System.Windows.Forms\ToolStripMenuItem.cs">
+ </Compile>
+ <Compile Include="System.Windows.Forms\ToolStripOverflow.cs">
+ </Compile>
+ <Compile Include="System.Windows.Forms\ToolStripOverflowButton.cs">
+ </Compile>
+ <Compile Include="System.Windows.Forms\ToolStripPanel.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\ToolStripPanelRenderEventArgs.cs" />
<Compile Include="System.Windows.Forms\ToolStripPanelRenderEventHandler.cs" />
- <Compile Include="System.Windows.Forms\ToolStripPanelRow.cs" />
+ <Compile Include="System.Windows.Forms\ToolStripPanelRow.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\ToolStripProfessionalRenderer.cs" />
- <Compile Include="System.Windows.Forms\ToolStripProgressBar.cs" />
+ <Compile Include="System.Windows.Forms\ToolStripProgressBar.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\ToolStripRenderer.cs" />
<Compile Include="System.Windows.Forms\ToolStripRenderEventArgs.cs" />
<Compile Include="System.Windows.Forms\ToolStripRenderEventHandler.cs" />
<Compile Include="System.Windows.Forms\ToolStripRenderMode.cs" />
- <Compile Include="System.Windows.Forms\ToolStripSeparator.cs" />
+ <Compile Include="System.Windows.Forms\ToolStripSeparator.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\ToolStripSeparatorRenderEventArgs.cs" />
<Compile Include="System.Windows.Forms\ToolStripSeparatorRenderEventHandler.cs" />
- <Compile Include="System.Windows.Forms\ToolStripSplitButton.cs" />
+ <Compile Include="System.Windows.Forms\ToolStripSplitButton.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\ToolStripSplitStackLayout.cs" />
- <Compile Include="System.Windows.Forms\ToolStripStatusLabel.cs" />
+ <Compile Include="System.Windows.Forms\ToolStripStatusLabel.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\ToolStripStatusLabelBorderSides.cs" />
<Compile Include="System.Windows.Forms\ToolStripSystemRenderer.cs" />
- <Compile Include="System.Windows.Forms\ToolStripTextBox.cs" />
+ <Compile Include="System.Windows.Forms\ToolStripTextBox.cs">
+ </Compile>
<Compile Include="System.Windows.Forms\ToolStripTextDirection.cs" />
- <Compile Include="System.Windows.Forms\ToolTip.cs" />
+ <Compile Include="System.Windows.Forms\ToolTip.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\ToolTipIcon.cs" />
<Compile Include="System.Windows.Forms\ToolWindowManager.cs" />
- <Compile Include="System.Windows.Forms\TrackBar.cs" />
+ <Compile Include="System.Windows.Forms\TrackBar.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\TrackBarRenderer.cs" />
<Compile Include="System.Windows.Forms\TreeNode.cs" />
<Compile Include="System.Windows.Forms\TreeNodeCollection.cs" />
<Compile Include="System.Windows.Forms\TreeNodeMouseHoverEventArgs.cs" />
<Compile Include="System.Windows.Forms\TreeNodeMouseHoverEventHandler.cs" />
<Compile Include="System.Windows.Forms\TreeNodeStates.cs" />
- <Compile Include="System.Windows.Forms\TreeView.cs" />
+ <Compile Include="System.Windows.Forms\TreeView.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\TreeViewAction.cs" />
<Compile Include="System.Windows.Forms\TreeViewCancelEventArgs.cs" />
<Compile Include="System.Windows.Forms\TreeViewCancelEventHandler.cs" />
<Compile Include="System.Windows.Forms\UICuesEventArgs.cs" />
<Compile Include="System.Windows.Forms\UICuesEventHandler.cs" />
<Compile Include="System.Windows.Forms\UnhandledExceptionMode.cs" />
- <Compile Include="System.Windows.Forms\UpDownBase.cs" />
+ <Compile Include="System.Windows.Forms\UpDownBase.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\UpDownEventArgs.cs" />
<Compile Include="System.Windows.Forms\UpDownEventHandler.cs" />
- <Compile Include="System.Windows.Forms\UserControl.cs" />
- <Compile Include="System.Windows.Forms\VScrollBar.cs" />
+ <Compile Include="System.Windows.Forms\UserControl.cs">
+ <SubType>Component</SubType>
+ </Compile>
+ <Compile Include="System.Windows.Forms\VScrollBar.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\ValidationConstraints.cs" />
<Compile Include="System.Windows.Forms\View.cs" />
<Compile Include="System.Windows.Forms\VScrollProperties.cs" />
- <Compile Include="System.Windows.Forms\WebBrowser.cs" />
- <Compile Include="System.Windows.Forms\WebBrowserBase.cs" />
+ <Compile Include="System.Windows.Forms\WebBrowser.cs">
+ </Compile>
+ <Compile Include="System.Windows.Forms\WebBrowserBase.cs">
+ <SubType>Component</SubType>
+ </Compile>
<Compile Include="System.Windows.Forms\WebBrowserDocumentCompletedEventArgs.cs" />
<Compile Include="System.Windows.Forms\WebBrowserDocumentCompletedEventHandler.cs" />
<Compile Include="System.Windows.Forms\WebBrowserEncryptionLevel.cs" />
<Compile Include="System.Windows.Forms.Theming\ThemeElementsNice.cs" />
<Compile Include="System.Windows.Forms.Theming\Default\ButtonPainter.cs" />
<Compile Include="System.Windows.Forms.Theming\Default\CheckBoxPainter.cs" />
+ <Compile Include="System.Windows.Forms.Theming\Default\RadioButtonPainter.cs" />
<Compile Include="System.Windows.Forms.Theming\Default\TabControlPainter.cs" />
<Compile Include="System.Windows.Forms.Theming\Default\ToolStripPainter.cs" />
<Compile Include="System.Windows.Forms.Theming\Nice\TabControlPainter.cs" />
<Compile Include="System.Windows.Forms.VisualStyles\VisualStyleInformation.cs" />
<Compile Include="System.Windows.Forms.VisualStyles\VisualStyleRenderer.cs" />
<Compile Include="System.Windows.Forms.VisualStyles\VisualStyleState.cs" />
+ <Compile Include="System.Windows.Forms.WebBrowserDialogs\AlertCheck.cs">
+ </Compile>
+ <Compile Include="System.Windows.Forms.WebBrowserDialogs\ConfirmCheck.cs">
+ </Compile>
+ <Compile Include="System.Windows.Forms.WebBrowserDialogs\Generic.cs">
+ </Compile>
+ <Compile Include="System.Windows.Forms.WebBrowserDialogs\Prompt.cs">
+ </Compile>
<Compile Include="System.Windows.Forms.X11Internal\X11Atoms.cs" />
<Compile Include="System.Windows.Forms.X11Internal\X11Display.cs" />
<Compile Include="System.Windows.Forms.X11Internal\X11Exception.cs" />
</PreBuildEvent>
<PostBuildEvent>
</PostBuildEvent>
- <ProjectGuid>{5E6430B2-6B9F-4E76-802E-20207EF80391}</ProjectGuid>
</PropertyGroup>
</Project>
+2007-10-16 Jonathan Pobst <monkey@jpobst.com>
+
+ * TableLayout.cs: Revert the last change to TableLayout. It breaks
+ other, more important things.
+
+2007-10-15 Jonathan Pobst <monkey@jpobst.com>
+
+ * TableLayout.cs: If a control has an explicitly set col/row greater
+ than the number of columns/rows in the panel, expand the table to
+ accommodate the control. [Fixes bug #332892]
+
2007-10-11 Jonathan Pobst <monkey@jpobst.com>
* TableLayout.cs: When calculating the size of AutoSize row/columns,
get { return is_default; }
set {
if (is_default != value) {
- is_default = true;
+ is_default = value;
Invalidate ();
}
}
+2007-10-22 Everaldo Canuto <ecanuto@novell.com>
+
+ * MdiClient.cs: Maximize new active mdi child when a maximized child is
+ closed see #325434 patch.
+
+2007-10-22 Everaldo Canuto <ecanuto@novell.com>
+
+ * MdiClient.cs: Fix remaining issues from layout vertical and horizontal,
+ see #325434 patch.
+
+2007-10-21 Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+ * PropertyGridView.cs: When showing the textbox for a grid item,
+ have two local variables to store the read-only and non-editable
+ status of a grid item (we were previously using just one variable
+ to do this, when actually they are slightly different).
+ Fixes part of #325023.
+
+2007-10-21 Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+ * PropertyGridView.cs: When showing a drop-down list, try to get the
+ values using TypeConverter.ConvertTo (to convert to a string). Fixes
+ part of #325023.
+
+2007-10-19 Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+ * PropertyGrid.cs: When updating a property and populating sub grid
+ items, remove the previous ones, and invalidate the specific area.
+ * PropertyGridView.cs: A new InvalidateBelowGridItem to invalidate the
+ area behind a grid item.
+ * GridItemCollection.cs: Add an internal Clear method, to allow us to
+ clean the items if needed (specially for controls implementing
+ ICustomTypeDescriptor and returning a variable number of properties).
+ Fixes #324865.
+
+2007-10-19 Jonathan Pobst <monkey@jpobst.com>
+
+ * TextControl.cs: Clean up and document the Insert function.
+
+2007-10-17 Jonathan Pobst <monkey@jpobst.com>
+
+ * TextControl.cs: Make sure we know our start point for updating the view
+ in ReplaceSelection. Fixes an issue where pasting multiline text wouldn't
+ update the view.
+
+2007-10-17 Jonathan Pobst <monkey@jpobst.com>
+
+ * ListView: Couple of corcompare fixes.
+
+2007-10-17 Geoff Norton <gnorton@novell.com>
+
+ * XplatUIOSX.cs: Implement support for window icons in the dock. Set
+ the title caption of real window.
+
+2007-10-17 Jonathan Pobst <monkey@jpobst.com>
+
+ * ErrorProvider.cs: Add the error provider's internal window to a
+ containercontrol when the parent changes. [Fixes bug #329714]
+
+2007-10-17 Geoff Norton <gnorton@novell.com>
+
+ * XplatUIOSX.cs: Implement ScrollWindow. Properly create TOOLWINDOWs.
+ When we make a new window; restore the old active window - fixes dialogs.
+
+2007-10-17 Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+ * PropertyGridView.cs: Look for RefreshPropertiesAttribute
+ when modifying a property, and if found then invalidate as
+ requested.
+ Fixes part of #324865.
+
+2007-10-17 Geoff Norton <gnorton@novell.com>
+
+ * XplatUIOSX.cs: Re-enable the native driver on the Mac. This is still
+ highly experimental. Fixed coordinate translation. Fixed window locations.
+ Initial support for clipping. Implemented NC areas and menus. Support for
+ launching from command line from Will Johansson (wjohansson@atacomm.com).
+ * OSXStructs.cs: Add ProcessSerialNumer (Patch from Will Johansson
+ wjohansson@atacomm.com)
+ * Hwnd.cs: Add some internal structures for tracking Mac cursors.
+ Hwnds now track the existence of all of their children for Mac clipping.
+ * XplatUI.cs: Re-enabled the native driver on the Mac.
+
+2007-10-17 Jonathan Pobst <monkey@jpobst.com>
+
+ * Line.cs: Move the InsertString function to here.
+ * TextControl.cs: Cleanup some duplicate code, move some InsertString
+ functionality to Line.
+
+2007-10-17 Geoff Norton <gnorton@novell.com>
+
+ * ComboBox.cs: Destroy the popup after hiding it. Fixes #322582
+
+2007-10-16 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * ButtonBase.cs: Fixed IsDefault to use assigned value instead of
+ always setting value to true.
+ * Form.cs: When changing AcceptButton, notify new and original button.
+
+2007-10-16 Jonathan Pobst <monkey@jpobst.com>
+
+ * Form.cs: Guard against an NRE when the user sets the AcceptButton to
+ a custom control that implements IButtonControl instead of an actual
+ button. [Fixes bug #334244]
+
+2007-10-15 Everaldo Canuto <ecanuto@novell.com>
+
+ * Form.cs: Change SelectActiveControl to internal, we need to call it in
+ MdiWindowManager.
+
+ * MdiWindowManager.cs: In RaiseActivated call SelectActiveControl to select
+ active control when activate a new mdi window.
+
+ [Fixes bug #330495]
+
+2007-10-15 Everaldo Canuto <ecanuto@novell.com>
+
+ * ComboBox.cs: Dont implicit add listbox_ctrl on OnHandleCreated because it
+ is already added.
+ [Fixes bug #333617]
+
+2007-10-15 Jonathan Pobst <monkey@jpobst.com>
+
+ * TextControl.cs: When SuspendRecalc is first called, reset the recalc_start
+ to MaxValue and recalc_end to MinValue. Currently, recalc_start is always 1,
+ so we always recalculate the whole document instead of just the new part.
+ [Fixes bug #325082]
+
+2007-10-15 Jonathan Pobst <monkey@jpobst.com>
+
+ * LineTag.cs: Fix a case where the GetCharIndex would not return 0
+ when the mouse was to the left of the first character in the line.
+
+2007-10-15 Jonathan Pobst <monkey@jpobst.com>
+
+ * TextBox.cs, TextBoxBase.cs: When setting the document's password
+ character, use the property instead of the variable so that the
+ UseSystemPasswordChar property is taken into account.
+ [Fixes bug #333748]
+
+2007-10-13 Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+ * FolderBrowserDialog.cs: When a node is right clicked and the "New
+ folder" contex menu appears, actually add the new folder to it, even
+ if the node is not currently selected. Still use SelectedNode in case
+ there wasn't found a node under the pointer.
+ Fixes #325452.
+
+2007-10-13 Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+ * ListViewItem.cs: When retrieving the focused state, the index check
+ should be done only when ListView is in virtualmode, as it is an
+ expensive check for normal mode.
+
+2007-10-13 Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+ * ListViewItem.cs: Make the focus state information be stored
+ in the ListView, not in the items. This is done to match the MS
+ behaviour for items that are not yet part of a ListView control;
+ besides that, since just one item can be focused at the same time,
+ we save a little space in our items.
+ Fixes part of #331643.
+
2007-10-13 Gert Driesen <drieseng@users.sourceforge.net>
* ComboBox.cs: When focus is lost, deselect the text. When setting
{
base.OnHandleCreated (e);
- if (listbox_ctrl != null) {
- Controls.AddImplicit (listbox_ctrl);
- listbox_ctrl.Visible = true;
- }
-
if (textbox_ctrl != null)
Controls.AddImplicit (textbox_ctrl);
#if NET_2_0
OnDropDownClosed (EventArgs.Empty);
#endif
+ /*
+ * Apples X11 looses override-redirect when doing a Unmap/Map on a previously mapped window
+ * this causes the popup to appear under the main form. This is horrible but necessary
+ */
+ listbox_ctrl.Dispose ();
+ listbox_ctrl = null;
}
private int FindStringCaseInsensitive (string search)
private void control_ParentChanged (object sender, EventArgs e)
{
- if (ep.container != null)
- return;
- control.Parent.Controls.Add (window);
- control.Parent.Controls.SetChildIndex (window, 0);
+ if (ep.container != null) {
+ ep.container.Controls.Add (window);
+ ep.container.Controls.SetChildIndex (window, 0);
+ } else {
+ control.Parent.Controls.Add (window);
+ control.Parent.Controls.SetChildIndex (window, 0);
+ }
}
private void window_Tick(object sender, EventArgs e) {
private ImageList imageList = new ImageList ();
private Environment.SpecialFolder rootFolder;
private bool dont_enable = false;
+ private TreeNode node_under_mouse;
public FolderBrowserTreeView (FolderBrowserDialog parent_dialog)
{
public void CreateNewFolder ()
{
- FBTreeNode fbnode = SelectedNode as FBTreeNode;
+ FBTreeNode fbnode = node_under_mouse == null ? SelectedNode as FBTreeNode : node_under_mouse as FBTreeNode;
if (fbnode == null || fbnode.RealPath == null)
return;
}
}
- // select new folder
- SelectedNode = e.Node;
+ // select new folder only if both the curren node under
+ // mouse pointer and SelectedNode are the same (match .Net)
+ if (node_under_mouse == SelectedNode)
+ SelectedNode = e.Node;
// disable LabelEdit when either edit has finished
// or has been cancelled, to prevent the user from
base.OnBeforeExpand (e);
}
+
+ protected override void OnMouseDown (MouseEventArgs e)
+ {
+ node_under_mouse = GetNodeAt (e.X, e.Y);
+ base.OnMouseDown (e);
+ }
protected override void OnMouseUp (MouseEventArgs e)
{
parentDialog.newFolderButton.Enabled = true;
parentDialog.newFolderMenuItem.Enabled = true;
}
+
+ node_under_mouse = null;
base.OnMouseUp (e);
}
XplatUI.Text (Handle, Text.Replace (Environment.NewLine, string.Empty));
}
- private void SelectActiveControl ()
+ internal void SelectActiveControl ()
{
if (this.IsMdiContainer) {
mdi_container.SendFocusToActiveChild ();
}
set {
+ if (accept_button != null)
+ accept_button.NotifyDefault (false);
+
accept_button = value;
- CheckAcceptButton();
+ if (accept_button != null)
+ accept_button.NotifyDefault (true);
+
+ CheckAcceptButton ();
}
}
window_manager = null;
}
- internal override void CheckAcceptButton()
+ internal override void CheckAcceptButton ()
{
if (accept_button != null) {
Button a_button = accept_button as Button;
-
+
if (ActiveControl == a_button)
return;
- if (ActiveControl is Button) {
- a_button.paint_as_acceptbutton = false;
- a_button.Invalidate();
+ // If the accept_button isn't a Button, we don't need to do
+ // the rest of this.
+ if (a_button == null)
return;
- } else {
+
+ if (ActiveControl is Button)
+ a_button.paint_as_acceptbutton = false;
+ else
a_button.paint_as_acceptbutton = true;
- a_button.Invalidate();
- }
+
+ a_button.Invalidate ();
}
}
using System;
using System.Collections;
+using System.Windows.Forms.PropertyGridInternal;
namespace System.Windows.Forms
{
}
#endregion
+
+ internal void Clear ()
+ {
+ for (int i = 0; i < list.Count; i++) {
+ GridEntry grid_entry = list.GetByIndex (i) as GridEntry;
+ if (grid_entry == null || grid_entry.Parent == null)
+ continue;
+
+ grid_entry.SetParent (null);
+ }
+
+ list.Clear ();
+ }
}
}
private IntPtr handle;
internal IntPtr client_window;
internal IntPtr whole_window;
+ internal IntPtr client_cursor;
+ internal IntPtr whole_cursor;
internal Menu menu;
internal TitleStyle title_style;
internal FormBorderStyle border_style;
internal FormWindowState cached_window_state = (FormWindowState)(-1); /* X11 only field */
internal Point previous_child_startup_location = new Point (int.MinValue, int.MinValue);
static internal Point previous_main_startup_location = new Point (int.MinValue, int.MinValue);
+ internal ArrayList children;
#endregion // Local Variables
// locks for some operations (used in XplatUIX11.cs)
opacity = 0xffffffff;
fixed_size = false;
drawing_stack = new Stack ();
+ children = new ArrayList ();
}
public void Dispose() {
expose_pending = false;
nc_expose_pending = false;
+ Parent = null;
lock (windows) {
windows.Remove(client_window);
windows.Remove(whole_window);
}
}
+ public IntPtr ClientCursor {
+ get {
+ return client_cursor;
+ }
+
+ set {
+ client_cursor = value;
+ }
+ }
+
public IntPtr ClientWindow {
get {
return client_window;
}
set {
+ if (parent != null)
+ parent.children.Remove (this);
parent = value;
+ if (parent != null)
+ parent.children.Add (this);
}
}
}
}
+ public IntPtr WholeCursor {
+ get {
+ return whole_cursor;
+ }
+
+ set {
+ whole_cursor = value;
+ }
+ }
+
public IntPtr WholeWindow {
get {
return whole_window;
}\r
}\r
\r
+ // Inserts a string at the given position\r
+ public void InsertString (int pos, string s)\r
+ {\r
+ LineTag tag = FindTag (pos);\r
+ int len = s.Length;\r
+\r
+ // Insert the text into the StringBuilder\r
+ text.Insert (pos, s);\r
+\r
+ // Update the start position of every tag after this one\r
+ tag = tag.Next;\r
+\r
+ while (tag != null) {\r
+ tag.Start += len;\r
+ tag = tag.Next;\r
+ }\r
+\r
+ // Make sure we have room in the widths array\r
+ Grow (len);\r
+\r
+ // This line needs to be recalculated\r
+ recalc = true;\r
+ }\r
+\r
/// <summary>\r
/// Go through all tags on a line and recalculate all size-related values;\r
/// returns true if lineheight changed\r
if (Length == 0)\r
return start;\r
\r
+ if (x < line.widths[low])\r
+ return low - 1;\r
+ \r
if (x > line.widths[line.TextLengthWithoutEnding ()])\r
return line.TextWithoutEnding ().Length;\r
\r
private Size tile_size;
private bool virtual_mode;
private int virtual_list_size;
+ private bool right_to_left_layout;
#endif
// internal variables
static object ItemSelectionChangedEvent = new object ();
static object CacheVirtualItemsEvent = new object ();
static object RetrieveVirtualItemEvent = new object ();
+ static object RightToLeftLayoutChangedEvent = new object ();
static object VirtualItemsSelectionRangeChangedEvent = new object ();
#endif
remove { Events.RemoveHandler (RetrieveVirtualItemEvent, value); }
}
+ public event EventHandler RightToLeftLayoutChanged {
+ add { Events.AddHandler (RightToLeftLayoutChangedEvent, value); }
+ remove { Events.RemoveHandler (RightToLeftLayoutChangedEvent, value); }
+ }
+
public event ListViewVirtualItemsSelectionRangeChangedEventHandler VirtualItemsSelectionRangeChanged {
add { Events.AddHandler (VirtualItemsSelectionRangeChangedEvent, value); }
remove { Events.RemoveHandler (VirtualItemsSelectionRangeChangedEvent, value); }
base.Padding = value;
}
}
+
+ [MonoTODO ("RTL not supported")]
+ [Localizable (true)]
+ [DefaultValue (false)]
+ public virtual bool RightToLeftLayout {
+ get { return right_to_left_layout; }
+ set {
+ if (right_to_left_layout != value) {
+ right_to_left_layout = value;
+ OnRightToLeftLayoutChanged (EventArgs.Empty);
+ }
+ }
+ }
#endif
[DefaultValue (true)]
if (eh != null)
eh(this, e);
}
-#endif
+#else
protected override void OnEnabledChanged (EventArgs e)
{
base.OnEnabledChanged (e);
}
+#endif
protected override void OnFontChanged (EventArgs e)
{
eh (this, args);
}
+ [EditorBrowsable (EditorBrowsableState.Advanced)]
+ protected virtual void OnRightToLeftLayoutChanged (EventArgs e)
+ {
+ EventHandler eh = (EventHandler)Events[RightToLeftLayoutChangedEvent];
+ if (eh != null)
+ eh (this, e);
+ }
+
protected virtual void OnVirtualItemsSelectionRangeChanged (ListViewVirtualItemsSelectionRangeChangedEventArgs args)
{
ListViewVirtualItemsSelectionRangeChangedEventHandler eh =
#region Instance Variables
private int image_index = -1;
private bool is_checked = false;
- private bool is_focused = false;
private int state_image_index = -1;
private ListViewSubItemCollection sub_items;
private object tag;
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public bool Focused {
get {
+ if (owner == null)
+ return false;
+
#if NET_2_0
- // As well as selection state in VirtualMode,
- // focus state is stored in the ListView
- if (owner != null && owner.VirtualMode)
+ // In virtual mode the checks are always done using indexes
+ if (owner.VirtualMode)
return Index == owner.focused_item_index;
#endif
- return is_focused;
+
+ // Light check
+ return owner.FocusedItem == this;
+
}
set {
- if (is_focused == value)
+ if (owner == null)
return;
- if (owner != null) {
- if (owner.FocusedItem != null)
- owner.FocusedItem.UpdateFocusedState (false);
+ if (Focused == value)
+ return;
- owner.focused_item_index = value ? Index : -1;
- }
+ ListViewItem prev_focused_item = owner.FocusedItem;
+ if (prev_focused_item != null)
+ prev_focused_item.UpdateFocusedState ();
+
+ owner.focused_item_index = value ? Index : -1;
- UpdateFocusedState (value);
+ UpdateFocusedState ();
}
}
ListViewItem clone = new ListViewItem ();
clone.image_index = this.image_index;
clone.is_checked = this.is_checked;
- clone.is_focused = this.is_focused;
clone.selected = this.selected;
clone.font = this.font;
clone.state_image_index = this.state_image_index;
}
#endif
- void UpdateFocusedState (bool is_focused)
+ // When focus changed, we need to invalidate area
+ // with previous layout and with the new one
+ void UpdateFocusedState ()
{
- this.is_focused = is_focused;
if (owner != null) {
Invalidate ();
Layout ();
case MdiLayout.TileVertical: {
// First count number of windows to tile
int total = 0;
+
+ // And space used by iconic windows
+ int clientHeight = ClientSize.Height;
+
for (int i = 0; i < Controls.Count; i++) {
Form form = Controls [i] as Form;
if (!form.Visible)
continue;
-
- if (form.WindowState == FormWindowState.Minimized)
+
+ if (form.WindowState == FormWindowState.Maximized)
+ form.WindowState = FormWindowState.Normal;
+ else if (form.WindowState == FormWindowState.Minimized) {
+ if (form.Bounds.Top < clientHeight)
+ clientHeight = form.Bounds.Top;
continue;
+ }
total++;
}
// Calculate desired height and width
Size newSize;
Size offset;
+
if (value == MdiLayout.TileHorizontal) {
- newSize = new Size (ClientSize.Width, ClientSize.Height / total);
+ newSize = new Size(ClientSize.Width, clientHeight / total);
offset = new Size (0, newSize.Height);
} else {
- newSize = new Size (ClientSize.Width / total, ClientSize.Height);
+ newSize = new Size(ClientSize.Width / total, clientHeight);
offset = new Size (newSize.Width, 0);
}
internal void ChildFormClosed (Form form)
{
- if (Controls.Count > 1) {
- Form next = (Form) Controls [1];
- if (form.WindowState == FormWindowState.Maximized)
- next.WindowState = FormWindowState.Maximized;
- ActivateChild (next);
- }
+ FormWindowState closed_form_windowstate = form.WindowState;
form.Visible = false;
Controls.Remove (form);
if (Controls.Count == 0) {
((MdiWindowManager) form.window_manager).RaiseDeactivate ();
+ } else if (closed_form_windowstate == FormWindowState.Maximized) {
+ Form current = (Form) Controls [0];
+ current.WindowState = FormWindowState.Maximized;
+ ActivateChild(current);
}
if (Controls.Count == 0) {
last_activation_event = 1;
form.OnActivatedInternal ();
+ form.SelectActiveControl ();
}
public void RaiseDeactivate ()
}
}
+ internal struct ProcessSerialNumber
+ {
+ public ulong highLongOfPSN;
+ public ulong lowLongOfPSN;
+ }
}
if (parent_grid_item == null)
return;
+ /* Clear any previous grid items */
+ if (parent_grid_item.GridItems.Count > 0) {
+ parent_grid_item.GridItems.Clear ();
+ property_grid_view.InvalidateBelowItem (parent_grid_item);
+ }
+
for (int i = 0; i < objs.Length; i ++) {
if (objs [i] == null)
continue;
Invalidate (new Rectangle (0, item.Top, SplitterLocation, row_height));
}
+ internal void InvalidateBelowItem (GridItem item)
+ {
+ Rectangle rect = new Rectangle (0, item.Top, Width, row_height);
+ Invalidate (rect);
+
+ if (item.Expanded) {
+ rect = new Rectangle (0, item.Top + row_height, Width,
+ Height - (item.Top + row_height));
+ Invalidate (rect);
+ }
+ }
+
#if !DOUBLEBUFFER
- void InvalidateGridItem (GridItem item)
+ internal void InvalidateGridItem (GridItem item)
{
Invalidate (new Rectangle (0, item.Top, Width, row_height));
}
}
}
- void AcceptListBoxSelection (object sender) {
+ // FIXME: Instead of let an exception being thrown, as we have always done,
+ // show a dialog message mentioning the issue, as MS does
+ void AcceptListBoxSelection (object sender)
+ {
if (this.property_grid.SelectedGridItem != null) {
PropertyDescriptor desc = property_grid.SelectedGridItem.PropertyDescriptor;
if (desc != null) {
- SetPropertyValue(((ListBox)sender).SelectedItem);
+ string obj_string = (string) ((ListBox) sender).SelectedItem;
+ TypeConverter converter = property_grid.SelectedGridItem.PropertyDescriptor.Converter;
+
+ // This is what MS does: call ConvertTo () for a string
+ object new_value = converter.ConvertFrom (obj_string);
+ SetPropertyValue (new_value);
}
}
CloseDropDown ();
desc.SetValue(target, newVal);
}
+ // TODO - What else should RefreshProperties.All do?
+ RefreshPropertiesAttribute refresh_attr = (RefreshPropertiesAttribute) desc.Attributes [typeof (RefreshPropertiesAttribute)];
+ if (refresh_attr != null && refresh_attr.RefreshProperties != RefreshProperties.None)
+ Invalidate ();
+
property_grid.PropertyValueChangedInternal ();
}
-
+
private void DropDownButtonClicked (object sender, EventArgs e) {
UITypeEditor editor = property_grid.SelectedGridItem.PropertyDescriptor.GetEditor (typeof (UITypeEditor)) as UITypeEditor;
if (editor == null) {
int i = 0;
object selected_value = property_grid.SelectedGridItem.Value;
foreach (object obj in std_values) {
- listBox.Items.Add(obj);
+
+ string obj_str;
+ if (converter.CanConvertTo (typeof (string)))
+ obj_str = (string) converter.ConvertTo (obj, typeof (string));
+ else
+ obj_str = obj.ToString ();
+
+ listBox.Items.Add (obj_str);
if (selected_value != null && selected_value.Equals(obj))
selected_index = i;
i++;
else
grid_textbox.Font = this.Font;
- grid_textbox.ReadOnly = false;
+ bool is_read_only;
+ bool is_non_editable = false; // Can be modifiable, but not directly editable
+
grid_textbox.DropDownButtonVisible = false;
grid_textbox.DialogButtonVisible = false;
if (forItem.PropertyDescriptor.Converter.GetStandardValuesSupported()) {
grid_textbox.DropDownButtonVisible = true;
- grid_textbox.ReadOnly = true;
+ is_non_editable = true;
}
}
else {
}
}
- grid_textbox.ReadOnly = grid_textbox.ReadOnly || forItem.PropertyDescriptor.IsReadOnly;
- grid_textbox.ForeColor = grid_textbox.ReadOnly ? SystemColors.InactiveCaption : SystemColors.WindowText;
+ is_read_only = forItem.PropertyDescriptor.IsReadOnly;
+ is_non_editable = is_non_editable || forItem.PropertyDescriptor.IsReadOnly;
+ grid_textbox.ReadOnly = is_non_editable;
+ grid_textbox.ForeColor = is_read_only ? SystemColors.InactiveCaption : SystemColors.WindowText;
int xloc = SplitterLocation + 1 + (paintsValue ? 27 : 0);
grid_textbox.SetBounds (xloc,
}
set {
- use_system_password_char = value;
+ if (use_system_password_char != value) {
+ use_system_password_char = value;
+
+ if (!Multiline)
+ document.PasswordChar = PasswordChar.ToString ();
+ else
+ document.PasswordChar = "";
+ }
}
}
#endif
if (value != password_char) {
password_char = value;
if (!Multiline) {
- document.PasswordChar = value.ToString();
+ document.PasswordChar = PasswordChar.ToString ();
} else {
document.PasswordChar = "";
}
} else {
document.Wrap = false;
if (this.password_char != '\0') {
- document.PasswordChar = password_char.ToString();
+ if (this is TextBox)
+ document.PasswordChar = (this as TextBox).PasswordChar.ToString ();
} else {
document.PasswordChar = "";
}
internal void SuspendRecalc ()
{
+ if (recalc_suspended == 0) {
+ recalc_start = int.MaxValue;
+ recalc_end = int.MinValue;
+ }
+
recalc_suspended++;
}
LineTag tag;
int index;
- tag = FindTag(0, viewport_y + viewport_height, out index, false);
+ tag = FindCursor (0, viewport_y + viewport_height, out index);
if (tag.Line.line_no > 1) {
line = GetLine(tag.Line.line_no - 1);
} else {
return res;
}
-
- // Insert multi-line text at the given position; use formatting at insertion point for inserted text
- internal void Insert(Line line, int pos, bool update_caret, string s) {
+ // Insert text at the given position; use formatting at insertion point for inserted text
+ internal void Insert (Line line, int pos, bool update_caret, string s)
+ {
int break_index;
int base_line;
int old_line_count;
int count = 1;
LineEnding ending;
- LineTag tag = LineTag.FindTag (line, pos);
+ Line split_line;
+ // Find the LineTag to add to
+ LineTag tag = line.FindTag (pos);
+
+ // Don't recalculate while we mess around
SuspendRecalc ();
base_line = line.line_no;
break_index = GetLineEnding (s, 0, out ending);
- // Bump the text at insertion point a line down if we're inserting more than one line
- if (break_index != s.Length) {
- Split (line, pos);
+ // There are no line feeds in our text to be pasted
+ if (break_index == s.Length) {
+ line.InsertString (pos, s);
+ } else {
+ // Add up to the first line feed to our current position
+ line.InsertString (pos, s.Substring (0, break_index + LineEndingLength (ending)));
+
+ // Split the rest of the original line to a new line
+ Split (line, pos + (break_index + LineEndingLength (ending)));
line.ending = ending;
- // Remainder of start line is now in base_line + 1
- }
+ break_index += LineEndingLength (ending);
+ split_line = GetLine (line.line_no + 1);
+
+ // Insert brand new lines for any more line feeds in the inserted string
+ while (true) {
+ int next_break = GetLineEnding (s, break_index, out ending);
+
+ if (next_break == s.Length)
+ break;
+
+ string line_text = s.Substring (break_index, next_break - break_index +
+ LineEndingLength (ending));
- InsertString (line, pos, s.Substring (0, break_index + LineEndingLength (ending)));
-
- break_index += LineEndingLength (ending);
- while (break_index < s.Length) {
- int next_break = GetLineEnding (s, break_index, out ending);
- string line_text = s.Substring (break_index, next_break - break_index +
- LineEndingLength (ending));
+ Add (base_line + count, line_text, line.alignment, tag.Font, tag.Color, ending);
- Add (base_line + count, line_text, line.alignment, tag.Font, tag.Color, ending);
+ Line last = GetLine (base_line + count);
+ last.ending = ending;
- Line last = GetLine (base_line + count);
- last.ending = ending;
+ count++;
+ break_index = next_break + LineEndingLength (ending);
+ }
- count++;
- break_index = next_break + LineEndingLength (ending);
+ // Add the remainder of the insert text to the split
+ // part of the original line
+ split_line.InsertString (0, s.Substring (break_index));
}
+
+ // Allow the document to recalculate things
+ ResumeRecalc (false);
- ResumeRecalc (true);
-
- UpdateView(line, lines - old_line_count + 1, pos);
+ UpdateView (line, lines - old_line_count + 1, pos);
+ // Move the caret to the end of the inserted text if requested
if (update_caret) {
- // Move caret to the end of the inserted text
Line l = GetLine (line.line_no + lines - old_line_count);
- PositionCaret(l, l.text.Length);
+ PositionCaret (l, l.text.Length);
DisplayCaret ();
}
}
- // Inserts a character at the given position
- internal void InsertString(Line line, int pos, string s) {
- InsertString(line.FindTag(pos), pos, s);
- }
-
// Inserts a string at the given position
- internal void InsertString(LineTag tag, int pos, string s) {
- Line line;
- int len;
-
- len = s.Length;
-
- CharCount += len;
-
- line = tag.Line;
- line.text.Insert(pos, s);
-
- tag = tag.Next;
- while (tag != null) {
- tag.Start += len;
- tag = tag.Next;
- }
- line.Grow(len);
- line.recalc = true;
-
- UpdateView(line, pos);
- }
-
- // Inserts a string at the caret position
- internal void InsertStringAtCaret(string s, bool move_caret) {
-
- InsertString (caret.tag, caret.pos, s);
-
- UpdateView(caret.line, caret.pos);
- if (move_caret) {
- caret.pos += s.Length;
- UpdateCaret();
- }
- }
-
-
+ internal void InsertString (Line line, int pos, string s)
+ {
+ // Update our character count
+ CharCount += s.Length;
- // Inserts a character at the given position
- internal void InsertChar(Line line, int pos, char ch) {
- InsertChar(line.FindTag(pos), pos, ch);
+ // Insert the text into the Line
+ line.InsertString (pos, s);
}
// Inserts a character at the given position
undo.RecordInsertString (selection_start.line, selection_start.pos, s);
ResumeRecalc (false);
+ Line begin_update_line = selection_start.line;
+ int begin_update_pos = selection_start.pos;
+
if (!select_new) {
CharIndexToLineTag(selection_start_pos + s.Length, out selection_start.line,
out selection_start.tag, out selection_start.pos);
}
PositionCaret (selection_start.line, selection_start.pos);
- UpdateView (selection_start.line, selection_pos_on_line);
+ UpdateView (begin_update_line, selection_end.line.line_no - begin_update_line.line_no, begin_update_pos);
}
internal void CharIndexToLineTag(int index, out Line line_out, out LineTag tag_out, out int pos) {
return last;
}
- // Give it x/y pixel coordinates and it returns the Tag at that position; optionally the char position is returned in index
- internal LineTag FindTag(int x, int y, out int index, bool exact) {
- Line line;
- LineTag tag;
-
- line = GetLineByPixel(y, exact);
- if (line == null) {
- index = 0;
- return null;
- }
- tag = line.tags;
-
- // Alignment adjustment
- x += line.X;
-
- while (true) {
- if (x >= tag.X && x < (tag.X+tag.Width)) {
- int end;
-
- end = tag.Start + tag.Length - 1;
-
- for (int pos = tag.Start; pos < end; pos++) {
- if (x < line.widths[pos]) {
- index = pos;
- return LineTag.GetFinalTag (tag);
- }
- }
- index=end;
- return LineTag.GetFinalTag (tag);
- }
- if (tag.Next != null) {
- tag = tag.Next;
- } else {
- if (exact) {
- index = 0;
- return null;
- }
-
- index = line.text.Length;
- return LineTag.GetFinalTag (tag);
- }
- }
- }
-
- // Give it x/y pixel coordinates and it returns the Tag at that position; optionally the char position is returned in index
+ // Give it x/y pixel coordinates and it returns the Tag at that position
internal LineTag FindCursor (int x, int y, out int index)
{
Line line;
line = GetLineByPixel (multiline ? y : x, false);
LineTag tag = line.GetTag (x);
-
+
if (tag.Length == 0)
index = 0;
else
default_class_name = "SWFClass" + System.Threading.Thread.GetDomainID().ToString();
if (RunningOnUnix) {
- if (Environment.GetEnvironmentVariable ("not_supported_MONO_MWF_USE_QUARTZ_BACKEND") != null)
+ if (Environment.GetEnvironmentVariable ("MONO_MWF_USE_QUARTZ_BACKEND") != null)
driver=XplatUIOSX.GetInstance ();
else if (Environment.GetEnvironmentVariable ("not_supported_MONO_MWF_USE_NEW_X11_BACKEND") != null)
driver=XplatUIX11_new.GetInstance ();
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
-// Copyright (c) 2004-2006 Novell, Inc.
+// Copyright (c) 2004-2007 Novell, Inc.
//
// Authors:
-// Geoff Norton <gnorton@customerdna.com>
+// Geoff Norton <gnorton@novell.com>
//
//
// This really doesn't work at all; please dont file bugs on it yet.
// MAJOR TODO:
-// Fix clipping of children
// Wire up keyboard
+#define EnableNCArea
+
using System;
using System.Threading;
using System.Drawing;
private static int RefCount;
private static bool themes_enabled;
private static IntPtr FocusWindow;
+ private static IntPtr ActiveWindow;
// Mouse
private static MouseButtons MouseState;
private static IntPtr FosterParent;
private static int TitleBarHeight;
private static int MenuBarHeight;
- private static EventTypeSpec [] viewEvents = new EventTypeSpec [] {
+ private static EventTypeSpec [] view_events = new EventTypeSpec [] {
new EventTypeSpec (OSXConstants.kEventClassControl, OSXConstants.kEventControlSetFocusPart),
new EventTypeSpec (OSXConstants.kEventClassControl, OSXConstants.kEventControlClick),
new EventTypeSpec (OSXConstants.kEventClassControl, OSXConstants.kEventControlContextualMenuClick),
new EventTypeSpec (OSXConstants.kEventClassControl, OSXConstants.kEventControlTrack),
new EventTypeSpec (OSXConstants.kEventClassControl, OSXConstants.kEventControlSimulateHit),
new EventTypeSpec (OSXConstants.kEventClassControl, OSXConstants.kEventControlBoundsChanged),
+ new EventTypeSpec (OSXConstants.kEventClassControl, OSXConstants.kEventControlTrackingAreaEntered),
+ new EventTypeSpec (OSXConstants.kEventClassControl, OSXConstants.kEventControlTrackingAreaExited),
new EventTypeSpec (OSXConstants.kEventClassControl, OSXConstants.kEventControlDraw)
};
- private static EventTypeSpec [] windowEvents = new EventTypeSpec[] {
+ private static EventTypeSpec [] window_events = new EventTypeSpec[] {
//new EventTypeSpec (OSXConstants.kEventClassMouse, OSXConstants.kEventMouseEntered),
//new EventTypeSpec (OSXConstants.kEventClassMouse, OSXConstants.kEventMouseExited),
new EventTypeSpec (OSXConstants.kEventClassMouse, OSXConstants.kEventMouseMoved),
WindowBackgrounds = new Hashtable ();
// Initialize the FosterParent
- IntPtr rect = IntPtr.Zero;
+ Rect rect = new Rect ();
SetRect (ref rect, (short)0, (short)0, (short)0, (short)0);
+ ProcessSerialNumber psn = new ProcessSerialNumber();
+
+ CheckError (GetCurrentProcess( ref psn ), "GetCurrentProcess ()");
+ CheckError (TransformProcessType (ref psn, 1), "TransformProcessType ()");
+ CheckError (SetFrontProcess (ref psn), "SetFrontProcess ()");
CheckError (CreateNewWindow (WindowClass.kDocumentWindowClass, WindowAttributes.kWindowStandardHandlerAttribute | WindowAttributes.kWindowCloseBoxAttribute | WindowAttributes.kWindowFullZoomAttribute | WindowAttributes.kWindowCollapseBoxAttribute | WindowAttributes.kWindowResizableAttribute | WindowAttributes.kWindowCompositingAttribute, ref rect, ref FosterParent), "CreateFosterParent ()");
// Get some values about bar heights
#endregion
- #region Private methods
- #endregion
-
#region Callbacks
private void CaretCallback (object sender, EventArgs e) {
break;
}
default: {
- Console.WriteLine ("WARNING: Unhandled eventClass {0}", eventClass);
break;
}
}
#endregion
#region Private Methods
+
+ internal Point ConvertScreenPointToClient (IntPtr handle, Point point) {
+ Point converted_point = new Point ();
+ Rect window_bounds = new Rect ();
+ CGPoint native_point = new CGPoint ();
+
+ GetWindowBounds (HIViewGetWindow (handle), 32, ref window_bounds);
+
+ native_point.x = (point.X - window_bounds.left);
+ native_point.y = (point.Y - window_bounds.top);
+
+ HIViewConvertPoint (ref native_point, IntPtr.Zero, handle);
+
+ converted_point.X = (int)native_point.x;
+ converted_point.Y = (int)native_point.y;
+
+ return converted_point;
+ }
+
+ internal Point ConvertClientPointToScreen (IntPtr handle, Point point) {
+ Point converted_point = new Point ();
+ Rect window_bounds = new Rect ();
+ CGPoint native_point = new CGPoint ();
+
+ GetWindowBounds (HIViewGetWindow (handle), 32, ref window_bounds);
+
+ native_point.x = point.X;
+ native_point.y = point.Y;
+
+ HIViewConvertPoint (ref native_point, handle, IntPtr.Zero);
+
+ converted_point.X = (int)(native_point.x + window_bounds.left);
+ converted_point.Y = (int)(native_point.y + window_bounds.top);
+
+ return converted_point;
+ }
// This sucks write a real driver
private int ProcessKeyboardEvent (IntPtr inEvent, uint eventKind, IntPtr handle) {
HIRect r = new HIRect ();
// Get our frame for the Handle
- CheckError (HIViewGetFrame (hwnd.Handle, ref r), "HIViewGetFrame ()");
+ CheckError (HIViewGetFrame (hwnd.WholeWindow, ref r), "HIViewGetFrame ()");
r.size.width = bounds.right-bounds.left;
r.size.height = bounds.bottom-bounds.top;
// Set the view to the new size
- CheckError (HIViewSetFrame (hwnd.WholeWindow, ref r), "HIViewSetFrame ()");
-
- // Update the hwnd internal size representation
- hwnd.x = (int)r.origin.x;
- hwnd.y = (int)r.origin.y;
- hwnd.width = (int)r.size.width;
- hwnd.height = (int)r.size.height;
- Rectangle client_rect = hwnd.ClientRect;
-
- r.size.width = client_rect.Width;
- r.size.height = client_rect.Height;
- r.origin.x = client_rect.X;
- r.origin.y = client_rect.Y;
-
- // Update the client area too
- CheckError (HIViewSetFrame (hwnd.ClientWindow, ref r));
+ CheckError (HIViewSetFrame (hwnd.WholeWindow, ref r), "HIViewSetFrame ()");
+
+ // Update the hwnd internal size representation
+ Size newsize = TranslateQuartzWindowSizeToWindowSize (Control.FromHandle (hwnd.Handle).GetCreateParams (), (int)r.size.width, (int)r.size.height);
+ hwnd.x = (int)bounds.left;
+ hwnd.y = (int)bounds.top;
+ hwnd.width = (int)newsize.Width;
+ hwnd.height = (int)newsize.Height;
+ PerformNCCalc (hwnd);
// Add the message to the queue
msg.message = Msg.WM_WINDOWPOSCHANGED;
return -9874;
// Generate the message
+ bool client = (hwnd.ClientWindow == view_handle ? true : false);
msg.hwnd = hwnd.Handle;
- msg.message = Msg.WM_MOUSEMOVE;
+ msg.message = (client ? Msg.WM_MOUSEMOVE : Msg.WM_NCMOUSEMOVE);
msg.lParam = (IntPtr) ((ushort)window_pt.y << 16 | (ushort)window_pt.x);
msg.wParam = GetMousewParam (0);
mouse_position.X = (int)window_pt.x;
MSG msg = new MSG ();
switch (eventKind) {
+ case OSXConstants.kEventControlTrackingAreaEntered: {
+ if (hwnd.Handle == handle)
+ SetThemeCursor ((uint)hwnd.ClientCursor);
+ else
+ SetThemeCursor ((uint)hwnd.WholeCursor);
+ break;
+ }
+ case OSXConstants.kEventControlTrackingAreaExited: {
+ SetThemeCursor ((uint)ThemeCursor.kThemeArrowCursor);
+ break;
+ }
case OSXConstants.kEventControlDraw: {
if(!hwnd.visible || !HIViewIsVisible (handle))
return 0;
- /*
- IntPtr rgnhandle = IntPtr.Zero;
- GetEventParameter (inEvent, OSXConstants.EventParamName.kEventParamRgnHandle, OSXConstants.EventParamType.typeQDRgnHandle, IntPtr.Zero, (uint)Marshal.SizeOf (typeof (IntPtr)), IntPtr.Zero, ref rgnhandle);
- IntPtr duprgn = NewRgn ();
- CopyRgn (rgnhandle, duprgn);
- ClipRegions [hwnd.Handle] = duprgn;
- */
-
// Get the dirty area
HIRect bounds = new HIRect ();
HIViewGetBounds (handle, ref bounds);
bool client = (hwnd.ClientWindow == handle ? true : false);
-
+
if (!client && bounds.origin.x >= hwnd.ClientRect.X && bounds.origin.y >= hwnd.ClientRect.Y) {
// This is a paint on WholeWindow inside the clientRect; we can safely discard this
return 0;
}
- hwnd.AddInvalidArea ((int)bounds.origin.x, (int)bounds.origin.y, (int)bounds.size.width, (int)bounds.size.height);
+ AddExpose (hwnd, client, (int)bounds.origin.x, (int)bounds.origin.y, (int)bounds.size.width, (int)bounds.size.height);
if (WindowBackgrounds [hwnd] != null) {
Color c = (Color)WindowBackgrounds [hwnd];
IntPtr contextref = IntPtr.Zero;
CGContextFillRect (contextref, bounds);
}
- // Add a paint to the queue
- msg.hwnd = hwnd.Handle;
- msg.message = Msg.WM_PAINT;
- msg.wParam = IntPtr.Zero;
- msg.lParam = IntPtr.Zero;
- MessageQueue.Enqueue (msg);
+#if OptimizeDrawing
+ if (!client && hwnd.nc_expose_pending) {
+#else
+ if (!client) {
+#endif
+ switch (hwnd.border_style) {
+ case FormBorderStyle.Fixed3D: {
+ Graphics g;
+
+ g = Graphics.FromHwnd(hwnd.whole_window);
+ if (hwnd.border_static)
+ ControlPaint.DrawBorder3D(g, new Rectangle(0, 0, hwnd.Width, hwnd.Height), Border3DStyle.SunkenOuter);
+ else
+ ControlPaint.DrawBorder3D(g, new Rectangle(0, 0, hwnd.Width, hwnd.Height), Border3DStyle.Sunken);
+ g.Dispose();
+ break;
+ }
+
+ case FormBorderStyle.FixedSingle: {
+ Graphics g;
+
+ g = Graphics.FromHwnd(hwnd.whole_window);
+ ControlPaint.DrawBorder(g, new Rectangle(0, 0, hwnd.Width, hwnd.Height), Color.Black, ButtonBorderStyle.Solid);
+ g.Dispose();
+ break;
+ }
+ }
+ }
return 0;
}
HIRect bounds = new HIRect ();
HIViewGetFrame (handle, ref bounds);
// Update the hwnd size
- hwnd.x = (int)bounds.origin.x;
- hwnd.y = (int)bounds.origin.y;
- hwnd.width = (int)bounds.size.width;
- hwnd.height = (int)bounds.size.height;
+ bool client = (hwnd.ClientWindow == handle ? true : false);
+ if (!client) {
+ hwnd.x = (int)bounds.origin.x;
+ hwnd.y = (int)bounds.origin.y;
+ hwnd.width = (int)bounds.size.width;
+ hwnd.height = (int)bounds.size.height;
+ }
// TODO: Do we need to send a paint here or does BoundsChanged make a ControlDraw for the exposed area?
}
CheckError (GetEventParameter (inEvent, OSXConstants.EventParamName.kEventParamMouseLocation, OSXConstants.EventParamType.typeQDPoint, IntPtr.Zero, (uint)Marshal.SizeOf (typeof (QDPoint)), IntPtr.Zero, ref point), "GetEventParameter() MouseLocation");
MouseTrackingResult mousestatus = MouseTrackingResult.kMouseTrackingMouseDown;
IntPtr modifiers = IntPtr.Zero;
+ if (GrabWindowHwnd != null)
+ hwnd = GrabWindowHwnd;
while (mousestatus != MouseTrackingResult.kMouseTrackingMouseUp) {
- CheckTimers (DateTime.Now);
+ CheckTimers (DateTime.UtcNow);
if (mousestatus == MouseTrackingResult.kMouseTrackingMouseDragged) {
QDPoint realpoint = point;
int x = point.x;
msg.hwnd = hwnd.Handle;
bool client = (hwnd.ClientWindow == handle ? true : false);
+ if (GrabWindowHwnd != null)
+ client = true;
+
int wparam = (int)GetMousewParam (0);
switch (MouseState) {
}
int x2 = point.x;
int y2 = point.y;
- ScreenToClient (hwnd.Handle, ref x2, ref y2);
+ if (client)
+ ScreenToClient (hwnd.Handle, ref x2, ref y2);
point.x = (short)x2;
point.y = (short)y2;
//NativeWindow.WndProc (msg.hwnd, msg.message, msg.lParam, msg.wParam);
MessageQueue.Enqueue (msg);
- IntPtr window = GetControlOwner (hwnd.Handle);
+ IntPtr window = HIViewGetWindow (hwnd.Handle);
SetKeyboardFocus (window, hwnd.Handle, 1);
-
+
return 0;
}
case OSXConstants.kEventControlContextualMenuClick:
QDPoint trackpoint = point;
int x = point.x;
int y = point.y;
- ScreenToClient (hwnd.Handle, ref x, ref y);
+
+
+ bool client = (hwnd.ClientWindow == handle ? true : false);
+ if (client)
+ ScreenToClient (hwnd.Handle, ref x, ref y);
+
point.x = (short)x;
point.y = (short)y;
-
+
// which button was pressed?
ushort button = 0;
GetEventParameter (inEvent, OSXConstants.EventParamName.kEventParamMouseButton, OSXConstants.EventParamType.typeMouseButton, IntPtr.Zero, (uint)Marshal.SizeOf (typeof (ushort)), IntPtr.Zero, ref button);
msg.hwnd = hwnd.Handle;
- bool client = (hwnd.ClientWindow == handle ? true : false);
int wparam = (int)GetMousewParam (0);
switch (button) {
return -9874;
}
private IntPtr GetMousewParam(int Delta) {
- int result = 0;
+ int result = 0;
if ((MouseState & MouseButtons.Left) != 0) {
result |= (int)MsgButtons.MK_LBUTTON;
private double NextTimeout ()
{
- DateTime now = DateTime.Now;
+ DateTime now = DateTime.UtcNow;
int timeout = 0x7FFFFFF;
lock (TimerList) {
foreach (Timer timer in TimerList) {
}
internal void InvertCaret () {
- IntPtr window = GetControlOwner (Caret.Hwnd);
+ IntPtr window = HIViewGetWindow (Caret.Hwnd);
SetPortWindowPort (window);
Rect r = new Rect ();
GetWindowPortBounds (window, ref r);
InvertRect (ref r);
}
+ void SendParentNotify(IntPtr child, Msg cause, int x, int y)
+ {
+ Hwnd hwnd;
+
+ if (child == IntPtr.Zero) {
+ return;
+ }
+
+ hwnd = Hwnd.GetObjectFromWindow (child);
+
+ if (hwnd == null) {
+ return;
+ }
+
+ if (hwnd.Handle == IntPtr.Zero) {
+ return;
+ }
+
+ if (ExStyleSet ((int) hwnd.initial_ex_style, WindowExStyles.WS_EX_NOPARENTNOTIFY)) {
+ return;
+ }
+
+ if (hwnd.Parent == null) {
+ return;
+ }
+
+ if (hwnd.Parent.Handle == IntPtr.Zero) {
+ return;
+ }
+
+ if (cause == Msg.WM_CREATE || cause == Msg.WM_DESTROY) {
+ SendMessage(hwnd.Parent.Handle, Msg.WM_PARENTNOTIFY, Control.MakeParam((int)cause, 0), child);
+ } else {
+ SendMessage(hwnd.Parent.Handle, Msg.WM_PARENTNOTIFY, Control.MakeParam((int)cause, 0), Control.MakeParam(x, y));
+ }
+
+ SendParentNotify (hwnd.Parent.Handle, cause, x, y);
+ }
+
+ bool StyleSet (int s, WindowStyles ws)
+ {
+ return (s & (int)ws) == (int)ws;
+ }
+
+ bool ExStyleSet (int ex, WindowExStyles exws)
+ {
+ return (ex & (int)exws) == (int)exws;
+ }
+
+ internal static Rectangle TranslateClientRectangleToQuartzClientRectangle (Hwnd hwnd) {
+ return TranslateClientRectangleToQuartzClientRectangle (hwnd, Control.FromHandle (hwnd.Handle));
+ }
+
+ internal static Rectangle TranslateClientRectangleToQuartzClientRectangle (Hwnd hwnd, Control ctrl) {
+ /* From XplatUIX11
+ * If this is a form with no window manager, X is handling all the border and caption painting
+ * so remove that from the area (since the area we set of the window here is the part of the window
+ * we're painting in only)
+ */
+ Rectangle rect = hwnd.ClientRect;
+ Form form = ctrl as Form;
+ CreateParams cp = null;
+
+ if (form != null)
+ cp = form.GetCreateParams ();
+
+ if (form != null && (form.window_manager == null || cp.IsSet (WindowExStyles.WS_EX_TOOLWINDOW))) {
+ Hwnd.Borders borders = Hwnd.GetBorders (cp, null);
+ Rectangle qrect = rect;
+
+ qrect.Y -= borders.top;
+ qrect.X -= borders.left;
+ qrect.Width += borders.left + borders.right;
+ qrect.Height += borders.top + borders.bottom;
+
+ rect = qrect;
+ }
+
+ if (rect.Width < 1 || rect.Height < 1) {
+ rect.Width = 1;
+ rect.Height = 1;
+ rect.X = -5;
+ rect.Y = -5;
+ }
+
+ return rect;
+ }
+
+ internal static Size TranslateWindowSizeToQuartzWindowSize (CreateParams cp) {
+ return TranslateWindowSizeToQuartzWindowSize (cp, new Size (cp.Width, cp.Height));
+ }
+
+ internal static Size TranslateWindowSizeToQuartzWindowSize (CreateParams cp, Size size) {
+ /* From XplatUIX11
+ * If this is a form with no window manager, X is handling all the border and caption painting
+ * so remove that from the area (since the area we set of the window here is the part of the window
+ * we're painting in only)
+ */
+ Form form = cp.control as Form;
+ if (form != null && (form.window_manager == null || cp.IsSet (WindowExStyles.WS_EX_TOOLWINDOW))) {
+ Hwnd.Borders borders = Hwnd.GetBorders (cp, null);
+ Size qsize = size;
+
+ qsize.Width -= borders.left + borders.right;
+ qsize.Height -= borders.top + borders.bottom;
+
+ size = qsize;
+ }
+
+ if (size.Height == 0)
+ size.Height = 1;
+ if (size.Width == 0)
+ size.Width = 1;
+ return size;
+ }
+
+ internal static Size TranslateQuartzWindowSizeToWindowSize (CreateParams cp, int width, int height) {
+ /* From XplatUIX11
+ * If this is a form with no window manager, X is handling all the border and caption painting
+ * so remove that from the area (since the area we set of the window here is the part of the window
+ * we're painting in only)
+ */
+ Size size = new Size (width, height);
+ Form form = cp.control as Form;
+ if (form != null && (form.window_manager == null || cp.IsSet (WindowExStyles.WS_EX_TOOLWINDOW))) {
+ Hwnd.Borders borders = Hwnd.GetBorders (cp, null);
+ Size qsize = size;
+
+ qsize.Width += borders.left + borders.right;
+ qsize.Height += borders.top + borders.bottom;
+
+ size = qsize;
+ }
+
+ return size;
+ }
+
+ private void DeriveStyles(int Style, int ExStyle, out FormBorderStyle border_style, out bool border_static, out TitleStyle title_style, out int caption_height, out int tool_caption_height) {
+
+ caption_height = 0;
+ tool_caption_height = 0;
+ border_static = false;
+
+ if (StyleSet (Style, WindowStyles.WS_CHILD)) {
+ if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_CLIENTEDGE)) {
+ border_style = FormBorderStyle.Fixed3D;
+ } else if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_STATICEDGE)) {
+ border_style = FormBorderStyle.Fixed3D;
+ border_static = true;
+ } else if (!StyleSet (Style, WindowStyles.WS_BORDER)) {
+ border_style = FormBorderStyle.None;
+ } else {
+ border_style = FormBorderStyle.FixedSingle;
+ }
+ title_style = TitleStyle.None;
+
+ if (StyleSet (Style, WindowStyles.WS_CAPTION)) {
+ caption_height = 0;
+ if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_TOOLWINDOW)) {
+ title_style = TitleStyle.Tool;
+ } else {
+ title_style = TitleStyle.Normal;
+ }
+ }
+
+ if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_MDICHILD)) {
+ caption_height = 0;
+
+ if (StyleSet (Style, WindowStyles.WS_OVERLAPPEDWINDOW) ||
+ ExStyleSet (ExStyle, WindowExStyles.WS_EX_TOOLWINDOW)) {
+ border_style = (FormBorderStyle) 0xFFFF;
+ } else {
+ border_style = FormBorderStyle.None;
+ }
+ }
+
+ } else {
+ title_style = TitleStyle.None;
+ if (StyleSet (Style, WindowStyles.WS_CAPTION)) {
+ if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_TOOLWINDOW)) {
+ title_style = TitleStyle.Tool;
+ } else {
+ title_style = TitleStyle.Normal;
+ }
+ }
+
+ border_style = FormBorderStyle.None;
+
+ if (StyleSet (Style, WindowStyles.WS_THICKFRAME)) {
+ if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_TOOLWINDOW)) {
+ border_style = FormBorderStyle.SizableToolWindow;
+ } else {
+ border_style = FormBorderStyle.Sizable;
+ }
+ } else {
+ if (StyleSet (Style, WindowStyles.WS_CAPTION)) {
+ if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_CLIENTEDGE)) {
+ border_style = FormBorderStyle.Fixed3D;
+ } else if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_STATICEDGE)) {
+ border_style = FormBorderStyle.Fixed3D;
+ border_static = true;
+ } else if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_DLGMODALFRAME)) {
+ border_style = FormBorderStyle.FixedDialog;
+ } else if (ExStyleSet (ExStyle, WindowExStyles.WS_EX_TOOLWINDOW)) {
+ border_style = FormBorderStyle.FixedToolWindow;
+ } else if (StyleSet (Style, WindowStyles.WS_BORDER)) {
+ border_style = FormBorderStyle.FixedSingle;
+ }
+ } else {
+ if (StyleSet (Style, WindowStyles.WS_BORDER)) {
+ border_style = FormBorderStyle.FixedSingle;
+ }
+ }
+ }
+ }
+ }
+
private void SetHwndStyles(Hwnd hwnd, CreateParams cp) {
- throw new NotImplementedException();
+ DeriveStyles(cp.Style, cp.ExStyle, out hwnd.border_style, out hwnd.border_static, out hwnd.title_style, out hwnd.caption_height, out hwnd.tool_caption_height);
}
internal void ShowCaret () {
IntPtr rgn = NewRgn ();
SetRectRgn (rgn, (short)client_bounds.origin.x, (short)client_bounds.origin.y, (short)(client_bounds.origin.x+hwnd.ClientRect.Width), (short)(client_bounds.origin.y+hwnd.ClientRect.Height));
- CreateMouseTrackingRegion (GetControlOwner (hwnd.client_window), rgn, IntPtr.Zero, 0, hwnd.client_region_id, hwnd.client_window, IntPtr.Zero, ref hwnd.client_region_ptr);
+ CreateMouseTrackingRegion (HIViewGetWindow (hwnd.client_window), rgn, IntPtr.Zero, 0, hwnd.client_region_id, hwnd.client_window, IntPtr.Zero, ref hwnd.client_region_ptr);
Console.WriteLine (hwnd.ClientRect);
Console.WriteLine ("Created a mouse trcaking region on the client window @ {0}x{1} {2}x{3}", (short)client_bounds.origin.x, (short)client_bounds.origin.y, (short)(client_bounds.origin.x+hwnd.ClientRect.Width), (short)(client_bounds.origin.y+hwnd.ClientRect.Height));
if (hwnd.ClientRect.X > 0 && hwnd.ClientRect.Y > 0) {
HIViewConvertRect (ref window_bounds, hwnd.whole_window, IntPtr.Zero);
rgn = NewRgn ();
SetRectRgn (rgn, (short)window_bounds.origin.x, (short)window_bounds.origin.y, (short)(window_bounds.origin.x+hwnd.ClientRect.X), (short)(window_bounds.origin.y+hwnd.ClientRect.Y));
- CreateMouseTrackingRegion (GetControlOwner (hwnd.whole_window), rgn, IntPtr.Zero, 0, hwnd.whole_region_id, hwnd.whole_window, IntPtr.Zero, ref hwnd.whole_region_ptr);
+ CreateMouseTrackingRegion (HIViewGetWindow (hwnd.whole_window), rgn, IntPtr.Zero, 0, hwnd.whole_region_id, hwnd.whole_window, IntPtr.Zero, ref hwnd.whole_region_ptr);
Console.WriteLine ("Created a mouse trcaking region on the whole window @ {0}x{1} {2}x{3}", (short)window_bounds.origin.x, (short)window_bounds.origin.y, (short)(window_bounds.origin.x+hwnd.ClientRect.X), (short)(window_bounds.origin.y+hwnd.ClientRect.Y));
}
}
throw new Exception ("XplatUIOSX.cs::Carbon subsystem threw an error: " + result);
}
+ private void AccumulateDestroyedHandles (Control c, ArrayList list)
+ {
+ if (c != null) {
+ Control[] controls = c.Controls.GetAllControls ();
+
+ if (c.IsHandleCreated && !c.IsDisposed) {
+ Hwnd hwnd = Hwnd.ObjectFromHandle(c.Handle);
+
+ list.Add (hwnd);
+ CleanupCachedWindows (hwnd);
+ }
+
+ for (int i = 0; i < controls.Length; i ++) {
+ AccumulateDestroyedHandles (controls[i], list);
+ }
+ }
+
+ }
+
+ void CleanupCachedWindows (Hwnd hwnd)
+ {
+ if (ActiveWindow == hwnd.Handle) {
+ SendMessage(hwnd.client_window, Msg.WM_ACTIVATE, (IntPtr)WindowActiveFlags.WA_INACTIVE, IntPtr.Zero);
+ ActiveWindow = IntPtr.Zero;
+ }
+
+ if (FocusWindow == hwnd.Handle) {
+ SendMessage(hwnd.client_window, Msg.WM_KILLFOCUS, IntPtr.Zero, IntPtr.Zero);
+ FocusWindow = IntPtr.Zero;
+ }
+
+ if (Grab.Hwnd == hwnd.Handle) {
+ Grab.Hwnd = IntPtr.Zero;
+ Grab.Confined = false;
+ }
+
+ DestroyCaret (hwnd.Handle);
+ }
+
+ private void PerformNCCalc(Hwnd hwnd) {
+#if EnableNCArea
+ XplatUIWin32.NCCALCSIZE_PARAMS ncp;
+ IntPtr ptr;
+ Rectangle rect;
+
+ rect = new Rectangle (0, 0, hwnd.Width, hwnd.Height);
+
+ ncp = new XplatUIWin32.NCCALCSIZE_PARAMS();
+ ptr = Marshal.AllocHGlobal(Marshal.SizeOf(ncp));
+
+ ncp.rgrc1.left = rect.Left;
+ ncp.rgrc1.top = rect.Top;
+ ncp.rgrc1.right = rect.Right;
+ ncp.rgrc1.bottom = rect.Bottom;
+
+ Marshal.StructureToPtr(ncp, ptr, true);
+ NativeWindow.WndProc(hwnd.client_window, Msg.WM_NCCALCSIZE, (IntPtr)1, ptr);
+ ncp = (XplatUIWin32.NCCALCSIZE_PARAMS)Marshal.PtrToStructure(ptr, typeof(XplatUIWin32.NCCALCSIZE_PARAMS));
+ Marshal.FreeHGlobal(ptr);
+
+
+ rect = new Rectangle(ncp.rgrc1.left, ncp.rgrc1.top, ncp.rgrc1.right - ncp.rgrc1.left, ncp.rgrc1.bottom - ncp.rgrc1.top);
+ hwnd.ClientRect = rect;
+
+ rect = TranslateClientRectangleToQuartzClientRectangle (hwnd);
+
+ if (hwnd.visible) {
+ HIRect r = new HIRect (rect.X, rect.Y, rect.Width, rect.Height);
+ HIViewSetFrame (hwnd.client_window, ref r);
+ }
+
+ AddExpose (hwnd, false, 0, 0, hwnd.Width, hwnd.Height);
+#endif
+ }
+
+ private void AddExpose (Hwnd hwnd, bool client, int x, int y, int width, int height) {
+ // Don't waste time
+ if ((hwnd == null) || (x > hwnd.Width) || (y > hwnd.Height) || ((x + width) < 0) || ((y + height) < 0)) {
+ return;
+ }
+
+ // Keep the invalid area as small as needed
+ if ((x + width) > hwnd.width) {
+ width = hwnd.width - x;
+ }
+
+ if ((y + height) > hwnd.height) {
+ height = hwnd.height - y;
+ }
+
+ if (client) {
+ hwnd.AddInvalidArea(x, y, width, height);
+#if OptimizeDrawing
+ if (!hwnd.expose_pending) {
+ if (!hwnd.nc_expose_pending) {
+#endif
+ MSG msg = new MSG ();
+ msg.message = Msg.WM_PAINT;
+ msg.hwnd = hwnd.Handle;
+ msg.lParam = IntPtr.Zero;
+ msg.wParam = IntPtr.Zero;
+ MessageQueue.Enqueue (msg);
+#if OptimizeDrawing
+ }
+ hwnd.expose_pending = true;
+ }
+#endif
+ } else {
+ hwnd.AddNcInvalidArea (x, y, width, height);
+#if OptimizeDrawing
+ if (!hwnd.nc_expose_pending) {
+ if (!hwnd.expose_pending) {
+#endif
+ MSG msg = new MSG ();
+ Rectangle rect = new Rectangle (x, y, width, height);
+ Region region = new Region (rect);
+ IntPtr hrgn = region.GetHrgn (null);
+ msg.message = Msg.WM_NCPAINT;
+ msg.hwnd = hwnd.Handle;
+ msg.wParam = hrgn == IntPtr.Zero ? (IntPtr)1 : hrgn;
+ msg.refobject = region;
+ MessageQueue.Enqueue (msg);
+#if OptimizeDrawing
+ }
+ hwnd.nc_expose_pending = true;
+ }
+#endif
+ }
+ }
#endregion
#region Public Methods
}
internal override void Activate(IntPtr handle) {
- ActivateWindow (GetControlOwner (handle), true);
+ ActivateWindow (HIViewGetWindow (handle), true);
}
internal override void AudibleAlert() {
WindowRect = Hwnd.GetWindowRectangle (cp, menu, ClientRect);
return true;
}
-
+
internal override void ClientToScreen(IntPtr handle, ref int x, ref int y) {
- CGPoint pt = new CGPoint ();
- Rect wBounds = new Rect ();
- Hwnd hwnd;
+ Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
- hwnd = Hwnd.ObjectFromHandle(handle);
+ Point point = ConvertClientPointToScreen (hwnd.ClientWindow, new Point (x, y));
- pt.x = x;
- pt.y = y;
+ x = point.X;
+ y = point.Y;
+ }
+
+ internal override void MenuToScreen(IntPtr handle, ref int x, ref int y) {
+ Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
- GetWindowBounds (GetControlOwner (hwnd.client_window), 32, ref wBounds);
- HIViewConvertPoint (ref pt, handle, IntPtr.Zero);
+ Point point = ConvertClientPointToScreen (hwnd.ClientWindow, new Point (x, y));
- x = (int)(pt.x+wBounds.left);
- y = (int)(pt.y+wBounds.top);
+ x = point.X;
+ y = point.Y;
}
internal override int[] ClipboardAvailableFormats(IntPtr handle) {
}
internal override void ClipboardClose(IntPtr handle) {
- throw new NotImplementedException();
}
internal override int ClipboardGetID(IntPtr handle, string format) {
}
internal override IntPtr ClipboardOpen(bool primary_selection) {
- throw new NotImplementedException();
+ return IntPtr.Zero;
}
internal override object ClipboardRetrieve(IntPtr handle, int id, XplatUI.ClipboardToObject converter) {
}
internal override IntPtr CreateWindow(CreateParams cp) {
- IntPtr windowHnd = IntPtr.Zero;
- IntPtr parentHnd = cp.Parent;
- bool realWindow = false;
- Rectangle clientRect;
- Hwnd hwnd = new Hwnd ();
-
- SetHwndStyles (hwnd, cp);
-
- if (parentHnd == IntPtr.Zero) {
- if ((cp.Style & (int)(WindowStyles.WS_CHILD))!=0) {
- // This is a child view that is going to be parentless;
- realWindow = false;
- CheckError (HIViewFindByID (HIViewGetRoot (FosterParent), new HIViewID (OSXConstants.kEventClassWindow, 1), ref parentHnd), "HIViewFindByID ()");
- } else if ((cp.Style & (int)(WindowStyles.WS_POPUP))!=0) {
- // This is a popup window that will be real.
- if (cp.X < 1) cp.X = 0;
- if (cp.Y < 1) cp.Y = 0;
- realWindow = true;
- } else {
- // This is a real root window too
- if (cp.X < 1) cp.X = 0;
- if (cp.Y < 1) cp.Y = 0;
- realWindow = true;
- }
+ Hwnd hwnd;
+ Hwnd parent_hwnd = null;
+ int X;
+ int Y;
+ int Width;
+ int Height;
+ IntPtr ParentHandle;
+ IntPtr WindowHandle;
+ IntPtr WholeWindow;
+ IntPtr ClientWindow;
+ IntPtr WholeWindowTracking;
+ IntPtr ClientWindowTracking;
+ WindowAttributes Attributes;
+
+ hwnd = new Hwnd ();
+
+ Attributes = new WindowAttributes ();
+ X = cp.X;
+ Y = cp.Y;
+ Width = cp.Width;
+ Height = cp.Height;
+ ParentHandle = IntPtr.Zero;
+ WindowHandle = IntPtr.Zero;
+ WholeWindow = IntPtr.Zero;
+ ClientWindow = IntPtr.Zero;
+ WholeWindowTracking = IntPtr.Zero;
+ ClientWindowTracking = IntPtr.Zero;
+
+ if (Width < 1) Width = 1;
+ if (Height < 1) Height = 1;
+
+ if (cp.Parent != IntPtr.Zero) {
+ parent_hwnd = Hwnd.ObjectFromHandle (cp.Parent);
+ ParentHandle = parent_hwnd.client_window;
} else {
- realWindow = false;
+ if (StyleSet (cp.Style, WindowStyles.WS_CHILD)) {
+ HIViewFindByID (HIViewGetRoot (FosterParent), new HIViewID (OSXConstants.kEventClassWindow, 1), ref ParentHandle);
+ }
}
- if (realWindow) {
+ Point next;
+ if (cp.control is Form) {
+ next = Hwnd.GetNextStackedFormLocation (cp, parent_hwnd);
+ X = next.X;
+ Y = next.Y;
+ }
+
+ hwnd.x = X;
+ hwnd.y = Y;
+ hwnd.width = Width;
+ hwnd.height = Height;
+ hwnd.parent = Hwnd.ObjectFromHandle (cp.Parent);
+ hwnd.initial_style = cp.WindowStyle;
+ hwnd.initial_ex_style = cp.WindowExStyle;
+
+ if (StyleSet (cp.Style, WindowStyles.WS_DISABLED)) {
+ hwnd.enabled = false;
+ }
+
+ ClientWindow = IntPtr.Zero;
+
+ Size QWindowSize = TranslateWindowSizeToQuartzWindowSize (cp);
+ Rectangle QClientRect = TranslateClientRectangleToQuartzClientRectangle (hwnd, cp.control);
+
+/* FIXME */
+ if (ParentHandle == IntPtr.Zero) {
+ IntPtr window_view = IntPtr.Zero;
WindowClass windowklass = WindowClass.kOverlayWindowClass;
WindowAttributes attributes = WindowAttributes.kWindowCompositingAttribute | WindowAttributes.kWindowStandardHandlerAttribute;
- if ((cp.Style & ((int)WindowStyles.WS_MINIMIZEBOX)) != 0) {
+ if (StyleSet (cp.Style, WindowStyles.WS_MINIMIZEBOX)) {
attributes |= WindowAttributes.kWindowCollapseBoxAttribute;
}
- if ((cp.Style & ((int)WindowStyles.WS_MAXIMIZEBOX)) != 0) {
+ if (StyleSet (cp.Style, WindowStyles.WS_MAXIMIZEBOX)) {
attributes |= WindowAttributes.kWindowResizableAttribute | WindowAttributes.kWindowHorizontalZoomAttribute | WindowAttributes.kWindowVerticalZoomAttribute;
}
- if ((cp.Style & ((int)WindowStyles.WS_SYSMENU)) != 0) {
+ if (StyleSet (cp.Style, WindowStyles.WS_SYSMENU)) {
attributes |= WindowAttributes.kWindowCloseBoxAttribute;
}
- if ((cp.ExStyle & ((int)WindowExStyles.WS_EX_TOOLWINDOW)) != 0) {
- attributes = WindowAttributes.kWindowStandardHandlerAttribute | WindowAttributes.kWindowCompositingAttribute;
- }
- if ((cp.Style & ((int)WindowStyles.WS_CAPTION)) != 0) {
+ if (StyleSet (cp.Style, WindowStyles.WS_CAPTION)) {
windowklass = WindowClass.kDocumentWindowClass;
}
+ if (ExStyleSet (cp.ExStyle, WindowExStyles.WS_EX_TOOLWINDOW)) {
+ windowklass = WindowClass.kOverlayWindowClass;
+ attributes = WindowAttributes.kWindowCompositingAttribute | WindowAttributes.kWindowStandardHandlerAttribute;
+ }
- IntPtr rect = IntPtr.Zero;
- IntPtr viewHnd = IntPtr.Zero;
- SetRect (ref rect, (short)cp.X, (short)(cp.Y + MenuBarHeight + TitleBarHeight), (short)(cp.Width+cp.X), (short)(cp.Height+cp.Y+MenuBarHeight+TitleBarHeight));
- CheckError (CreateNewWindow (windowklass, attributes, ref rect, ref windowHnd), "CreateNewWindow ()");
-
- CheckError (InstallEventHandler (GetWindowEventTarget (windowHnd), CarbonEventHandler, (uint)windowEvents.Length, windowEvents, windowHnd, IntPtr.Zero), "InstallEventHandler ()");
- CheckError (HIViewFindByID (HIViewGetRoot (windowHnd), new HIViewID (OSXConstants.kEventClassWindow, 1), ref viewHnd), "HIViewFindByID ()");
- parentHnd = viewHnd;
- }
- hwnd.X = cp.X;
- hwnd.Y = cp.Y;
- hwnd.Width = cp.Width;
- hwnd.Height = cp.Height;
- hwnd.Parent = Hwnd.ObjectFromHandle (cp.Parent);
- hwnd.visible = false;
- clientRect = hwnd.ClientRect;
-
- HIRect r = new HIRect (0, 0, cp.Width, cp.Height);
- CheckError (HIObjectCreate (__CFStringMakeConstantString ("com.apple.hiview"), 0, ref hwnd.whole_window), "HIObjectCreate ()");
- CheckError (InstallEventHandler (GetControlEventTarget (hwnd.whole_window), CarbonEventHandler, (uint)viewEvents.Length, viewEvents, hwnd.whole_window, IntPtr.Zero), "InstallEventHandler ()");
- CheckError (HIViewChangeFeatures (hwnd.whole_window, 1 << 1, 0), "HIViewChangeFeatures ()");
- CheckError (HIViewSetFrame (hwnd.whole_window, ref r), "HIViewSetFrame ()");
- hwnd.WholeWindow = hwnd.whole_window;
-
- r = new HIRect (0, 0, clientRect.Width, clientRect.Height);
- CheckError (HIObjectCreate (__CFStringMakeConstantString ("com.apple.hiview"), 0, ref hwnd.client_window), "HIObjectCreate ()");
- CheckError (InstallEventHandler (GetControlEventTarget (hwnd.client_window), CarbonEventHandler, (uint)viewEvents.Length, viewEvents, hwnd.client_window, IntPtr.Zero), "InstallEventHandler ()");
- CheckError (HIViewChangeFeatures (hwnd.client_window, 1 << 1, 0), "HIViewChangeFeatures ()");
- CheckError (HIViewSetFrame (hwnd.client_window, ref r), "HIViewSetFrame ()");
- hwnd.ClientWindow = hwnd.client_window;
-
- CheckError (HIViewAddSubview (hwnd.whole_window, hwnd.client_window));
- CheckError (HIViewPlaceInSuperviewAt (hwnd.client_window, clientRect.X, clientRect.Y));
-
- if (parentHnd != IntPtr.Zero && parentHnd != hwnd.WholeWindow) {
- CheckError (HIViewAddSubview (parentHnd, hwnd.whole_window), "HIViewAddSubview ()");
- CheckError (HIViewPlaceInSuperviewAt (hwnd.whole_window, cp.X, cp.Y), "HIPlaceInSuperviewAt ()");
- if ((cp.Style & (int)(WindowStyles.WS_VISIBLE))!=0) {
- CheckError (HIViewSetVisible (hwnd.whole_window, true), "HIViewSetVisible ()");
- CheckError (HIViewSetVisible (hwnd.client_window, true), "HIViewSetVisible ()");
- hwnd.visible = true;
+ Rect rect = new Rect ();
+ if (StyleSet (cp.Style, WindowStyles.WS_POPUP)) {
+ SetRect (ref rect, (short)X, (short)(Y), (short)(X + QWindowSize.Width), (short)(Y + QWindowSize.Height));
} else {
- CheckError (HIViewSetVisible (hwnd.whole_window, false), "HIViewSetVisible ()");
- CheckError (HIViewSetVisible (hwnd.client_window, false), "HIViewSetVisible ()");
- hwnd.visible = false;
+ SetRect (ref rect, (short)X, (short)(Y + MenuBarHeight), (short)(X + QWindowSize.Width), (short)(Y + MenuBarHeight + QWindowSize.Height));
}
+
+ CreateNewWindow (windowklass, attributes, ref rect, ref WindowHandle);
+ InstallEventHandler (GetWindowEventTarget (WindowHandle), CarbonEventHandler, (uint)window_events.Length, window_events, WindowHandle, IntPtr.Zero);
+ HIViewFindByID (HIViewGetRoot (WindowHandle), new HIViewID (OSXConstants.kEventClassWindow, 1), ref window_view);
+ ParentHandle = window_view;
}
- if (realWindow) {
- WindowMapping [hwnd.Handle] = windowHnd;
- if ((cp.Style & (int)(WindowStyles.WS_VISIBLE))!=0) {
- CheckError (ShowWindow (windowHnd));
- CheckError (HIViewSetVisible (hwnd.whole_window, true), "HIViewSetVisible ()");
- CheckError (HIViewSetVisible (hwnd.client_window, true), "HIViewSetVisible ()");
- hwnd.visible = true;
- }
- if ((cp.Style & (int)(WindowStyles.WS_POPUP))!=0) {
- CheckError (HIViewSetVisible (hwnd.whole_window, true), "HIViewSetVisible ()");
- CheckError (HIViewSetVisible (hwnd.client_window, true), "HIViewSetVisible ()");
- hwnd.visible = true;
+
+ HIObjectCreate (__CFStringMakeConstantString ("com.apple.hiview"), 0, ref WholeWindow);
+ HIObjectCreate (__CFStringMakeConstantString ("com.apple.hiview"), 0, ref ClientWindow);
+ InstallEventHandler (GetControlEventTarget (WholeWindow), CarbonEventHandler, (uint)view_events.Length, view_events, WholeWindow, IntPtr.Zero);
+ InstallEventHandler (GetControlEventTarget (ClientWindow), CarbonEventHandler, (uint)view_events.Length, view_events, ClientWindow, IntPtr.Zero);
+ HIViewChangeFeatures (WholeWindow, 1<<1, 0);
+ HIViewChangeFeatures (ClientWindow, 1<<1, 0);
+ HIViewNewTrackingArea (WholeWindow, IntPtr.Zero, (UInt64)WholeWindow, ref WholeWindowTracking);
+ HIViewNewTrackingArea (ClientWindow, IntPtr.Zero, (UInt64)ClientWindow, ref ClientWindowTracking);
+ HIRect WholeRect;
+ if (WindowHandle != IntPtr.Zero) {
+ WholeRect = new HIRect (0, 0, QWindowSize.Width, QWindowSize.Height);
+ } else {
+ WholeRect = new HIRect (X, Y, QWindowSize.Width, QWindowSize.Height);
+ }
+ HIRect ClientRect = new HIRect (QClientRect.X, QClientRect.Y, QClientRect.Width, QClientRect.Height);
+ HIViewSetFrame (WholeWindow, ref WholeRect);
+ HIViewSetFrame (ClientWindow, ref ClientRect);
+
+ HIViewAddSubview (ParentHandle, WholeWindow);
+ HIViewAddSubview (WholeWindow, ClientWindow);
+
+ hwnd.WholeWindow = WholeWindow;
+ hwnd.ClientWindow = ClientWindow;
+
+ if (StyleSet (cp.Style, WindowStyles.WS_VISIBLE) || StyleSet (cp.Style, WindowStyles.WS_POPUP)) {
+ if (WindowHandle != IntPtr.Zero) {
+ WindowMapping [hwnd.Handle] = WindowHandle;
+ IntPtr active = GetActive ();
+ CheckError (ShowWindow (WindowHandle));
+ if (active != IntPtr.Zero)
+ Activate (active);
}
- }
+ HIViewSetVisible (WholeWindow, true);
+ HIViewSetVisible (ClientWindow, true);
+ hwnd.visible = true;
+ } else {
+ HIViewSetVisible (WholeWindow, false);
+ HIViewSetVisible (ClientWindow, false);
+ hwnd.visible = false;
+ }
+
+ Text (hwnd.Handle, cp.Caption);
+ SendMessage (hwnd.Handle, Msg.WM_CREATE, (IntPtr)1, IntPtr.Zero /* XXX unused */);
+ SendMessage (hwnd.Handle, Msg.WM_SHOWWINDOW, (IntPtr)1, IntPtr.Zero);
+
return hwnd.Handle;
}
}
[MonoTODO]
internal override IntPtr DefineCursor(Bitmap bitmap, Bitmap mask, Color cursor_pixel, Color mask_pixel, int xHotSpot, int yHotSpot) {
- throw new NotImplementedException ();
+ return IntPtr.Zero;
}
- [MonoTODO]
internal override IntPtr DefineStdCursor(StdCursor id) {
switch (id) {
case StdCursor.AppStarting:
return (IntPtr)ThemeCursor.kThemeArrowCursor;
case StdCursor.SizeWE:
return (IntPtr)ThemeCursor.kThemeArrowCursor;
- case StdCursor.UpArrow:
+ case StdCursor.UpArrow:
return (IntPtr)ThemeCursor.kThemeArrowCursor;
case StdCursor.VSplit:
return (IntPtr)ThemeCursor.kThemeArrowCursor;
case StdCursor.WaitCursor:
return (IntPtr)ThemeCursor.kThemeSpinningCursor;
- default:
+ default:
return (IntPtr)ThemeCursor.kThemeArrowCursor;
}
}
Exit ();
break;
}
+ case Msg.WM_PAINT: {
+#if OptimizeDrawing
+ hwnd.expose_pending = false;
+#endif
+ break;
+ }
+ case Msg.WM_NCPAINT: {
+#if OptimizeDrawing
+ hwnd.nc_expose_pending = false;
+#endif
+ break;
+ }
+ case Msg.WM_NCCALCSIZE: {
+ if (msg.WParam == (IntPtr)1) {
+ XplatUIWin32.NCCALCSIZE_PARAMS ncp;
+ ncp = (XplatUIWin32.NCCALCSIZE_PARAMS)Marshal.PtrToStructure (msg.LParam, typeof (XplatUIWin32.NCCALCSIZE_PARAMS));
+
+ // Add all the stuff X is supposed to draw.
+ Control ctrl = Control.FromHandle (hwnd.Handle);
+ if (ctrl != null) {
+ Hwnd.Borders rect = Hwnd.GetBorders (ctrl.GetCreateParams (), null);
+
+ ncp.rgrc1.top += rect.top;
+ ncp.rgrc1.bottom -= rect.bottom;
+ ncp.rgrc1.left += rect.left;
+ ncp.rgrc1.right -= rect.right;
+
+ Marshal.StructureToPtr (ncp, msg.LParam, true);
+ }
+ }
+ break;
+ }
}
return IntPtr.Zero;
}
Hwnd hwnd;
hwnd = Hwnd.ObjectFromHandle(handle);
-
- if ((hwnd.whole_window != IntPtr.Zero) && HIViewGetSuperview (hwnd.whole_window) != IntPtr.Zero)
- CheckError (HIViewRemoveFromSuperview (handle), "HIViewRemoveFromSuperview ()");
- if (WindowMapping [hwnd.Handle] != null) {
- DisposeWindow ((IntPtr)(WindowMapping [hwnd.Handle]));
+ if (hwnd == null) {
+ return;
+ }
+
+ SendParentNotify (hwnd.Handle, Msg.WM_DESTROY, int.MaxValue, int.MaxValue);
+
+ CleanupCachedWindows (hwnd);
+
+ ArrayList windows = new ArrayList ();
+
+ AccumulateDestroyedHandles (Control.ControlNativeWindow.ControlFromHandle(hwnd.Handle), windows);
+
+
+ foreach (Hwnd h in windows) {
+ SendMessage (h.Handle, Msg.WM_DESTROY, IntPtr.Zero, IntPtr.Zero);
+ h.zombie = true;
}
- CFRelease (hwnd.ClientWindow);
- CFRelease (hwnd.WholeWindow);
+
+/*
+ if (hwnd.whole_window != IntPtr.Zero)
+ CFRelease (hwnd.whole_window);
+ if (hwnd.client_window != IntPtr.Zero)
+ CFRelease (hwnd.client_window);
+*/
+ if (WindowMapping [hwnd.Handle] != null)
+ DisposeWindow ((IntPtr)(WindowMapping [hwnd.Handle]));
}
internal override IntPtr DispatchMessage(ref MSG msg) {
}
internal override void EndLoop(Thread thread) {
- throw new NotImplementedException();
}
internal void Exit() {
GetMessageResult = false;
- ExitToShell ();
+ //ExitToShell ();
}
internal override IntPtr GetActive() {
[MonoTODO]
internal override void GetCursorInfo(IntPtr cursor, out int width, out int height, out int hotspot_x, out int hotspot_y) {
- throw new NotImplementedException ();
+ width = 12;
+ height = 12;
+ hotspot_x = 0;
+ hotspot_y = 0;
}
internal override void GetDisplaySize(out Size size) {
Hwnd hwnd;
hwnd = Hwnd.ObjectFromHandle(handle);
- if (hwnd != null && hwnd.parent != null) {
- return hwnd.parent.Handle;
+ if (hwnd != null && hwnd.Parent != null) {
+ return hwnd.Parent.Handle;
}
return IntPtr.Zero;
}
return true;
}
- [MonoTODO]
- internal override Point GetMenuOrigin(IntPtr hwnd) {
- throw new NotImplementedException();
+ internal override Point GetMenuOrigin(IntPtr handle) {
+ Hwnd hwnd;
+
+ hwnd = Hwnd.ObjectFromHandle(handle);
+
+ if (hwnd != null) {
+ return hwnd.MenuOrigin;
+ }
+ return Point.Empty;
}
internal override bool GetMessage(object queue_id, ref MSG msg, IntPtr hWnd, int wFilterMin, int wFilterMax) {
IntPtr evtRef = IntPtr.Zero;
IntPtr target = GetEventDispatcherTarget();
- CheckTimers (DateTime.Now);
+ CheckTimers (DateTime.UtcNow);
ReceiveNextEvent (0, IntPtr.Zero, 0, true, ref evtRef);
if (evtRef != IntPtr.Zero && target != IntPtr.Zero) {
SendEventToEventTarget (evtRef, target);
}
internal override FormWindowState GetWindowState(IntPtr hwnd) {
- IntPtr window = GetControlOwner (hwnd);
+ IntPtr window = HIViewGetWindow (hwnd);
if (IsWindowCollapsed (window))
return FormWindowState.Minimized;
}
internal override void Invalidate (IntPtr handle, Rectangle rc, bool clear) {
- Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
-
- if (hwnd.visible && HIViewIsVisible (handle)) {
- MSG msg = new MSG ();
- msg.hwnd = hwnd.Handle;
- msg.wParam = IntPtr.Zero;
- msg.lParam = IntPtr.Zero;
- msg.message = Msg.WM_PAINT;
- MessageQueue.Enqueue (msg);
- // This is currently causing some graphics corruption
- //hwnd.AddInvalidArea (rc.X, rc.Y, rc.Width, rc.Height);
- hwnd.AddInvalidArea (0, 0, hwnd.ClientRect.Width, hwnd.ClientRect.Height);
- hwnd.expose_pending = true;
- }
+ Hwnd hwnd;
+
+ hwnd = Hwnd.ObjectFromHandle(handle);
+
+ if (clear) {
+ AddExpose (hwnd, true, hwnd.X, hwnd.Y, hwnd.Width, hwnd.Height);
+ } else {
+ AddExpose (hwnd, true, rc.X, rc.Y, rc.Width, rc.Height);
+ }
}
internal override void InvalidateNC (IntPtr handle)
{
- // XXX FIXME
+ Hwnd hwnd;
+
+ hwnd = Hwnd.ObjectFromHandle(handle);
+
+ AddExpose (hwnd, false, 0, 0, hwnd.Width, hwnd.Height);
}
internal override bool IsEnabled(IntPtr handle) {
TimerList.Remove(timer);
}
}
-
- internal override void MenuToScreen(IntPtr handle, ref int x, ref int y) {
- CGPoint pt = new CGPoint ();
- Rect wBounds = new Rect ();
- Hwnd hwnd;
-
- hwnd = Hwnd.ObjectFromHandle(handle);
-
- pt.x = x;
- pt.y = y;
- GetWindowBounds (GetControlOwner (hwnd.whole_window), 32, ref wBounds);
- HIViewConvertPoint (ref pt, handle, IntPtr.Zero);
-
- x = (int)(pt.x+wBounds.left);
- y = (int)(pt.y+wBounds.top);
- }
[MonoTODO]
internal override void OverrideCursor(IntPtr cursor) {
HideCaret();
}
- Graphics dc = Graphics.FromHwnd (paint_hwnd.client_window);
- paint_event = new PaintEventArgs(dc, hwnd.Invalid);
+ Graphics dc;
+
+ if (client) {
+ dc = Graphics.FromHwnd (paint_hwnd.client_window);
+
+ Region clip_region = new Region ();
+ clip_region.MakeEmpty();
+
+ foreach (Rectangle r in hwnd.ClipRectangles) {
+ clip_region.Union (r);
+ }
+
+ if (hwnd.UserClip != null) {
+ clip_region.Intersect(hwnd.UserClip);
+ }
+
+// dc.Clip = clip_region;
+ paint_event = new PaintEventArgs(dc, hwnd.Invalid);
+#if OptimizeDrawing
+ hwnd.expose_pending = false;
+#endif
+ hwnd.ClearInvalidArea();
- hwnd.expose_pending = false;
- hwnd.ClearInvalidArea();
+ hwnd.drawing_stack.Push (paint_event);
+ hwnd.drawing_stack.Push (dc);
+ } else {
+ dc = Graphics.FromHwnd (paint_hwnd.whole_window);
+
+ if (!hwnd.nc_invalid.IsEmpty) {
+ dc.SetClip (hwnd.nc_invalid);
+ paint_event = new PaintEventArgs(dc, hwnd.nc_invalid);
+ } else {
+ paint_event = new PaintEventArgs(dc, new Rectangle(0, 0, hwnd.width, hwnd.height));
+ }
+#if OptimizeDrawing
+ hwnd.nc_expose_pending = false;
+#endif
+ hwnd.ClearNcInvalidArea ();
- hwnd.drawing_stack.Push (dc);
+ hwnd.drawing_stack.Push (paint_event);
+ hwnd.drawing_stack.Push (dc);
+ }
return paint_event;
}
dc.Flush ();
dc.Dispose ();
+ PaintEventArgs pe = (PaintEventArgs)hwnd.drawing_stack.Pop();
+ pe.SetGraphics (null);
+ pe.Dispose ();
+
if (Caret.Visible == 1) {
ShowCaret();
Caret.Paused = false;
}
internal override bool PeekMessage(Object queue_id, ref MSG msg, IntPtr hWnd, int wFilterMin, int wFilterMax, uint flags) {
- Console.WriteLine("XplatUIOSX.PeekMessage");
return true;
}
return true;
}
- [MonoTODO]
internal override void PostQuitMessage(int exitCode) {
- throw new NotImplementedException();
+ PostMessage (FosterParent, Msg.WM_QUIT, IntPtr.Zero, IntPtr.Zero);
}
- [MonoTODO]
internal override void RequestAdditionalWM_NCMessages(IntPtr hwnd, bool hover, bool leave) {
- throw new NotImplementedException();
}
- [MonoTODO]
internal override void RequestNCRecalc(IntPtr handle) {
- throw new NotImplementedException();
+ Hwnd hwnd;
+
+ hwnd = Hwnd.ObjectFromHandle(handle);
+
+ if (hwnd == null) {
+ return;
+ }
+
+ PerformNCCalc(hwnd);
+ SendMessage(handle, Msg.WM_WINDOWPOSCHANGED, IntPtr.Zero, IntPtr.Zero);
+ InvalidateNC(handle);
}
[MonoTODO]
}
internal override void ScreenToClient(IntPtr handle, ref int x, ref int y) {
- CGPoint pt = new CGPoint ();
- Rect wBounds = new Rect ();
+ Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
- GetWindowBounds (GetControlOwner (handle), 32, ref wBounds);
- pt.x = (x-wBounds.left);
- pt.y = (y-wBounds.top);
- HIViewConvertPoint (ref pt, IntPtr.Zero, handle);
+ Point point = ConvertScreenPointToClient (hwnd.ClientWindow, new Point (x, y));
- x = (int)pt.x;
- y = (int)pt.y;
+ x = point.X;
+ y = point.Y;
}
- [MonoTODO]
internal override void ScreenToMenu(IntPtr handle, ref int x, ref int y) {
- CGPoint pt = new CGPoint ();
- Rect wBounds = new Rect ();
+ Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
- GetWindowBounds (GetControlOwner (handle), 32, ref wBounds);
- pt.x = (x-wBounds.left);
- pt.y = (y-wBounds.top);
- HIViewConvertPoint (ref pt, IntPtr.Zero, handle);
+ Point point = ConvertScreenPointToClient (hwnd.WholeWindow, new Point (x, y));
- x = (int)pt.x;
- y = (int)pt.y;
+ x = point.X;
+ y = point.Y;
}
internal override void ScrollWindow(IntPtr handle, Rectangle area, int XAmount, int YAmount, bool clear) {
- //IntPtr rect = IntPtr.Zero;
- //HIRect vBounds = new HIRect ();
-
- Hwnd hwnd = Hwnd.ObjectFromHandle(handle);
-
- /*
- if (hwnd.invalid != Rectangle.Empty) {
- // BIG FAT WARNING. This only works with how we use this function right now
- // where we basically still scroll the whole window, but work around areas
- // that are covered by our children
-
- hwnd.invalid.X += XAmount;
- hwnd.invalid.Y += YAmount;
-
- if (hwnd.invalid.X < 0) {
- hwnd.invalid.Width += hwnd.invalid.X;
- hwnd.invalid.X =0;
- }
-
- if (hwnd.invalid.Y < 0) {
- hwnd.invalid.Height += hwnd.invalid.Y;
- hwnd.invalid.Y =0;
- }
- }*/
-
- HIRect scrollrect = new HIRect ();
- scrollrect.origin.x = area.X;
- scrollrect.origin.y = area.Y;
- scrollrect.size.width = area.Width;
- scrollrect.size.height = area.Height;
- HIViewScrollRect (hwnd.Handle, ref scrollrect, (float)XAmount, (float)-YAmount);
- /*
- HIViewGetBounds (hwnd.client_window, ref vBounds);
- HIViewConvertRect (ref vBounds, hwnd.client_window, IntPtr.Zero);
- SetRect (ref rect, (short)(vBounds.origin.x+area.X), (short)(vBounds.origin.y-TitleBarHeight+area.Y), (short)(vBounds.origin.x+area.Width), (short)(vBounds.origin.y+area.Height-TitleBarHeight));
- ScrollRect (ref rect, (short)XAmount, (short)-YAmount, IntPtr.Zero);
- */
- // Generate an expose for the area exposed by the horizontal scroll
- /*
- if (XAmount > 0) {
- hwnd.AddInvalidArea (area.X, area.Y, XAmount, area.Height);
- } else if (XAmount < 0) {
- hwnd.AddInvalidArea (XAmount + area.X + area.Width, area.Y, -XAmount, area.Height);
- }
-
- // Generate an expose for the area exposed by the vertical scroll
- if (YAmount > 0) {
- hwnd.AddInvalidArea (area.X, area.Y, area.Width, YAmount);
- } else if (YAmount < 0) {
- hwnd.AddInvalidArea (area.X, YAmount + area.Y + area.Height, area.Width, -YAmount);
- }
-
- UpdateWindow (handle);
- */
+ HIRect scroll_rect = new HIRect ();
+ scroll_rect.origin.x = area.X;
+ scroll_rect.origin.y = area.Y;
+ scroll_rect.size.width = area.Width;
+ scroll_rect.size.height = area.Height;
+ HIViewScrollRect (handle, ref scroll_rect, (float)XAmount, (float)-YAmount);
}
internal override void ScrollWindow(IntPtr hwnd, int XAmount, int YAmount, bool clear) {
- throw new NotImplementedException("");
+ HIRect scroll_rect = new HIRect ();
+
+ HIViewGetBounds (hwnd, ref scroll_rect);
+ HIViewScrollRect (hwnd, ref scroll_rect, (float)XAmount, (float)-YAmount);
}
[MonoTODO]
[MonoTODO]
internal override IntPtr SendMessage (IntPtr hwnd, Msg message, IntPtr wParam, IntPtr lParam) {
- throw new NotImplementedException ();
+ return NativeWindow.WndProc(hwnd, message, wParam, lParam);
}
internal override int SendInput(IntPtr hwnd, Queue keys) {
}
internal override void SetCursor(IntPtr window, IntPtr cursor) {
- SetThemeCursor ((uint) cursor);
+ Hwnd hwnd = Hwnd.ObjectFromHandle (window);
+
+ if (hwnd.Handle == window)
+ hwnd.ClientCursor = cursor;
+ else
+ hwnd.WholeCursor = cursor;
}
internal override void SetCursorPos(IntPtr handle, int x, int y) {
FocusWindow = handle;
}
- [MonoTODO]
internal override void SetIcon(IntPtr handle, Icon icon) {
- throw new NotImplementedException();
+ Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
+
+ // FIXME: we need to map the icon for active window switches
+ if (WindowMapping [hwnd.Handle] != null) {
+ if (icon == null) {
+ RestoreApplicationDockTileImage ();
+ } else {
+ Bitmap bitmap;
+ int size;
+ IntPtr[] data;
+ int index;
+
+ bitmap = new Bitmap (128, 128);
+ using (Graphics g = Graphics.FromImage (bitmap)) {
+ g.DrawImage (icon.ToBitmap (), 0, 0, 128, 128);
+ }
+ index = 0;
+ size = bitmap.Width * bitmap.Height;
+ data = new IntPtr[size];
+
+ for (int y = 0; y < bitmap.Height; y++) {
+ for (int x = 0; x < bitmap.Width; x++) {
+ int pixel = bitmap.GetPixel (x, y).ToArgb ();
+ byte a = (byte) ((pixel >> 24) & 0xFF);
+ byte r = (byte) ((pixel >> 16) & 0xFF);
+ byte g = (byte) ((pixel >> 8) & 0xFF);
+ byte b = (byte) (pixel & 0xFF);
+ data[index++] = (IntPtr)(a + (r << 8) + (g << 16) + (b << 24));
+ }
+ }
+
+ IntPtr provider = CGDataProviderCreateWithData (IntPtr.Zero, data, size*4, IntPtr.Zero);
+Console.WriteLine (provider);
+ IntPtr image = CGImageCreate (128, 128, 8, 32, 4*128, CGColorSpaceCreateDeviceRGB (), 4, provider, IntPtr.Zero, 0, 0);
+Console.WriteLine (image);
+ SetApplicationDockTileImage (image);
+ }
+ }
}
internal override void SetModal(IntPtr handle, bool Modal) {
- IntPtr hWnd = GetControlOwner (Hwnd.ObjectFromHandle (handle).WholeWindow);
+ IntPtr hWnd = HIViewGetWindow (Hwnd.ObjectFromHandle (handle).WholeWindow);
if (Modal)
BeginAppModalStateForWindow (hWnd);
else
internal override IntPtr SetParent(IntPtr handle, IntPtr parent) {
Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
- hwnd.parent = Hwnd.ObjectFromHandle (parent);
+ hwnd.Parent = Hwnd.ObjectFromHandle (parent);
if (HIViewGetSuperview (hwnd.whole_window) != IntPtr.Zero) {
CheckError (HIViewRemoveFromSuperview (hwnd.whole_window), "HIViewRemoveFromSuperview ()");
}
- CheckError (HIViewAddSubview (hwnd.parent.client_window, hwnd.whole_window));
+ CheckError (HIViewAddSubview (hwnd.Parent.client_window, hwnd.whole_window));
+ HIViewPlaceInSuperviewAt (hwnd.whole_window, hwnd.X, hwnd.Y);
CheckError (HIViewAddSubview (hwnd.whole_window, hwnd.client_window));
HIViewPlaceInSuperviewAt (hwnd.client_window, hwnd.ClientRect.X, hwnd.ClientRect.Y);
}
internal override void SetBorderStyle(IntPtr handle, FormBorderStyle border_style) {
- Hwnd hwnd;
-
- hwnd = Hwnd.ObjectFromHandle(handle);
- hwnd.border_style = border_style;
+ Form form = Control.FromHandle (handle) as Form;
+ if (form != null && form.window_manager == null && (border_style == FormBorderStyle.FixedToolWindow ||
+ border_style == FormBorderStyle.SizableToolWindow)) {
+ form.window_manager = new ToolWindowManager (form);
+ }
- // FIXME - do we need to trigger some resize?
+ RequestNCRecalc(handle);
}
internal override void SetMenu(IntPtr handle, Menu menu) {
hwnd = Hwnd.ObjectFromHandle(handle);
hwnd.menu = menu;
- // FIXME - do we need to trigger some resize?
+ RequestNCRecalc(handle);
}
internal override void SetWindowMinMax(IntPtr handle, Rectangle maximized, Size min, Size max) {
- throw new NotImplementedException();
}
internal override void SetWindowPos(IntPtr handle, int x, int y, int width, int height) {
Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
- Rectangle client_rect = hwnd.GetClientRectangle (width, height);
+
+ if (hwnd == null) {
+ return;
+ }
+
+ if (width < 0) width = 0;
+ if (height < 0) height = 0;
// Save a server roundtrip (and prevent a feedback loop)
if ((hwnd.x == x) && (hwnd.y == y) && (hwnd.width == width) && (hwnd.height == height)) {
return;
}
+ hwnd.x = x;
+ hwnd.y = y;
+ hwnd.width = width;
+ hwnd.height = height;
+ SendMessage(hwnd.client_window, Msg.WM_WINDOWPOSCHANGED, IntPtr.Zero, IntPtr.Zero);
+
+ Control ctrl = Control.FromHandle (handle);
+ Size TranslatedSize = TranslateWindowSizeToQuartzWindowSize (ctrl.GetCreateParams (), new Size (width, height));
+ Rect rect = new Rect ();
if (WindowMapping [hwnd.Handle] != null) {
- if (y <= MenuBarHeight+TitleBarHeight) {
- y+=MenuBarHeight+TitleBarHeight;
- }
- IntPtr rect = IntPtr.Zero;
- SetRect (ref rect, (short)x, (short)y, (short)(x+width), (short)(y+height));
- CheckError (SetWindowBounds ((IntPtr) WindowMapping [hwnd.Handle], 33, ref rect), "SetWindowBounds ()");
- HIRect r = new HIRect (0, 0, width, height);
- CheckError (HIViewSetFrame (hwnd.whole_window, ref r), "HIViewSetFrame ()");
- r = new HIRect (client_rect.X, client_rect.Y, client_rect.X+client_rect.Width, client_rect.Y+client_rect.Height);
- CheckError (HIViewSetFrame (hwnd.client_window, ref r), "HIViewSetFrame ()");
+ SetRect (ref rect, (short)x, (short)(y+MenuBarHeight), (short)(x+TranslatedSize.Width), (short)(y+MenuBarHeight+TranslatedSize.Height));
+ SetWindowBounds ((IntPtr) WindowMapping [hwnd.Handle], 33, ref rect);
+ HIRect frame_rect = new HIRect (0, 0, TranslatedSize.Width, TranslatedSize.Height);
+ HIViewSetFrame (hwnd.whole_window, ref frame_rect);
} else {
- HIRect r = new HIRect (x, y, width, height);
- CheckError (HIViewSetFrame (hwnd.whole_window, ref r), "HIViewSetFrame ()");
- r = new HIRect (client_rect.X, client_rect.Y, client_rect.X+client_rect.Width, client_rect.Y+client_rect.Height);
- CheckError (HIViewSetFrame (hwnd.client_window, ref r), "HIViewSetFrame ()");
- }
+ HIRect frame_rect = new HIRect (x, y, TranslatedSize.Width, TranslatedSize.Height);
+ HIViewSetFrame (hwnd.whole_window, ref frame_rect);
+ }
+ PerformNCCalc(hwnd);
+
+ hwnd.x = x;
+ hwnd.y = y;
+ hwnd.width = width;
+ hwnd.height = height;
}
internal override void SetWindowState(IntPtr hwnd, FormWindowState state) {
- IntPtr window = GetControlOwner (hwnd);
+ IntPtr window = HIViewGetWindow (hwnd);
switch (state) {
case FormWindowState.Minimized: {
}
internal override object StartLoop(Thread thread) {
- throw new NotImplementedException();
+ return new object ();
}
[MonoTODO]
internal override void UpdateWindow(IntPtr handle) {
Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
- if (hwnd.visible && HIViewIsVisible (handle) && !hwnd.expose_pending) {
+#if OptimizeDrawing
+ if (hwnd.visible && HIViewIsVisible (handle) && !hwnd.expose_pending) {
+#else
+ if (hwnd.visible && HIViewIsVisible (handle)) {
+#endif
MSG msg = new MSG ();
msg.message = Msg.WM_PAINT;
msg.hwnd = hwnd.Handle;
throw new NotImplementedException();
}
+ //FIXME: This isn't actually correct; its jsut something visual we can use now for debugging
internal override void DrawReversibleRectangle(IntPtr handle, Rectangle rect, int line_width) {
- throw new NotImplementedException();
+ Rect draw_rect = new Rect ();
+ IntPtr WindowHandle = HIViewGetWindow (handle);
+
+ SetPortWindowPort (WindowHandle);
+ GetWindowPortBounds (WindowHandle, ref draw_rect);
+
+ draw_rect.top += (short)(rect.Y + TitleBarHeight);
+ draw_rect.left += (short)rect.X;
+ draw_rect.bottom = (short)(draw_rect.top + rect.Height);
+ draw_rect.right = (short)(draw_rect.left + rect.Width);
+ InvertRect (ref draw_rect);
}
[MonoTODO]
internal override int KeyboardSpeed { get{ throw new NotImplementedException(); } }
internal override int KeyboardDelay { get{ throw new NotImplementedException(); } }
- internal override int CaptionHeight { get{ throw new NotImplementedException(); } }
+ internal override int CaptionHeight {
+ get {
+ return 19;
+ }
+ }
+
internal override Size CursorSize { get{ throw new NotImplementedException(); } }
internal override bool DragFullWindows { get{ throw new NotImplementedException(); } }
internal override Size DragSize { get{ throw new NotImplementedException(); } }
- internal override Size FrameBorderSize { get{ throw new NotImplementedException(); } }
+
+ internal override Size FrameBorderSize {
+ get {
+ return new Size (2, 2);
+ }
+ }
+
internal override Size IconSize { get{ throw new NotImplementedException(); } }
internal override Size MaxWindowTrackSize { get{ throw new NotImplementedException(); } }
internal override bool MenuAccessKeysUnderlined {
return false;
}
}
- internal override Size MinimizedWindowSize { get{ throw new NotImplementedException(); } }
- internal override Size MinimizedWindowSpacingSize { get{ throw new NotImplementedException(); } }
- internal override Size MinimumWindowSize { get{ throw new NotImplementedException(); } }
- internal override Size MinWindowTrackSize { get{ throw new NotImplementedException(); } }
- internal override Size SmallIconSize { get{ throw new NotImplementedException(); } }
- internal override int MouseButtonCount { get{ throw new NotImplementedException(); } }
- internal override bool MouseButtonsSwapped { get{ throw new NotImplementedException(); } }
- internal override bool MouseWheelPresent { get{ throw new NotImplementedException(); } }
- internal override Rectangle VirtualScreen { get{ throw new NotImplementedException(); } }
- internal override Rectangle WorkingArea {
+ internal override Size MinimizedWindowSize { get{ throw new NotImplementedException(); } }
+ internal override Size MinimizedWindowSpacingSize { get{ throw new NotImplementedException(); } }
+ internal override Size MinimumWindowSize { get{ throw new NotImplementedException(); } }
+ internal override Size MinWindowTrackSize { get{ throw new NotImplementedException(); } }
+ internal override Size SmallIconSize { get{ throw new NotImplementedException(); } }
+ internal override int MouseButtonCount { get{ throw new NotImplementedException(); } }
+ internal override bool MouseButtonsSwapped { get{ throw new NotImplementedException(); } }
+ internal override bool MouseWheelPresent { get{ throw new NotImplementedException(); } }
+
+ internal override Rectangle VirtualScreen {
+ get {
+ return WorkingArea;
+ }
+ }
+
+ internal override Rectangle WorkingArea {
get {
HIRect bounds = CGDisplayBounds (CGMainDisplayID ());
return new Rectangle ((int)bounds.origin.x, (int)bounds.origin.y, (int)bounds.size.width, (int)bounds.size.height);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern int HIViewScrollRect (IntPtr vHnd, ref HIRect rect, float x, float y);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- internal static extern int HIViewScrollRect (IntPtr vHnd, IntPtr rect, float x, float y);
+ internal static extern int HIViewScrollRect (IntPtr vHnd, Rect rect, float x, float y);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern int HIViewSetZOrder (IntPtr hWnd, int cmd, IntPtr oHnd);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern int HIViewSetBoundsOrigin (IntPtr vHnd, float x, float y);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern int HIViewConvertRect (ref HIRect r, IntPtr a, IntPtr b);
+ [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern int HIViewNewTrackingArea (IntPtr inView, IntPtr inShape, UInt64 inID, ref IntPtr outRef);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- internal static extern void ScrollRect (ref IntPtr r, short dh, short dv, IntPtr rgnHandle);
+ internal static extern void ScrollRect (ref Rect r, short dh, short dv, IntPtr rgnHandle);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- internal static extern void SetRect (ref IntPtr r, short left, short top, short right, short bottom);
+ internal static extern void SetRect (ref Rect r, short left, short top, short right, short bottom);
- //[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- //static extern int CreateEvent (IntPtr allocator, uint classid, uint kind, double when, uint attributes, ref IntPtr outEvent);
[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- static extern int InstallEventHandler (IntPtr window, CarbonEventDelegate handlerProc, uint numtypes, EventTypeSpec [] typeList, IntPtr userData, IntPtr handlerRef);
+ static extern int InstallEventHandler (IntPtr window, CarbonEventDelegate handlerProc, uint numtypes, EventTypeSpec [] typeList, IntPtr userData, IntPtr handlerRef);
[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- internal static extern IntPtr GetControlOwner (IntPtr aView);
+ internal static extern IntPtr HIViewGetWindow (IntPtr aView);
[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
static extern int ActivateWindow (IntPtr windowHnd, bool inActivate);
[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern int EndAppModalStateForWindow (IntPtr window);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- internal static extern int CreateNewWindow (WindowClass klass, WindowAttributes attributes, ref IntPtr r, ref IntPtr window);
+ internal static extern int CreateNewWindow (WindowClass klass, WindowAttributes attributes, ref Rect r, ref IntPtr window);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern int DisposeWindow (IntPtr wHnd);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern int HideWindow (IntPtr wHnd);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- internal static extern int SetWindowBounds (IntPtr wHnd, uint reg, ref IntPtr rect);
+ internal static extern int SetWindowBounds (IntPtr wHnd, uint reg, ref Rect rect);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern int GetWindowPortBounds (IntPtr wHnd, ref Rect rect);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal extern static void SetThemeCursor (uint inCursor);
#endregion
- }
+ #region Windowing imports
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ private extern static int GetCurrentProcess (ref ProcessSerialNumber psn);
+ [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal extern static int TransformProcessType (ref ProcessSerialNumber psn, uint type);
+ [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal extern static int SetFrontProcess (ref ProcessSerialNumber psn);
+ #endregion
+
+ #region Dock tile imports
+ [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal extern static IntPtr CGColorSpaceCreateDeviceRGB();
+ [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal extern static IntPtr CGDataProviderCreateWithData (IntPtr info, IntPtr [] data, int size, IntPtr releasefunc);
+ [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal extern static IntPtr CGImageCreate (int width, int height, int bitsPerComponent, int bitsPerPixel, int bytesPerRow, IntPtr colorspace, uint bitmapInfo, IntPtr provider, IntPtr decode, int shouldInterpolate, int intent);
+ [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal extern static void SetApplicationDockTileImage(IntPtr imageRef);
+ [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal extern static void RestoreApplicationDockTileImage();
+ #endregion
+ }
}
[Test]\r
public void Constructor ()\r
{\r
- NullButton b = new NullButton ();\r
+ MockButton b = new MockButton ();\r
\r
Assert.AreEqual (SystemColors.Control, b.BackColor, "A4");\r
Assert.AreEqual (FlatStyle.Standard, b.FlatStyle, "A6");\r
- Assert.AreEqual (null, b.Image, "A7");\r
+ Assert.IsNull (b.Image, "A7");\r
Assert.AreEqual (ContentAlignment.MiddleCenter, b.ImageAlign, "A8");\r
Assert.AreEqual (-1, b.ImageIndex, "A9");\r
- Assert.AreEqual (null, b.ImageList, "A11");\r
+ Assert.IsNull (b.ImageList, "A11");\r
Assert.AreEqual (ImeMode.Disable, b.ImeMode, "A12");\r
Assert.AreEqual (string.Empty, b.Text, "A13");\r
Assert.AreEqual (ContentAlignment.MiddleCenter, b.TextAlign, "A14");\r
\r
#if NET_2_0\r
- Assert.AreEqual (false, b.AutoEllipsis, "A1");\r
- Assert.AreEqual (false, b.AutoSize, "A2");\r
+ Assert.IsFalse (b.AutoEllipsis, "A1");\r
+ Assert.IsFalse (b.AutoSize, "A2");\r
Assert.AreEqual (string.Empty, b.ImageKey, "A10");\r
Assert.AreEqual (TextImageRelation.Overlay, b.TextImageRelation, "A15");\r
- Assert.AreEqual (true, b.UseCompatibleTextRendering, "A16");\r
- Assert.AreEqual (true, b.UseMnemonic, "A17");\r
- Assert.AreEqual (true, b.UseVisualStyleBackColor, "A18");\r
+ Assert.IsTrue (b.UseCompatibleTextRendering, "A16");\r
+ Assert.IsTrue (b.UseMnemonic, "A17");\r
+ Assert.IsTrue (b.UseVisualStyleBackColor, "A18");\r
Assert.AreEqual (AccessibleStates.None, b.AccessibilityObject.State, "A19");\r
#endif\r
}\r
+\r
+ [Test]\r
+ public void IsDefault ()\r
+ {\r
+ MockButton b = new MockButton ();\r
+ Assert.IsFalse (b.IsDefault, "#1");\r
+ b.IsDefault = true;\r
+ Assert.IsTrue (b.IsDefault, "#2");\r
+ b.IsDefault = false;\r
+ Assert.IsFalse (b.IsDefault, "#3");\r
+ }\r
\r
- private class NullButton : ButtonBase\r
+ private class MockButton : ButtonBase\r
{\r
+ public new bool IsDefault {\r
+ get { return base.IsDefault; }\r
+ set { base.IsDefault = value; }\r
+ }\r
}\r
}\r
}\r
+2007-10-16 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * ButtonBaseTest.cs: Added test for IsDefault.
+ * FormTest.cs: Added test for AcceptButton. Commented out CWLs.
+
+2007-10-13 Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+ * ListViewItemTest.cs: New tests for focused state. Also,
+ comment a new ones, as they don't work by now, but should work
+ as soon as we fix an issue there.
+
2007-10-13 Gert Driesen <drieseng@users.sourceforge.net>
* RichTextBoxTest.cs: Added tests for negative SelectionLength and
[TestFixture]
public class FormTest
{
+ [Test]
+ public void AcceptButton ()
+ {
+ Form form = new Form ();
+ Assert.IsNull (form.AcceptButton, "#A");
+
+ MockButton buttonA = new MockButton (true);
+ Assert.IsFalse (buttonA.IsDefaultButton, "#B1");
+ form.AcceptButton = buttonA;
+ Assert.IsNotNull (form.AcceptButton, "#B2");
+ Assert.AreSame (buttonA, form.AcceptButton, "#B3");
+ Assert.IsTrue (buttonA.IsDefaultButton, "#B4");
+
+ form.AcceptButton = null;
+ Assert.IsNull (form.AcceptButton, "#C1");
+ Assert.IsFalse (buttonA.IsDefaultButton, "#C2");
+
+ ButtonControl buttonB = new ButtonControl ();
+ Assert.IsFalse (buttonB.IsDefaultButton, "#D1");
+ form.AcceptButton = buttonB;
+ Assert.IsNotNull (form.AcceptButton, "#D2");
+ Assert.AreSame (buttonB, form.AcceptButton, "#D3");
+ Assert.IsFalse (buttonA.IsDefaultButton, "#D4");
+ Assert.IsTrue (buttonB.IsDefaultButton, "#D5");
+
+ MockButton buttonC = new MockButton (false);
+ Assert.IsFalse (buttonC.IsDefaultButton, "#E1");
+ form.AcceptButton = buttonC;
+ Assert.IsNotNull (form.AcceptButton, "#E2");
+ Assert.AreSame (buttonC, form.AcceptButton, "#E3");
+ Assert.IsFalse (buttonC.IsDefaultButton, "#E4");
+ Assert.IsFalse (buttonA.IsDefaultButton, "#E5");
+ Assert.IsFalse (buttonB.IsDefaultButton, "#E6");
+ }
+
[Test]
public void bug_82358 ()
{
- Console.WriteLine ("Starting bug_82358");
+ //Console.WriteLine ("Starting bug_82358");
int sizeable_factor;
int title_bar;
int tool_bar;
FormBorderStyle style;
- Console.WriteLine ("Universal theme says: d2={0}, d3={1}, title_bar={2}, sizeable_factor={3}, tool_border={4}, tool_bar={5}", d2, d3, title_bar, sizeable_factor, tool_border, tool_bar);
+ //Console.WriteLine ("Universal theme says: d2={0}, d3={1}, title_bar={2}, sizeable_factor={3}, tool_border={4}, tool_bar={5}", d2, d3, title_bar, sizeable_factor, tool_border, tool_bar);
// Changing client size, then FormBorderStyle.
using (Form f = new Form ()) {
style = FormBorderStyle.FixedToolWindow;
- Console.WriteLine ("Created form, size: {0}, clientsize: {1}", f.Size, f.ClientSize);
+ //Console.WriteLine ("Created form, size: {0}, clientsize: {1}", f.Size, f.ClientSize);
f.ClientSize = size;
- Console.WriteLine ("Changed ClientSize, size: {0}, clientsize: {1}", f.Size, f.ClientSize);
+ //Console.WriteLine ("Changed ClientSize, size: {0}, clientsize: {1}", f.Size, f.ClientSize);
f.FormBorderStyle = style;
- Console.WriteLine ("Changed FormBorderStyle, size: {0}, clientsize: {1}", f.Size, f.ClientSize);
+ //Console.WriteLine ("Changed FormBorderStyle, size: {0}, clientsize: {1}", f.Size, f.ClientSize);
Assert.AreEqual (size.ToString (), f.ClientSize.ToString (), style.ToString () + "-A1");
Assert.AreEqual (new Size (size.Width + tool_border, size.Height + tool_border + tool_bar).ToString (), f.Size.ToString (), style.ToString () + "-A2");
f.Visible = true;
- Console.WriteLine ("Made visible, size: {0}, clientsize: {1}", f.Size, f.ClientSize);
+ //Console.WriteLine ("Made visible, size: {0}, clientsize: {1}", f.Size, f.ClientSize);
Assert.AreEqual (size.ToString (), f.ClientSize.ToString (), style.ToString () + "-A3");
Assert.AreEqual (new Size (size.Width + tool_border, size.Height + tool_border + tool_bar).ToString (), f.Size.ToString (), style.ToString () + "-A4");
}
{
((Form) sender).Close ();
}
-
-
-
+
[Test]
public void ShowDialogCloseTest ()
{
cp = TestHelper.GetCreateParams (frm);
Assert.AreEqual (FormStartPosition.WindowsDefaultLocation, frm.StartPosition, "$A6");
Assert.AreEqual (new Point (int.MinValue, int.MinValue).ToString (), new Point (cp.X, cp.Y).ToString (), "#A6");
-
-
}
}
frm.Show ();
}
-
using (Form frm = new Form ()) {
frm.MdiParent = Main;
frm.Location = new Point (23, 45);
frm.Show ();
}
-
-
using (Form frm = new Form ()) {
frm.MdiParent = Main;
frm.Location = new Point (34, 56);
frm.Show ();
}
-
using (Form frm = new Form ()) {
frm.TopLevel = false;
Main.Controls.Add (frm);
frm.Show ();
}
-
-
using (Form frm = new Form ()) {
frm.TopLevel = false;
Main.Controls.Add (frm);
frm.Show ();
}
-
Main.Size = new Size (600, 600);
using (Form frm = new Form ()) {
frm.TopLevel = false;
myform.Visible = true;
myform.Text = "NewForm";
myform.Name = "FormTest";
- Assert.IsNull (myform.AcceptButton, "#1");
Assert.IsNull (myform.ActiveMdiChild, "#2");
Assert.IsFalse (myform.AutoScale, "#3");
Assert.IsNull (myform.CancelButton, "#6");
tv.GotFocus += new EventHandler (tv_GotFocus);
f.Activated += new EventHandler (f_Activated);
f.Controls.Add (tv);
- Console.WriteLine ("****************** STARTING ************************");
+ //Console.WriteLine ("****************** STARTING ************************");
f.Show ();
- Console.WriteLine ("****************** ENDED ************************");
+ //Console.WriteLine ("****************** ENDED ************************");
- Console.WriteLine (log.EventsJoined ());
+ //Console.WriteLine (log.EventsJoined ());
Assert.IsTrue (log.EventRaised ("GotFocus"), "#01");
}
}
void f_Activated (object sender, EventArgs e)
{
- Console.WriteLine (" ACTIVATED");
- Console.WriteLine (Environment.StackTrace);
+ //Console.WriteLine (" ACTIVATED");
+ //Console.WriteLine (Environment.StackTrace);
}
void tv_GotFocus (object sender, EventArgs e)
{
- Console.WriteLine (Environment.StackTrace);
+ //Console.WriteLine (Environment.StackTrace);
}
[Test] // Bug #80773
private bool _closeOnLoad;
private bool _visibleOnLoad;
- }
+ }
+
+ private class MockButton : Button
+ {
+ public MockButton (bool notify)
+ {
+ _notify = notify;
+ }
+
+ public bool Notify {
+ get { return _notify; }
+ set { _notify = value; }
+ }
+
+ public bool IsDefaultButton
+ {
+ get { return base.IsDefault; }
+ set { base.IsDefault = value; }
+ }
+
+ public override void NotifyDefault (bool value)
+ {
+ if (Notify)
+ base.NotifyDefault (value);
+ }
+
+ private bool _notify;
+ }
+
+ private class ButtonControl : IButtonControl
+ {
+ public DialogResult DialogResult {
+ get { return _dialogResult; }
+ set { _dialogResult = value; }
+ }
+
+ public bool IsDefaultButton {
+ get { return _isDefault; }
+ }
+
+ public void NotifyDefault (bool value)
+ {
+ _isDefault = value;
+ }
+
+ public void PerformClick ()
+ {
+ }
+
+ private bool _isDefault;
+ private DialogResult _dialogResult = DialogResult.None;
+ }
}
public class TimeBombedForm : Form
Assert.IsFalse (item3.Focused, "#D3");
Assert.IsNull (lv.FocusedItem, "#D4");
+ // Test Focused for Items without owner
+ ListViewItem item4 = new ListViewItem ();
+ Assert.IsFalse (item4.Focused);
+ item4.Focused = true;
+
+ Assert.IsFalse (item4.Focused, "#E1");
+
form.Dispose ();
}
[Test]
public void ListViewItemTestClone ()
{
- ListViewItem item1 = new ListViewItem ("Hello");
+ Form f = new Form ();
+ ListView lv = new ListView ();
+ lv.Parent = f;
+
+ ListViewItem item1 = lv.Items.Add ("Hello");
item1.ForeColor = Color.Blue;
item1.BackColor = Color.Red;
item1.Font = new Font ("Arial", 14);
item1.ToolTipText = item1.Text;
#endif
+ f.Show ();
+
ListViewItem item2 = (ListViewItem) item1.Clone ();
Assert.AreEqual (Color.Blue, item2.ForeColor, "#1");
Assert.AreEqual (Color.Red, item2.BackColor, "#2");
#if NET_2_0
Assert.AreEqual (item1.ToolTipText, item2.ToolTipText, "#8");
#endif
+ // Focused is not copied
+ // These tests shoule be re-enabled when #333693
+ /*Assert.IsTrue (item1.Focused, "#9");
+ Assert.IsFalse (item2.Focused, "#10");*/
+
+ f.Dispose ();
}
#if NET_2_0
<Reference Include="System">
<Name>System</Name>
</Reference>
+ <Reference Include="System.configuration" />
<Reference Include="System.Data">
<Name>System.Data</Name>
</Reference>
+2007-10-18 Jb Evain <jbevain@novell.com>
+
+ * Mono.Cecil.Cil/MethodBody.cs: Add an Optimize method which
+ is the opposite of Simplify. Based on a patch by Carlo.
+
+ * Mono.Cecil.Cil/CodeWriter.cs: don't care about reducing MaxStack.
+
2007-10-11 Jb Evain <jbevain@novell.com>
* Mono.Cecil/TypeReference.cs: add a IsNested helper property.
}
}
- int max = 0, current = 0;
+ int max = 0;
foreach (Instruction instr in instructions) {
-
if (ehs.Contains (instr))
- current++;
+ max++;
switch (instr.OpCode.StackBehaviourPush) {
case StackBehaviour.Push1:
case StackBehaviour.Pushr8:
case StackBehaviour.Pushref:
case StackBehaviour.Varpush:
- current++;
+ max++;
break;
case StackBehaviour.Push1_push1:
- current += 2;
+ max += 2;
break;
}
- if (max < current)
- max = current;
-
- switch (instr.OpCode.StackBehaviourPop) {
- case StackBehaviour.Varpop:
- break;
- case StackBehaviour.Pop1:
- case StackBehaviour.Popi:
- case StackBehaviour.Popref:
- current--;
- break;
- case StackBehaviour.Pop1_pop1:
- case StackBehaviour.Popi_pop1:
- case StackBehaviour.Popi_popi:
- case StackBehaviour.Popi_popi8:
- case StackBehaviour.Popi_popr4:
- case StackBehaviour.Popi_popr8:
- case StackBehaviour.Popref_pop1:
- case StackBehaviour.Popref_popi:
- current -= 2;
- break;
- case StackBehaviour.Popi_popi_popi:
- case StackBehaviour.Popref_popi_popi:
- case StackBehaviour.Popref_popi_popi8:
- case StackBehaviour.Popref_popi_popr4:
- case StackBehaviour.Popref_popi_popr8:
- case StackBehaviour.Popref_popi_popref:
- current -= 3;
- break;
+ if (instr.OpCode.OperandType == OperandType.InlineMethod) {
+ IMethodSignature signature = instr.Operand as IMethodSignature;
+ if (signature != null && signature.ReturnType.ReturnType.FullName != Constants.Void)
+ max++;
}
-
- if (current < 0)
- current = 0;
}
instructions.Container.MaxStack = max;
return nb;
}
- public void Simplify ()
+ public void Modify ()
{
foreach (Instruction i in this.Instructions) {
if (i.OpCode.OpCodeType != OpCodeType.Macro)
switch (i.OpCode.Code) {
case Code.Ldarg_0 :
- Simplify (i, OpCodes.Ldarg,
+ Modify (i, OpCodes.Ldarg,
CodeReader.GetParameter (this, 0));
break;
case Code.Ldarg_1 :
- Simplify (i, OpCodes.Ldarg,
+ Modify (i, OpCodes.Ldarg,
CodeReader.GetParameter (this, 1));
break;
case Code.Ldarg_2 :
- Simplify (i, OpCodes.Ldarg,
+ Modify (i, OpCodes.Ldarg,
CodeReader.GetParameter (this, 2));
break;
case Code.Ldarg_3 :
- Simplify (i, OpCodes.Ldarg,
+ Modify (i, OpCodes.Ldarg,
CodeReader.GetParameter (this, 3));
break;
case Code.Ldloc_0 :
- Simplify (i, OpCodes.Ldloc,
+ Modify (i, OpCodes.Ldloc,
CodeReader.GetVariable (this, 0));
break;
case Code.Ldloc_1 :
- Simplify (i, OpCodes.Ldloc,
+ Modify (i, OpCodes.Ldloc,
CodeReader.GetVariable (this, 1));
break;
case Code.Ldloc_2 :
- Simplify (i, OpCodes.Ldloc,
+ Modify (i, OpCodes.Ldloc,
CodeReader.GetVariable (this, 2));
break;
case Code.Ldloc_3 :
- Simplify (i, OpCodes.Ldloc,
+ Modify (i, OpCodes.Ldloc,
CodeReader.GetVariable (this, 3));
break;
case Code.Stloc_0 :
- Simplify (i, OpCodes.Stloc,
+ Modify (i, OpCodes.Stloc,
CodeReader.GetVariable (this, 0));
break;
case Code.Stloc_1 :
- Simplify (i, OpCodes.Stloc,
+ Modify (i, OpCodes.Stloc,
CodeReader.GetVariable (this, 1));
break;
case Code.Stloc_2 :
- Simplify (i, OpCodes.Stloc,
+ Modify (i, OpCodes.Stloc,
CodeReader.GetVariable (this, 2));
break;
case Code.Stloc_3 :
- Simplify (i, OpCodes.Stloc,
+ Modify (i, OpCodes.Stloc,
CodeReader.GetVariable (this, 3));
break;
case Code.Ldarg_S :
i.OpCode = OpCodes.Stloc;
break;
case Code.Ldc_I4_M1 :
- Simplify (i, OpCodes.Ldc_I4, -1);
+ Modify (i, OpCodes.Ldc_I4, -1);
break;
case Code.Ldc_I4_0 :
- Simplify (i, OpCodes.Ldc_I4, 0);
+ Modify (i, OpCodes.Ldc_I4, 0);
break;
case Code.Ldc_I4_1 :
- Simplify (i, OpCodes.Ldc_I4, 1);
+ Modify (i, OpCodes.Ldc_I4, 1);
break;
case Code.Ldc_I4_2 :
- Simplify (i, OpCodes.Ldc_I4, 2);
+ Modify (i, OpCodes.Ldc_I4, 2);
break;
case Code.Ldc_I4_3 :
- Simplify (i, OpCodes.Ldc_I4, 3);
+ Modify (i, OpCodes.Ldc_I4, 3);
break;
case Code.Ldc_I4_4 :
- Simplify (i, OpCodes.Ldc_I4, 4);
+ Modify (i, OpCodes.Ldc_I4, 4);
break;
case Code.Ldc_I4_5 :
- Simplify (i, OpCodes.Ldc_I4, 5);
+ Modify (i, OpCodes.Ldc_I4, 5);
break;
case Code.Ldc_I4_6 :
- Simplify (i, OpCodes.Ldc_I4, 6);
+ Modify (i, OpCodes.Ldc_I4, 6);
break;
case Code.Ldc_I4_7 :
- Simplify (i, OpCodes.Ldc_I4, 7);
+ Modify (i, OpCodes.Ldc_I4, 7);
break;
case Code.Ldc_I4_8 :
- Simplify (i, OpCodes.Ldc_I4, 8);
+ Modify (i, OpCodes.Ldc_I4, 8);
break;
case Code.Ldc_I4_S :
i.OpCode = OpCodes.Ldc_I4;
}
}
- static void Simplify (Instruction i, OpCode op, object operand)
+ public void Optimize ()
+ {
+ foreach (Instruction instr in m_instructions) {
+ int index;
+ switch (instr.OpCode.Code) {
+ case Code.Ldarg:
+ index = m_method.Parameters.IndexOf ((ParameterDefinition) instr.Operand);
+ if (index == -1 && instr.Operand == m_method.This)
+ index = 0;
+ else if (m_method.HasThis)
+ index++;
+
+ switch (index) {
+ case 0:
+ Modify (instr, OpCodes.Ldarg_0, null);
+ break;
+ case 1:
+ Modify (instr, OpCodes.Ldarg_1, null);
+ break;
+ case 2:
+ Modify (instr, OpCodes.Ldarg_2, null);
+ break;
+ case 3:
+ Modify (instr, OpCodes.Ldarg_3, null);
+ break;
+ default:
+ if (index < 256)
+ Modify (instr, OpCodes.Ldarg_S, instr.Operand);
+ break;
+ }
+ break;
+ case Code.Ldloc:
+ index = m_variables.IndexOf ((VariableDefinition) instr.Operand);
+ switch (index) {
+ case 0:
+ Modify (instr, OpCodes.Ldloc_0, null);
+ break;
+ case 1:
+ Modify (instr, OpCodes.Ldloc_1, null);
+ break;
+ case 2:
+ Modify (instr, OpCodes.Ldloc_2, null);
+ break;
+ case 3:
+ Modify (instr, OpCodes.Ldloc_3, null);
+ break;
+ default:
+ if (index < 256)
+ Modify (instr, OpCodes.Ldloc_S, instr.Operand);
+ break;
+ }
+ break;
+ case Code.Stloc:
+ index = m_variables.IndexOf ((VariableDefinition) instr.Operand);
+ switch (index) {
+ case 0:
+ Modify (instr, OpCodes.Stloc_0, null);
+ break;
+ case 1:
+ Modify (instr, OpCodes.Stloc_1, null);
+ break;
+ case 2:
+ Modify (instr, OpCodes.Stloc_2, null);
+ break;
+ case 3:
+ Modify (instr, OpCodes.Stloc_3, null);
+ break;
+ default:
+ if (index < 256)
+ Modify (instr, OpCodes.Stloc_S, instr.Operand);
+ break;
+ }
+ break;
+ case Code.Ldarga:
+ index = m_method.Parameters.IndexOf ((ParameterDefinition) instr.Operand);
+ if (index == -1 && instr.Operand == m_method.This)
+ index = 0;
+ else if (m_method.HasThis)
+ index++;
+ if (index < 256)
+ Modify (instr, OpCodes.Ldarga_S, instr.Operand);
+ break;
+ case Code.Ldloca:
+ if (m_variables.IndexOf ((VariableDefinition) instr.Operand) < 256)
+ Modify (instr, OpCodes.Ldloca_S, instr.Operand);
+ break;
+ case Code.Ldc_I4:
+ int i = (int) instr.Operand;
+ switch (i) {
+ case -1:
+ Modify (instr, OpCodes.Ldc_I4_M1, null);
+ break;
+ case 0:
+ Modify (instr, OpCodes.Ldc_I4_0, null);
+ break;
+ case 1:
+ Modify (instr, OpCodes.Ldc_I4_1, null);
+ break;
+ case 2:
+ Modify (instr, OpCodes.Ldc_I4_2, null);
+ break;
+ case 3:
+ Modify (instr, OpCodes.Ldc_I4_3, null);
+ break;
+ case 4:
+ Modify (instr, OpCodes.Ldc_I4_4, null);
+ break;
+ case 5:
+ Modify (instr, OpCodes.Ldc_I4_5, null);
+ break;
+ case 6:
+ Modify (instr, OpCodes.Ldc_I4_6, null);
+ break;
+ case 7:
+ Modify (instr, OpCodes.Ldc_I4_7, null);
+ break;
+ case 8:
+ Modify (instr, OpCodes.Ldc_I4_8, null);
+ break;
+ default:
+ if (i >= -128 || i < 128)
+ Modify (instr, OpCodes.Ldc_I4_S, (sbyte) i);
+ break;
+ }
+ break;
+ }
+ }
+
+ OptimizeBranches ();
+ }
+
+ void OptimizeBranches ()
+ {
+ ComputeOffsets ();
+
+ foreach (Instruction instr in m_instructions) {
+ if (instr.OpCode.OperandType != OperandType.InlineBrTarget)
+ continue;
+
+ if (OptimizeBranch (instr))
+ ComputeOffsets ();
+ }
+ }
+
+ static bool OptimizeBranch (Instruction instr)
+ {
+ int offset = ((Instruction) instr.Operand).Offset - (instr.Offset + instr.OpCode.Size + 4);
+ if (! (offset >= -128 && offset <= 127))
+ return false;
+
+ switch (instr.OpCode.Code) {
+ case Code.Br:
+ instr.OpCode = OpCodes.Br_S;
+ break;
+ case Code.Brfalse:
+ instr.OpCode = OpCodes.Brfalse_S;
+ break;
+ case Code.Brtrue:
+ instr.OpCode = OpCodes.Brtrue_S;
+ break;
+ case Code.Beq:
+ instr.OpCode = OpCodes.Beq_S;
+ break;
+ case Code.Bge:
+ instr.OpCode = OpCodes.Bge_S;
+ break;
+ case Code.Bgt:
+ instr.OpCode = OpCodes.Bgt_S;
+ break;
+ case Code.Ble:
+ instr.OpCode = OpCodes.Ble_S;
+ break;
+ case Code.Blt:
+ instr.OpCode = OpCodes.Blt_S;
+ break;
+ case Code.Bne_Un:
+ instr.OpCode = OpCodes.Bne_Un_S;
+ break;
+ case Code.Bge_Un:
+ instr.OpCode = OpCodes.Bge_Un_S;
+ break;
+ case Code.Bgt_Un:
+ instr.OpCode = OpCodes.Bgt_Un_S;
+ break;
+ case Code.Ble_Un:
+ instr.OpCode = OpCodes.Ble_Un_S;
+ break;
+ case Code.Blt_Un:
+ instr.OpCode = OpCodes.Blt_Un_S;
+ break;
+ case Code.Leave:
+ instr.OpCode = OpCodes.Leave_S;
+ break;
+ }
+
+ return true;
+ }
+
+ void ComputeOffsets ()
+ {
+ int offset = 0;
+
+ foreach (Instruction instr in m_instructions) {
+ instr.Offset = offset;
+ offset += instr.GetSize ();
+ }
+ }
+
+ static void Modify (Instruction i, OpCode op, object operand)
{
i.OpCode = op;
i.Operand = operand;
[assembly: CLSCompliant (false)]
[assembly: ComVisible (false)]
-[assembly: AssemblyVersion ("0.6.8.7193")]
+[assembly: AssemblyVersion ("0.6.8.7804")]
#if KEYFILE
[assembly: AssemblyKeyFile("../../mono.snk")]
+2007-10-17 Nagappan <anagappan@novell.com>
+
+ * TdsConnectionPool.cs: Default the pooling is enabled. It has to be
+ disabled only when we clear all the pools.
+
2007-09-25 Nagappan A <anagappan@novell.com>
* Tds.cs (Pooling): Added new property to get the internal
ArrayList list = new ArrayList ();
TdsConnectionInfo info;
bool initialized;
- static bool pooling = false;
+ bool pooling = true;
int activeConnections = 0;
TdsConnectionPoolManager manager;
this.manager = manager;
}
- public static bool Pooling {
+ public bool Pooling {
get { return pooling; }
set { pooling = value; }
}
+2007-10-18 Andreia Gaita <avidigal@novell.com>\r
+\r
+ * use the newly-renamed gluezilla library\r
+\r
2007-10-07 Andreia Gaita <avidigal@novell.com>\r
\r
* More dialog event options.\r
internal class Base\r
{\r
private static Hashtable boundControls;\r
- internal static bool xulbrowserInstalled;\r
+ internal static bool gluezillaInstalled;\r
\r
private class BindingInfo\r
{\r
public CallbackBinder callback;\r
- public IntPtr xulbrowser;\r
+ public IntPtr gluezilla;\r
}\r
\r
private static bool isInitialized ()\r
{\r
- if (!xulbrowserInstalled)\r
+ if (!gluezillaInstalled)\r
return false;\r
return true;\r
}\r
\r
public static void DebugStartup ()\r
{\r
- xulbrowser_debug_startup ();\r
+ gluezilla_debug_startup ();\r
Trace.Listeners.Add (new TextWriterTraceListener (@"log"));\r
Trace.AutoFlush = true;\r
}\r
Marshal.StructureToPtr (info.callback, ptrCallback, true);\r
\r
try {\r
- info.xulbrowser = xulbrowser_init (ptrCallback, Environment.CurrentDirectory);\r
+ info.gluezilla = gluezilla_init (ptrCallback, Environment.CurrentDirectory);\r
}\r
catch (DllNotFoundException) {\r
- Console.WriteLine ("libxulbrowser not found. To have webbrowser support, you need libxulbrowser installed");\r
+ Console.WriteLine ("libgluezilla not found. To have webbrowser support, you need libgluezilla installed");\r
Marshal.FreeHGlobal (ptrCallback);\r
- xulbrowserInstalled = false;\r
+ gluezillaInstalled = false;\r
return;\r
}\r
- xulbrowserInstalled = true;\r
+ gluezillaInstalled = true;\r
boundControls.Add (control as IWebBrowser, info);\r
DebugStartup ();\r
}\r
return;\r
BindingInfo info = getBinding (control);\r
\r
- xulbrowser_shutdown (info.xulbrowser);\r
+ gluezilla_shutdown (info.gluezilla);\r
}\r
\r
public static void Bind (IWebBrowser control, IntPtr handle, int width, int height)\r
return;\r
BindingInfo info = getBinding (control);\r
\r
- xulbrowser_createBrowserWindow (info.xulbrowser, handle, width, height);\r
+ gluezilla_createBrowserWindow (info.gluezilla, handle, width, height);\r
}\r
\r
// layout\r
return;\r
BindingInfo info = getBinding (control);\r
\r
- xulbrowser_focus (info.xulbrowser, focus);\r
+ gluezilla_focus (info.gluezilla, focus);\r
}\r
\r
\r
return;\r
BindingInfo info = getBinding (control);\r
\r
- xulbrowser_deactivate (info.xulbrowser);\r
+ gluezilla_deactivate (info.gluezilla);\r
}\r
\r
public static void Activate (IWebBrowser control)\r
return;\r
BindingInfo info = getBinding (control);\r
\r
- xulbrowser_activate (info.xulbrowser);\r
+ gluezilla_activate (info.gluezilla);\r
}\r
\r
public static void Deactivate (IWebBrowser control)\r
return;\r
BindingInfo info = getBinding (control);\r
\r
- xulbrowser_deactivate (info.xulbrowser);\r
+ gluezilla_deactivate (info.gluezilla);\r
}\r
\r
public static void Resize (IWebBrowser control, int width, int height)\r
return;\r
BindingInfo info = getBinding (control);\r
\r
- xulbrowser_resize (info.xulbrowser, width, height);\r
+ gluezilla_resize (info.gluezilla, width, height);\r
}\r
\r
// navigation\r
return;\r
BindingInfo info = getBinding (control);\r
\r
- xulbrowser_navigate (info.xulbrowser, uri);\r
+ gluezilla_navigate (info.gluezilla, uri);\r
}\r
\r
\r
return false;\r
BindingInfo info = getBinding (control);\r
\r
- return xulbrowser_forward (info.xulbrowser);\r
+ return gluezilla_forward (info.gluezilla);\r
}\r
\r
public static bool Back (IWebBrowser control)\r
return false;\r
BindingInfo info = getBinding (control);\r
\r
- return xulbrowser_back (info.xulbrowser);\r
+ return gluezilla_back (info.gluezilla);\r
}\r
\r
public static void Home (IWebBrowser control)\r
return;\r
BindingInfo info = getBinding (control);\r
\r
- xulbrowser_home (info.xulbrowser);\r
+ gluezilla_home (info.gluezilla);\r
}\r
\r
public static void Stop (IWebBrowser control)\r
return;\r
BindingInfo info = getBinding (control);\r
\r
- xulbrowser_stop (info.xulbrowser);\r
+ gluezilla_stop (info.gluezilla);\r
}\r
\r
public static void Reload (IWebBrowser control, ReloadOption option)\r
return;\r
BindingInfo info = getBinding (control);\r
\r
- xulbrowser_reload (info.xulbrowser, option);\r
+ gluezilla_reload (info.gluezilla, option);\r
}\r
\r
public static nsIDOMHTMLDocument GetDOMDocument (IWebBrowser control)\r
return null;\r
BindingInfo info = getBinding (control);\r
\r
- return xulbrowser_getDomDocument (info.xulbrowser);\r
+ return gluezilla_getDomDocument (info.gluezilla);\r
}\r
\r
public static IntPtr StringInit ()\r
{\r
- return xulbrowser_stringInit ();\r
+ return gluezilla_stringInit ();\r
}\r
\r
public static void StringFinish (HandleRef str)\r
{\r
- xulbrowser_stringFinish (str);\r
+ gluezilla_stringFinish (str);\r
}\r
\r
public static string StringGet (HandleRef str)\r
{\r
- IntPtr p = xulbrowser_stringGet (str);\r
+ IntPtr p = gluezilla_stringGet (str);\r
return Marshal.PtrToStringUni (p);\r
}\r
\r
public static void StringSet (HandleRef str, string text)\r
{\r
- xulbrowser_stringSet (str, text);\r
+ gluezilla_stringSet (str, text);\r
}\r
\r
#region pinvokes\r
- [DllImport("xulbrowser")]\r
- private static extern void xulbrowser_debug_startup();\r
+ [DllImport("gluezilla")]\r
+ private static extern void gluezilla_debug_startup();\r
\r
- [DllImport("xulbrowser")]\r
- private static extern IntPtr xulbrowser_init (IntPtr events, string startDir);\r
+ [DllImport("gluezilla")]\r
+ private static extern IntPtr gluezilla_init (IntPtr events, string startDir);\r
\r
- [DllImport ("xulbrowser")]\r
- private static extern IntPtr xulbrowser_shutdown (IntPtr instance);\r
+ [DllImport ("gluezilla")]\r
+ private static extern IntPtr gluezilla_shutdown (IntPtr instance);\r
\r
- [DllImport ("xulbrowser")]\r
- private static extern int xulbrowser_createBrowserWindow (IntPtr instance, IntPtr hwnd, Int32 width, Int32 height);\r
+ [DllImport ("gluezilla")]\r
+ private static extern int gluezilla_createBrowserWindow (IntPtr instance, IntPtr hwnd, Int32 width, Int32 height);\r
\r
// layout\r
- [DllImport ("xulbrowser")]\r
- private static extern int xulbrowser_focus (IntPtr instance, FocusOption focus);\r
- [DllImport ("xulbrowser")]\r
- private static extern int xulbrowser_blur (IntPtr instance);\r
- [DllImport ("xulbrowser")]\r
- private static extern int xulbrowser_activate (IntPtr instance);\r
- [DllImport ("xulbrowser")]\r
- private static extern int xulbrowser_deactivate (IntPtr instance);\r
- [DllImport ("xulbrowser")]\r
- private static extern int xulbrowser_resize (IntPtr instance, Int32 width, Int32 height);\r
+ [DllImport ("gluezilla")]\r
+ private static extern int gluezilla_focus (IntPtr instance, FocusOption focus);\r
+ [DllImport ("gluezilla")]\r
+ private static extern int gluezilla_blur (IntPtr instance);\r
+ [DllImport ("gluezilla")]\r
+ private static extern int gluezilla_activate (IntPtr instance);\r
+ [DllImport ("gluezilla")]\r
+ private static extern int gluezilla_deactivate (IntPtr instance);\r
+ [DllImport ("gluezilla")]\r
+ private static extern int gluezilla_resize (IntPtr instance, Int32 width, Int32 height);\r
\r
// navigation\r
- [DllImport("xulbrowser")]\r
- private static extern int xulbrowser_navigate (IntPtr instance, string uri);\r
- [DllImport ("xulbrowser")]\r
- private static extern bool xulbrowser_forward (IntPtr instance);\r
- [DllImport ("xulbrowser")]\r
- private static extern bool xulbrowser_back (IntPtr instance);\r
- [DllImport ("xulbrowser")]\r
- private static extern int xulbrowser_home (IntPtr instance);\r
- [DllImport ("xulbrowser")]\r
- private static extern int xulbrowser_stop (IntPtr instance);\r
- [DllImport ("xulbrowser")]\r
- private static extern int xulbrowser_reload (IntPtr instance, ReloadOption option);\r
+ [DllImport("gluezilla")]\r
+ private static extern int gluezilla_navigate (IntPtr instance, string uri);\r
+ [DllImport ("gluezilla")]\r
+ private static extern bool gluezilla_forward (IntPtr instance);\r
+ [DllImport ("gluezilla")]\r
+ private static extern bool gluezilla_back (IntPtr instance);\r
+ [DllImport ("gluezilla")]\r
+ private static extern int gluezilla_home (IntPtr instance);\r
+ [DllImport ("gluezilla")]\r
+ private static extern int gluezilla_stop (IntPtr instance);\r
+ [DllImport ("gluezilla")]\r
+ private static extern int gluezilla_reload (IntPtr instance, ReloadOption option);\r
\r
// dom\r
- [DllImport ("xulbrowser")]\r
- private static extern nsIDOMHTMLDocument xulbrowser_getDomDocument (IntPtr instance);\r
-\r
- [DllImport ("xulbrowser")]\r
- private static extern IntPtr xulbrowser_stringInit ();\r
- [DllImport ("xulbrowser")]\r
- private static extern int xulbrowser_stringFinish (HandleRef str);\r
- [DllImport ("xulbrowser")]\r
- private static extern IntPtr xulbrowser_stringGet (HandleRef str);\r
- [DllImport ("xulbrowser")]\r
- private static extern void xulbrowser_stringSet (HandleRef str, [MarshalAs (UnmanagedType.LPWStr)] string text);\r
+ [DllImport ("gluezilla")]\r
+ private static extern nsIDOMHTMLDocument gluezilla_getDomDocument (IntPtr instance);\r
+\r
+ [DllImport ("gluezilla")]\r
+ private static extern IntPtr gluezilla_stringInit ();\r
+ [DllImport ("gluezilla")]\r
+ private static extern int gluezilla_stringFinish (HandleRef str);\r
+ [DllImport ("gluezilla")]\r
+ private static extern IntPtr gluezilla_stringGet (HandleRef str);\r
+ [DllImport ("gluezilla")]\r
+ private static extern void gluezilla_stringSet (HandleRef str, [MarshalAs (UnmanagedType.LPWStr)] string text);\r
#endregion\r
}\r
}\r
{
throw new NotImplementedException ();
}
-
+#if !TARGET_JVM
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static string get_bundled_machine_config ();
+#endif
public virtual Stream OpenStreamForRead (string streamName)
{
[Serializable]
public class HashSet<T>
{
+ [MonoTODO]
+ public bool Add (T item)
+ {
+ return true;
+ }
+
+ [MonoTODO]
+ public void Clear ()
+ {
+ }
+
+ [MonoTODO]
+ public bool Contains (T item)
+ {
+ return false;
+ }
}
}
+2007-10-20 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * System.Data_test.dll.sources: Added DbDataAdapterTest.cs,
+ OdbcCommandTest.cs, OdbcConnectionTest.cs, OdbcDataAdapterTest.cs,
+ OleDbCommandTest.cs, OleDbConnectionTest.cs, OleDbDataAdapterTest.cs,
+ SqlDataAdapterTest.cs.
+
+2007-10-15 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * System.Data_test.dll.sources: Added DbTransactionTest.cs.
+
2007-10-01 Joel Reed <joelwreed@gmail.com>
* Mono.Data.SqlExpressions/Functions.cs: accept SingleColumnValues and
+2007-10-21 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * DbDataPermissionAttribute.cs: In KeyRestrictionBehavior, reuse
+ ExceptionHelper.CheckEnumValue.
+ * ExceptionHelper.cs: Use same exception message for both 1.0 and 2.0.
+ * Index.cs: Fixed compiler warnings. Code formatting.
+
+2007-10-20 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * DbDataAdapter.cs: Implemented UpdateBatchSize setter.
+ * DataAdapter.cs: In FillLoadOption setter, ensure value is valid.
+ Modified MissingMappingAction and MissingSchemaAction setters to use
+ ExceptionHelper.CheckEnumValue to validate value. Spaces to tabs and
+ code formatting.
+ * ExceptionHelper.cs: Added CheckEnumValue method and modified
+ InvalidEnumValueException method to return AORE on 2.0 profile. Added
+ ConnectionClosed method that returns an InvalidOperationException.
+
+2007-10-19 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * DbTransaction.cs: Do not perform a rollback in Dispose (bool).
+ Leaves it up to deriving classes to override Dispose (bool) and
+ perform a rollback if necessary. Fixes bug #325397. Code formatting.
+ * ExceptionHelper.cs: Added TransactionNotUsable method that constructs
+ an InvalidOperationException to be thrown by IDbTransaction
+ implementations when the transaction is no longer open.
+
2007-09-27 Nagappan A <anagappan@novell.com>
* DbDataAdapter.cs: Added MonoTODO in appropriate place.
[RefreshProperties (RefreshProperties.All)]
public LoadOption FillLoadOption {
get { return fillLoadOption; }
- set { fillLoadOption = value; }
+ set {
+ ExceptionHelper.CheckEnumValue (typeof (LoadOption), value);
+ fillLoadOption = value;
+ }
}
#endif
public MissingMappingAction MissingMappingAction {
get { return missingMappingAction; }
set {
- if (!Enum.IsDefined (typeof (MissingMappingAction), value))
- throw ExceptionHelper.InvalidEnumValueException ("MissingMappingAction", value);
+ ExceptionHelper.CheckEnumValue (typeof (MissingMappingAction), value);
missingMappingAction = value;
}
}
[DefaultValue (MissingSchemaAction.Add)]
public MissingSchemaAction MissingSchemaAction {
get { return missingSchemaAction; }
- set {
- if (!Enum.IsDefined (typeof (MissingSchemaAction), value))
- throw ExceptionHelper.InvalidEnumValueException ("MissingSchemaAction", value);
+ set {
+ ExceptionHelper.CheckEnumValue (typeof (MissingSchemaAction), value);
missingSchemaAction = value;
}
}
#region Methods
#if !ONLY_1_0
- [Obsolete ("Use the protected constructor instead", false)]
+ [Obsolete ("Use the protected constructor instead", false)]
#endif
- [MonoTODO]
+ [MonoTODO]
protected virtual DataAdapter CloneInternals ()
{
throw new NotImplementedException ();
{
return BuildSchema (reader, table, schemaType, MissingSchemaAction,
MissingMappingAction, TableMappings);
- }
-
- /// <summary>
- /// Creates or Modifies the schema of the given DataTable based on the schema of
- /// the reader and the arguments passed.
- /// </summary>
- internal static int[] BuildSchema (IDataReader reader,
- DataTable table,
+ }
+
+ /// <summary>
+ /// Creates or Modifies the schema of the given DataTable based on the schema of
+ /// the reader and the arguments passed.
+ /// </summary>
+ internal static int[] BuildSchema (IDataReader reader, DataTable table,
SchemaType schemaType,
MissingSchemaAction missingSchAction,
MissingMappingAction missingMapAction,
(string)schemaRow [ColumnNameCol] == String.Empty) {
sourceColumnName = DefaultSourceColumnName;
realSourceColumnName = DefaultSourceColumnName + "1";
- }
- else {
+ } else {
sourceColumnName = (string) schemaRow [ColumnNameCol];
realSourceColumnName = sourceColumnName;
}
- for (int i = 1; sourceColumns.Contains (realSourceColumnName); i += 1)
+ for (int i = 1; sourceColumns.Contains (realSourceColumnName); i += 1)
realSourceColumnName = String.Format ("{0}{1}", sourceColumnName, i);
sourceColumns.Add(realSourceColumnName);
int index = dtMapping.IndexOfDataSetTable (table.TableName);
string srcTable = (index != -1 ? dtMapping[index].SourceTable : table.TableName);
tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (dtMapping, srcTable, table.TableName, missingMapAction);
- if (tableMapping != null)
- {
+ if (tableMapping != null) {
table.TableName = tableMapping.DataSetTable;
// check to see if the column mapping exists
DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction(tableMapping.ColumnMappings, realSourceColumnName, missingMapAction);
- if (columnMapping != null)
- {
+ if (columnMapping != null) {
Type columnType = (Type)schemaRow[DataTypeCol];
DataColumn col =
columnMapping.GetDataColumnBySchemaAction(
columnType,
missingSchAction);
- if (col != null)
- {
+ if (col != null) {
// if the column is not in the table - add it.
- if (table.Columns.IndexOf(col) == -1)
- {
+ if (table.Columns.IndexOf(col) == -1) {
if (missingSchAction == MissingSchemaAction.Add
|| missingSchAction == MissingSchemaAction.AddWithKey)
table.Columns.Add(col);
Array.Copy(mapping,0,tmp,0,col.Ordinal);
Array.Copy(mapping,col.Ordinal,tmp,col.Ordinal + 1,mapping.Length - col.Ordinal);
mapping = tmp;
- }
-
+ }
if (missingSchAction == MissingSchemaAction.AddWithKey) {
-
object value = (AllowDBNullCol != null) ? schemaRow[AllowDBNullCol] : null;
bool allowDBNull = value is bool ? (bool)value : true;
bool isUnique = value is bool ? (bool)value : false;
col.AllowDBNull = allowDBNull;
- // fill woth key info
+ // fill woth key info
if (isAutoIncrement && DataColumn.CanAutoIncrement(columnType)) {
col.AutoIncrement = true;
if (!allowDBNull)
}
}
return mapping;
- }
+ }
internal bool FillTable (DataTable dataTable, IDataReader dataReader, int startRecord, int maxRecords, ref int counter)
{
{
DataTableMapping tableMapping = null;
- if (schemaType == SchemaType.Mapped)
- {
+ if (schemaType == SchemaType.Mapped) {
tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTableName, sourceTableName, MissingMappingAction);
if (tableMapping != null)
return tableMapping.DataSetTable;
return null;
- }
- else
+ } else
return sourceTableName;
}
if (tableName != null) {
// check if the table exists in the dataset
- if (dataSet.Tables.Contains (tableName))
+ if (dataSet.Tables.Contains (tableName))
// get the table from the dataset
dataTable = dataSet.Tables [tableName];
else {
dataTable = dataSet.Tables.Add (tableName);
}
- if (!FillTable (dataTable, dataReader, startRecord, maxRecords, ref count)) {
+ if (!FillTable (dataTable, dataReader, startRecord, maxRecords, ref count))
continue;
- }
tableName = String.Format ("{0}{1}", srcTable, ++resultIndex);
}
}
} while (dataReader.NextResult ());
- }
- finally {
+ } finally {
dataReader.Close ();
}
- return count;
+ return count;
}
#if NET_2_0
[DefaultValue (1)]
public virtual int UpdateBatchSize {
get { return 1; }
- [MonoTODO]
- set { throw new NotSupportedException (); }
+ set {
+ if (value != 1)
+ throw new NotSupportedException ();
+ }
}
#else
IDbCommand SelectCommand {
public KeyRestrictionBehavior KeyRestrictionBehavior {
get { return keyRestrictionBehavior; }
set {
- if (!Enum.IsDefined (typeof (KeyRestrictionBehavior), value)) {
- string msg = Locale.GetText ("Unknown value.");
-#if NET_2_0
- throw new ArgumentOutOfRangeException ("KeyRestrictionBehavior", value, msg);
-#else
- throw new ArgumentException ("KeyRestrictionBehavior", msg);
-#endif
- }
+ ExceptionHelper.CheckEnumValue (typeof (KeyRestrictionBehavior), value);
keyRestrictionBehavior = value;
}
}
// Tim Coleman (tim@timcoleman.com)
//
// Copyright (C) Tim Coleman, 2003
-//
-
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
#if NET_2_0 || TARGET_JVM
-namespace System.Data.Common {
+namespace System.Data.Common
+{
public abstract class DbTransaction : MarshalByRefObject, IDbTransaction, IDisposable
{
#region Constructors
get { return DbConnection; }
}
- protected abstract DbConnection DbConnection { get; }
+ protected abstract DbConnection DbConnection {
+ get;
+ }
IDbConnection IDbTransaction.Connection {
get { return (IDbConnection) Connection; }
}
- public abstract IsolationLevel IsolationLevel { get; }
+ public abstract IsolationLevel IsolationLevel {
+ get;
+ }
#endregion // Properties
#region Methods
public abstract void Commit ();
+
public abstract void Rollback ();
public void Dispose ()
protected virtual void Dispose (bool disposing)
{
- if (disposing)
- Rollback();
}
#endregion // Methods
//\r
\r
using System;\r
+using System.Globalization;\r
\r
namespace System.Data.Common\r
{\r
internal sealed class ExceptionHelper\r
- { \r
+ {\r
internal static ArgumentException InvalidSizeValue (int value)\r
{\r
string [] args = new string [] {value.ToString ()};\r
return new ArgumentException (GetExceptionMessage ("Invalid parameter Size value '{0}'. The value must be greater than or equal to 0.",args));\r
}\r
\r
+ internal static void CheckEnumValue (Type enumType, object value)\r
+ {\r
+ if (!Enum.IsDefined (enumType, value))\r
+ throw InvalidEnumValueException (enumType.Name, value);\r
+ }\r
+\r
internal static ArgumentException InvalidEnumValueException (String enumeration, object value)\r
{\r
- return new ArgumentException (String.Format ("The {0} enumeration value, {1}, is invalid", enumeration, value));\r
+ string msg = string.Format (CultureInfo.InvariantCulture,\r
+ "The {0} enumeration value, {1}, is invalid.",\r
+ enumeration, value);\r
+#if NET_2_0\r
+ return new ArgumentOutOfRangeException (enumeration, msg);\r
+#else\r
+ return new ArgumentException (msg);\r
+#endif\r
}\r
\r
internal static ArgumentOutOfRangeException InvalidDataRowVersion (DataRowVersion value)\r
- { \r
+ {\r
object [] args = new object [] { "DataRowVersion", value.ToString () } ;\r
return new ArgumentOutOfRangeException (GetExceptionMessage ("{0}: Invalid DataRow Version enumeration value: {1}",args));\r
}\r
return new InvalidOperationException (GetExceptionMessage ("Execute requires the command to have a transaction object when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized."));\r
}\r
\r
+ internal static InvalidOperationException TransactionNotUsable (Type type)\r
+ {\r
+ return new InvalidOperationException (string.Format (\r
+ CultureInfo.InvariantCulture,\r
+ "This {0} has completed; it is no longer usable.",\r
+ type.Name));\r
+ }\r
+\r
internal static InvalidOperationException ParametersNotInitialized (int parameterPosition,string parameterName,string parameterType)\r
{\r
object [] args = new object [] { parameterPosition, parameterName, parameterType };\r
return new InvalidOperationException (GetExceptionMessage ("The connection is already Open (state={0}).",args));\r
}\r
\r
+ internal static InvalidOperationException ConnectionClosed ()\r
+ {\r
+ return new InvalidOperationException ("Invalid operation. The Connection is closed.");\r
+ }\r
+\r
internal static InvalidOperationException ConnectionStringNotInitialized ()\r
{\r
return new InvalidOperationException (GetExceptionMessage ("The ConnectionString property has not been initialized."));\r
{\r
if ((args == null) || (args.Length == 0)) {\r
return exceptionMessage;\r
- }\r
- else {\r
+ } else {\r
return String.Format (exceptionMessage,args);\r
}\r
}\r
\r
internal static string GetExceptionMessage (string exceptionMessage)\r
{\r
- return GetExceptionMessage (exceptionMessage,null);\r
+ return GetExceptionMessage (exceptionMessage, null);\r
}\r
}\r
}\r
\r
namespace System.Data.Common\r
{\r
- enum IndexDuplicatesState { Unknown, True, False }; \r
+ enum IndexDuplicatesState\r
+ {\r
+ Unknown,\r
+ True,\r
+ False\r
+ }\r
+\r
/// <summary>\r
/// Summary description for Index.\r
/// </summary>\r
{\r
#region Fields\r
\r
- int[] _array;\r
+ int [] _array;\r
int _size;\r
Key _key;\r
- int _refCount = 0;\r
+ int _refCount;\r
IndexDuplicatesState _hasDuplicates;\r
\r
#endregion // Fields\r
\r
#region Constructors\r
\r
- internal Index(Key key)\r
+ internal Index (Key key)\r
{\r
_key = key;\r
Reset();\r
\r
#region Properties\r
\r
- internal Key Key \r
- {\r
- get {\r
- return _key;\r
- }\r
+ internal Key Key {\r
+ get { return _key; }\r
}\r
\r
- internal int Size\r
- {\r
+ internal int Size {\r
get {\r
EnsureArray();\r
return _size;\r
}\r
}\r
\r
- internal int RefCount\r
- {\r
- get {\r
- return _refCount;\r
- }\r
+ internal int RefCount {\r
+ get { return _refCount; }\r
}\r
\r
- internal int IndexToRecord(int index){\r
+ internal int IndexToRecord (int index)\r
+ {\r
return index < 0 ? index : Array[index];\r
}\r
\r
- private int[] Array\r
- {\r
+ private int [] Array {\r
get {\r
- EnsureArray();\r
+ EnsureArray ();\r
return _array;\r
}\r
}\r
\r
- internal bool HasDuplicates\r
- {\r
+ internal bool HasDuplicates {\r
get {\r
if (_array == null || _hasDuplicates == IndexDuplicatesState.Unknown) {\r
- EnsureArray();\r
+ EnsureArray ();\r
if (_hasDuplicates == IndexDuplicatesState.Unknown) {\r
// check for duplicates\r
_hasDuplicates = IndexDuplicatesState.False;\r
- for(int i = 0; i < Size - 1; i++) {\r
- if (Key.CompareRecords(Array[i],Array[i+1]) == 0) {\r
+ for (int i = 0; i < Size - 1; i++) {\r
+ if (Key.CompareRecords (Array [i], Array [i + 1]) == 0) {\r
_hasDuplicates = IndexDuplicatesState.True;\r
break;\r
}\r
\r
#region Methods\r
\r
- internal int[] Duplicates {\r
+ internal int [] Duplicates {\r
get {\r
if (!HasDuplicates)\r
return null;\r
ArrayList dups = new ArrayList();\r
\r
bool inRange = false;\r
- for(int i = 0; i < Size - 1; i++) {\r
- if (Key.CompareRecords(Array[i],Array[i+1]) == 0){\r
+ for (int i = 0; i < Size - 1; i++) {\r
+ if (Key.CompareRecords (Array [i], Array [i + 1]) == 0) {\r
if (!inRange) {\r
dups.Add(Array[i]);\r
inRange = true;\r
}\r
\r
- dups.Add(Array[i+1]);\r
+ dups.Add (Array [i + 1]);\r
}\r
else\r
inRange = false;\r
}\r
\r
- return (int[])dups.ToArray(typeof(int));\r
+ return (int []) dups.ToArray (typeof (int));\r
}\r
}\r
\r
- private void EnsureArray()\r
+ private void EnsureArray ()\r
{\r
- if (_array == null) {\r
- RebuildIndex();\r
- }\r
+ if (_array == null)\r
+ RebuildIndex ();\r
}\r
\r
- internal int[] GetAll()\r
+ internal int [] GetAll ()\r
{\r
return Array;\r
}\r
\r
- internal DataRow[] GetAllRows ()\r
+ internal DataRow [] GetAllRows ()\r
{\r
- DataRow[] list = new DataRow [Size];\r
- for (int i=0; i < Size; ++i)\r
+ DataRow [] list = new DataRow [Size];\r
+ for (int i = 0; i < Size; ++i)\r
list [i] = Key.Table.RecordCache [Array [i]];\r
return list;\r
}\r
\r
- internal DataRow[] GetDistinctRows () \r
+ internal DataRow [] GetDistinctRows () \r
{\r
ArrayList list = new ArrayList ();\r
list.Add (Key.Table.RecordCache [Array [0]]);\r
int currRecord = Array [0];\r
- for (int i=1; i < Size; ++i) {\r
+ for (int i = 1; i < Size; ++i) {\r
if (Key.CompareRecords (currRecord, Array [i]) == 0)\r
continue;\r
list.Add (Key.Table.RecordCache [Array [i]]);\r
currRecord = Array [i];\r
}\r
- return (DataRow[])list.ToArray (typeof (DataRow));\r
+ return (DataRow []) list.ToArray (typeof (DataRow));\r
}\r
\r
internal void Reset()\r
{\r
_array = null;\r
- RebuildIndex();\r
+ RebuildIndex ();\r
}\r
\r
private void RebuildIndex()\r
{\r
// consider better capacity approximation\r
- _array = new int[Key.Table.RecordCache.CurrentCapacity];\r
+ _array = new int [Key.Table.RecordCache.CurrentCapacity];\r
_size = 0;\r
- foreach(DataRow row in Key.Table.Rows) {\r
- int record = Key.GetRecord(row);\r
- if (record != -1) {\r
- _array[_size++] = record;\r
- }\r
+ foreach (DataRow row in Key.Table.Rows) {\r
+ int record = Key.GetRecord (row);\r
+ if (record != -1)\r
+ _array [_size++] = record;\r
}\r
_hasDuplicates = IndexDuplicatesState.False;\r
// Note : MergeSort may update hasDuplicates to True\r
- Sort();\r
+ Sort ();\r
}\r
\r
- private void Sort()\r
+ private void Sort ()\r
{\r
//QuickSort(Array,0,Size-1);\r
- MergeSort(Array,Size);\r
+ MergeSort (Array, Size);\r
}\r
\r
/*\r
* Returns record number of the record equal to the key values supplied \r
* in the meaning of index key, or -1 if no equal record found.\r
*/\r
- internal int Find(object[] keys)\r
+ internal int Find (object [] keys)\r
{\r
int index = FindIndex(keys);\r
- return IndexToRecord(index);\r
+ return IndexToRecord (index);\r
}\r
\r
/*\r
* Returns record index (location) of the record equal to the key values supplied \r
* in the meaning of index key, or -1 if no equal record found.\r
*/\r
- internal int FindIndex(object[] keys)\r
+ internal int FindIndex (object [] keys)\r
{\r
- if (keys == null || keys.Length != Key.Columns.Length) {\r
+ if (keys == null || keys.Length != Key.Columns.Length)\r
throw new ArgumentException("Expecting " + Key.Columns.Length + " value(s) for the key being indexed, " +\r
"but received " + ((keys == null) ? 0 : keys.Length) + " value(s).");\r
- }\r
\r
- int tmp = Key.Table.RecordCache.NewRecord();\r
+ int tmp = Key.Table.RecordCache.NewRecord ();\r
try {\r
// init key values for temporal record\r
- for(int i = 0; i < Key.Columns.Length; i++) {\r
- Key.Columns[i].DataContainer[tmp] = keys[i];\r
- }\r
- return FindIndex(tmp);\r
- }\r
-// catch(FormatException) {\r
-// return -1;\r
-// }\r
-// catch(InvalidCastException) {\r
-// return -1;\r
-// }\r
- finally {\r
- Key.Table.RecordCache.DisposeRecord(tmp);\r
+ for (int i = 0; i < Key.Columns.Length; i++)\r
+ Key.Columns [i].DataContainer [tmp] = keys [i];\r
+ return FindIndex (tmp);\r
+ } finally {\r
+ Key.Table.RecordCache.DisposeRecord (tmp);\r
}\r
}\r
\r
* Returns record number of the record equal to the record supplied \r
* in the meaning of index key, or -1 if no equal record found.\r
*/\r
- internal int Find(int record)\r
+ internal int Find (int record)\r
{\r
- int index = FindIndex(record);\r
- return IndexToRecord(index);\r
+ int index = FindIndex (record);\r
+ return IndexToRecord (index);\r
}\r
\r
/*\r
* Returns array of record numbers of the records equal equal to the key values supplied \r
* in the meaning of index key, or -1 if no equal record found.\r
*/\r
- internal int[] FindAll(object[] keys)\r
+ internal int[] FindAll (object [] keys)\r
{\r
- int[] indexes = FindAllIndexes(keys);\r
- IndexesToRecords(indexes);\r
+ int [] indexes = FindAllIndexes (keys);\r
+ IndexesToRecords (indexes);\r
return indexes;\r
}\r
\r
* Returns array of indexes of the records inside the index equal equal to the key values supplied \r
* in the meaning of index key, or -1 if no equal record found.\r
*/\r
- internal int[] FindAllIndexes(object[] keys)\r
+ internal int [] FindAllIndexes (object [] keys)\r
{\r
- if (keys == null || keys.Length != Key.Columns.Length) {\r
+ if (keys == null || keys.Length != Key.Columns.Length)\r
throw new ArgumentException("Expecting " + Key.Columns.Length + " value(s) for the key being indexed," +\r
"but received " + ((keys == null) ? 0 : keys.Length) + " value(s).");\r
- }\r
\r
- int tmp = Key.Table.RecordCache.NewRecord();\r
+ int tmp = Key.Table.RecordCache.NewRecord ();\r
try {\r
// init key values for temporal record\r
- for(int i = 0; i < Key.Columns.Length; i++) {\r
- Key.Columns[i].DataContainer[tmp] = keys[i];\r
- }\r
- return FindAllIndexes(tmp);\r
- }\r
- catch(FormatException) {\r
- return new int[0];\r
- }\r
- catch(InvalidCastException) {\r
- return new int[0];\r
- }\r
- finally {\r
- Key.Table.RecordCache.DisposeRecord(tmp);\r
+ for (int i = 0; i < Key.Columns.Length; i++)\r
+ Key.Columns [i].DataContainer [tmp] = keys [i];\r
+ return FindAllIndexes (tmp);\r
+ } catch(FormatException) {\r
+ return new int [0];\r
+ } catch(InvalidCastException) {\r
+ return new int [0];\r
+ } finally {\r
+ Key.Table.RecordCache.DisposeRecord (tmp);\r
}\r
}\r
\r
* Returns array of record numbers of the records equal to the record supplied \r
* in the meaning of index key, or empty list if no equal records found.\r
*/\r
- internal int[] FindAll(int record)\r
+ internal int [] FindAll (int record)\r
{\r
- int[] indexes = FindAllIndexes(record);\r
- IndexesToRecords(indexes);\r
+ int [] indexes = FindAllIndexes (record);\r
+ IndexesToRecords (indexes);\r
return indexes;\r
}\r
\r
* Returns array of indexes of the records inside the index that equal to the record supplied \r
* in the meaning of index key, or empty list if no equal records found.\r
*/\r
- internal int[] FindAllIndexes(int record)\r
+ internal int [] FindAllIndexes (int record)\r
{\r
int index = FindIndex(record);\r
-\r
- if (index == -1) {\r
+ if (index == -1)\r
return new int[0];\r
- }\r
\r
int startIndex = index++;\r
int endIndex = index;\r
- \r
- for(;startIndex >= 0 && Key.CompareRecords(Array[startIndex],record) == 0;startIndex--);\r
- for(;endIndex < Size && Key.CompareRecords(Array[endIndex],record) == 0;endIndex++);\r
+\r
+ for (; startIndex >= 0 && Key.CompareRecords (Array [startIndex], record) == 0; startIndex--) {\r
+ }\r
+ for (; endIndex < Size && Key.CompareRecords (Array [endIndex], record) == 0; endIndex++) {\r
+ }\r
\r
int length = endIndex - startIndex - 1;\r
- int[] indexes = new int[length];\r
- \r
- for(int i = 0; i < length; i++) {\r
- indexes[i] = ++startIndex;\r
- }\r
+ int [] indexes = new int [length];\r
\r
+ for (int i = 0; i < length; i++)\r
+ indexes [i] = ++startIndex;\r
+ \r
return indexes;\r
}\r
\r
* Returns index inside the array where record number of the record equal to the record supplied \r
* in the meaning of index key is sored, or -1 if no equal record found.\r
*/\r
- private int FindIndex(int record)\r
+ private int FindIndex (int record)\r
{\r
- if (Size == 0) {\r
+ if (Size == 0)\r
return -1;\r
- }\r
- return BinarySearch(Array,0,Size - 1,record);\r
+ return BinarySearch (Array, 0, Size - 1, record);\r
}\r
\r
/*\r
* Finds exact location of the record specified\r
*/ \r
- private int FindIndexExact(int record)\r
+ private int FindIndexExact (int record)\r
{\r
for (int i = 0, size = Size; i < size; i++)\r
- if (Array[i] == record)\r
+ if (Array [i] == record)\r
return i;\r
-\r
return -1;\r
}\r
\r
/*\r
* Returns array of records from the indexes (locations) inside the index\r
*/\r
- private void IndexesToRecords(int[] indexes)\r
+ private void IndexesToRecords (int [] indexes)\r
{\r
- for(int i = 0; i < indexes.Length; i++) {\r
- indexes[i] = Array[indexes[i]];\r
- }\r
+ for (int i = 0; i < indexes.Length; i++)\r
+ indexes [i] = Array [indexes [i]];\r
}\r
\r
- internal void Delete(DataRow row)\r
+ internal void Delete (DataRow row)\r
{\r
- int oldRecord = Key.GetRecord(row);\r
-\r
- Delete(oldRecord);\r
+ int oldRecord = Key.GetRecord (row);\r
+ Delete (oldRecord);\r
}\r
\r
- internal void Delete(int oldRecord)\r
+ internal void Delete (int oldRecord)\r
{\r
if (oldRecord == -1)\r
return;\r
\r
- int index = FindIndexExact(oldRecord);\r
+ int index = FindIndexExact (oldRecord);\r
if (index != -1) {\r
- if ((_hasDuplicates == IndexDuplicatesState.True)) {\r
+ if (_hasDuplicates == IndexDuplicatesState.True) {\r
int c1 = 1;\r
int c2 = 1;\r
\r
- if (index > 0) {\r
- c1 = Key.CompareRecords(Array[index - 1],oldRecord);\r
- }\r
- if (index < Size - 1) {\r
- c2 = Key.CompareRecords(Array[index + 1],oldRecord);\r
- }\r
+ if (index > 0)\r
+ c1 = Key.CompareRecords (Array [index - 1], oldRecord);\r
+ if (index < Size - 1)\r
+ c2 = Key.CompareRecords (Array [index + 1], oldRecord);\r
\r
- if (c1 == 0 ^ c2 == 0) {\r
+ if (c1 == 0 ^ c2 == 0)\r
_hasDuplicates = IndexDuplicatesState.Unknown;\r
- }\r
}\r
Remove(index);\r
}\r
}\r
\r
- private void Remove(int index)\r
+ private void Remove (int index)\r
{\r
- if (Size > 1) {\r
- System.Array.Copy(Array,index+1,Array,index,Size - index - 1);\r
- }\r
+ if (Size > 1)\r
+ System.Array.Copy (Array, index + 1, Array, index,Size - index - 1);\r
_size--;\r
}\r
\r
-\r
- internal void Update(DataRow row,int oldRecord, DataRowVersion oldVersion, DataRowState oldState)\r
- { \r
+ internal void Update (DataRow row, int oldRecord, DataRowVersion oldVersion, DataRowState oldState)\r
+ {\r
bool contains = Key.ContainsVersion (oldState, oldVersion);\r
- int newRecord = Key.GetRecord(row); \r
+ int newRecord = Key.GetRecord (row);\r
// the record did not appeared in the index before update\r
if (oldRecord == -1 || Size == 0 || !contains) {\r
- if (newRecord >= 0) {\r
- if (FindIndexExact(newRecord) < 0)\r
- Add(row,newRecord);\r
- }\r
+ if (newRecord >= 0)\r
+ if (FindIndexExact (newRecord) < 0)\r
+ Add (row,newRecord);\r
return;\r
}\r
\r
return;\r
}\r
\r
- int oldIdx = FindIndexExact(oldRecord);\r
-\r
- if( oldIdx == -1 ) {\r
- Add(row,newRecord);\r
+ int oldIdx = FindIndexExact (oldRecord);\r
+ if (oldIdx == -1) {\r
+ Add (row, newRecord);\r
return;\r
}\r
- \r
+\r
int newIdx = -1;\r
- int compare = Key.CompareRecords(Array[oldIdx],newRecord);\r
- int start,end;\r
+ int compare = Key.CompareRecords (Array [oldIdx], newRecord);\r
+ int start, end;\r
\r
int c1 = 1;\r
int c2 = 1;\r
\r
if (compare == 0) {\r
- if (Array[oldIdx] == newRecord) {\r
+ if (Array [oldIdx] == newRecord) {\r
// we deal with the same record that didn't change\r
// in the context of current index.\r
// so , do nothing.\r
return;\r
}\r
- }\r
- else {\r
- if ((_hasDuplicates == IndexDuplicatesState.True)) {\r
- if (oldIdx > 0) {\r
- c1 = Key.CompareRecords(Array[oldIdx - 1],newRecord);\r
- }\r
- if (oldIdx < Size - 1) {\r
- c2 = Key.CompareRecords(Array[oldIdx + 1],newRecord);\r
- }\r
-\r
- if ((c1 == 0 ^ c2 == 0) && compare != 0) {\r
+ } else {\r
+ if (_hasDuplicates == IndexDuplicatesState.True) {\r
+ if (oldIdx > 0)\r
+ c1 = Key.CompareRecords (Array [oldIdx - 1], newRecord);\r
+ if (oldIdx < Size - 1)\r
+ c2 = Key.CompareRecords (Array [oldIdx + 1], newRecord);\r
+\r
+ if ((c1 == 0 ^ c2 == 0) && compare != 0)\r
_hasDuplicates = IndexDuplicatesState.Unknown;\r
- }\r
}\r
}\r
\r
if ((oldIdx == 0 && compare > 0) || (oldIdx == (Size - 1) && compare < 0) || (compare == 0)) {\r
// no need to switch cells\r
newIdx = oldIdx;\r
- }\r
- else {\r
+ } else {\r
if (compare < 0) {\r
// search after the old place\r
start = oldIdx + 1;\r
end = Size - 1;\r
- }\r
- else {\r
+ } else {\r
// search before the old palce\r
start = 0;\r
end = oldIdx - 1;\r
}\r
\r
- newIdx = LazyBinarySearch(Array,start,end,newRecord); \r
+ newIdx = LazyBinarySearch (Array, start, end, newRecord);\r
\r
if (oldIdx < newIdx) {\r
- System.Array.Copy(Array,oldIdx + 1,Array,oldIdx,newIdx - oldIdx);\r
+ System.Array.Copy (Array, oldIdx + 1, Array, oldIdx, newIdx - oldIdx);\r
if (Key.CompareRecords (Array [newIdx], newRecord) > 0)\r
--newIdx;\r
- }\r
- else if (oldIdx > newIdx){\r
- System.Array.Copy(Array,newIdx,Array,newIdx + 1,oldIdx - newIdx);\r
+ } else if (oldIdx > newIdx){\r
+ System.Array.Copy (Array, newIdx, Array, newIdx + 1, oldIdx - newIdx);\r
if (Key.CompareRecords (Array [newIdx], newRecord) < 0)\r
++newIdx;\r
}\r
- } \r
+ }\r
Array[newIdx] = newRecord;\r
\r
if (compare != 0) {\r
if (!(_hasDuplicates == IndexDuplicatesState.True)) {\r
- if (newIdx > 0) {\r
- c1 = Key.CompareRecords(Array[newIdx - 1],newRecord);\r
- }\r
- if (newIdx < Size - 1) {\r
- c2 = Key.CompareRecords(Array[newIdx + 1],newRecord);\r
- }\r
+ if (newIdx > 0)\r
+ c1 = Key.CompareRecords (Array [newIdx - 1], newRecord);\r
+ if (newIdx < Size - 1)\r
+ c2 = Key.CompareRecords (Array [newIdx + 1], newRecord);\r
\r
- if (c1 == 0 || c2 == 0) {\r
+ if (c1 == 0 || c2 == 0)\r
_hasDuplicates = IndexDuplicatesState.True;\r
- }\r
}\r
}\r
}\r
\r
- internal void Add(DataRow row) {\r
- Add(row, Key.GetRecord(row));\r
+ internal void Add (DataRow row)\r
+ {\r
+ Add(row, Key.GetRecord (row));\r
}\r
\r
- private void Add(DataRow row,int newRecord)\r
+ private void Add (DataRow row,int newRecord)\r
{\r
int newIdx;\r
\r
\r
if (Size == 0) {\r
newIdx = 0;\r
- }\r
- else {\r
- newIdx = LazyBinarySearch(Array,0,Size - 1,newRecord);\r
+ } else {\r
+ newIdx = LazyBinarySearch (Array, 0, Size - 1, newRecord);\r
// if newl value is greater - insert afer old value\r
// else - insert before old value\r
- if (Key.CompareRecords(Array[newIdx],newRecord) < 0) {\r
+ if (Key.CompareRecords (Array [newIdx], newRecord) < 0)\r
newIdx++;\r
- }\r
}\r
- \r
- Insert(newIdx,newRecord);\r
+\r
+ Insert (newIdx, newRecord);\r
\r
int c1 = 1;\r
int c2 = 1;\r
if (!(_hasDuplicates == IndexDuplicatesState.True)) {\r
- if (newIdx > 0) {\r
- c1 = Key.CompareRecords(Array[newIdx - 1],newRecord);\r
- }\r
- if (newIdx < Size - 1) {\r
- c2 = Key.CompareRecords(Array[newIdx + 1],newRecord);\r
- }\r
+ if (newIdx > 0)\r
+ c1 = Key.CompareRecords (Array [newIdx - 1], newRecord);\r
+ if (newIdx < Size - 1)\r
+ c2 = Key.CompareRecords (Array [newIdx + 1], newRecord);\r
\r
- if (c1 == 0 || c2 == 0) {\r
+ if (c1 == 0 || c2 == 0)\r
_hasDuplicates = IndexDuplicatesState.True;\r
- }\r
}\r
}\r
\r
- private void Insert(int index,int r)\r
+ private void Insert (int index,int r)\r
{\r
if (Array.Length == Size) {\r
- int[] tmp = (Size == 0) ? new int[16] : new int[Size << 1];\r
- System.Array.Copy(Array,0,tmp,0,index);\r
- tmp[index] = r;\r
- System.Array.Copy(Array,index,tmp,index + 1,Size - index);\r
+ int [] tmp = (Size == 0) ? new int[16] : new int[Size << 1];\r
+ System.Array.Copy (Array, 0, tmp, 0, index);\r
+ tmp [index] = r;\r
+ System.Array.Copy (Array, index, tmp, index + 1, Size - index);\r
_array = tmp;\r
- }\r
- else {\r
- System.Array.Copy(Array,index,Array,index + 1,Size - index);\r
- Array[index] = r;\r
+ } else {\r
+ System.Array.Copy (Array, index, Array, index + 1, Size - index);\r
+ Array [index] = r;\r
}\r
_size++;\r
}\r
\r
- private void MergeSort(int[] to, int length)\r
- {\r
- int[] from = new int[length];\r
- System.Array.Copy(to, 0, from, 0, from.Length);\r
-\r
- MergeSort(from, to, 0, from.Length);\r
- }\r
-\r
- private void MergeSort(int[] from, int[] to,int p, int r)\r
- {\r
- int q = (p + r) >> 1;\r
- if (q == p) {\r
- return;\r
- } \r
+ private void MergeSort (int [] to, int length)\r
+ {\r
+ int [] from = new int [length];\r
+ System.Array.Copy (to, 0, from, 0, from.Length);\r
+ MergeSort (from, to, 0, from.Length);\r
+ }\r
\r
- MergeSort(to, from, p, q);\r
- MergeSort(to, from, q, r);\r
+ private void MergeSort(int[] from, int[] to,int p, int r)\r
+ {\r
+ int q = (p + r) >> 1;\r
+ if (q == p)\r
+ return;\r
\r
- // merge\r
- for (int middle = q, current = p;;) {\r
- int res = Key.CompareRecords(from[p],from[q]);\r
- if (res > 0) {\r
- to[current++] = from[q++];\r
+ MergeSort (to, from, p, q);\r
+ MergeSort (to, from, q, r);\r
\r
- if (q == r) {\r
- while( p < middle) {\r
- to[current++] = from[p++];\r
- }\r
- break;\r
- }\r
- }\r
- else {\r
+ // merge\r
+ for (int middle = q, current = p;;) {\r
+ int res = Key.CompareRecords (from[p], from[q]);\r
+ if (res > 0) {\r
+ to [current++] = from [q++];\r
\r
- if (res == 0) {\r
- _hasDuplicates = IndexDuplicatesState.True;\r
+ if (q == r) {\r
+ while (p < middle)\r
+ to[current++] = from[p++];\r
+ break;\r
}\r
+ } else {\r
+ if (res == 0)\r
+ _hasDuplicates = IndexDuplicatesState.True;\r
\r
- to[current++] = from[p++];\r
+ to [current++] = from [p++];\r
\r
- if (p == middle) {\r
- while( q < r) {\r
- to[current++] = from[q++];\r
- }\r
- break;\r
- }\r
- }\r
- }\r
+ if (p == middle) {\r
+ while (q < r)\r
+ to[current++] = from[q++];\r
+ break;\r
+ }\r
+ }\r
+ }\r
}\r
\r
- private void QuickSort(int[] a,int p,int r)\r
+ private void QuickSort (int [] a,int p,int r)\r
{\r
if (p < r) {\r
- int q = Partition(a,p,r);\r
- QuickSort(a,p,q);\r
- QuickSort(a,q+1,r);\r
+ int q = Partition (a, p, r);\r
+ QuickSort (a, p, q);\r
+ QuickSort (a, q + 1, r);\r
}\r
}\r
\r
- private int Partition(int[] a,int p,int r)\r
+ private int Partition (int [] a,int p,int r)\r
{\r
- int x = a[p];\r
+ int x = a [p];\r
int i = p - 1;\r
int j = r + 1;\r
\r
- while(true) {\r
+ while (true) {\r
// decrement upper limit while values are greater then border value\r
do {\r
j--;\r
- }\r
- while(Key.CompareRecords(a[j],x) > 0); //while(a[j] > x);\r
+ } while (Key.CompareRecords (a [j], x) > 0);\r
\r
do {\r
i++;\r
- }\r
- while(Key.CompareRecords(a[i],x) < 0); //while(a[i] < x);\r
+ } while (Key.CompareRecords (a [i], x) < 0);\r
\r
- if (i<j) {\r
- int tmp = a[j];\r
- a[j] = a[i];\r
- a[i] = tmp;\r
- }\r
- else {\r
+ if (i < j) {\r
+ int tmp = a [j];\r
+ a [j] = a [i];\r
+ a [i] = tmp;\r
+ } else {\r
return j;\r
}\r
}\r
}\r
\r
- private int BinarySearch(int[] a, int p, int r,int b)\r
+ private int BinarySearch (int [] a, int p, int r,int b)\r
{\r
- int i = LazyBinarySearch(a,p,r,b);\r
-\r
- return (Key.CompareRecords(a[i],b) == 0) ? i : -1;\r
+ int i = LazyBinarySearch (a, p, r, b);\r
+ return (Key.CompareRecords (a [i], b) == 0) ? i : -1;\r
}\r
\r
// Lazy binary search only returns the cell number the search finished in,\r
// but does not checks that the correct value was actually found\r
- private int LazyBinarySearch(int[] a, int p, int r,int b)\r
+ private int LazyBinarySearch (int [] a, int p, int r, int b)\r
{\r
- if ( p == r ) {\r
+ if (p == r)\r
return p;\r
- }\r
\r
- int q = (p+r) >> 1;\r
+ int q = (p + r) >> 1;\r
\r
- int compare = Key.CompareRecords(a[q],b);\r
- if (compare < 0) { // if (a[q] < b) {\r
- return LazyBinarySearch(a,q+1,r,b);\r
- }\r
- else if (compare > 0) { // a[q] > b\r
- return LazyBinarySearch(a,p,q,b);\r
- } \r
- else { // a[q] == b\r
+ int compare = Key.CompareRecords (a [q], b);\r
+ if (compare < 0)\r
+ return LazyBinarySearch (a, q + 1, r, b);\r
+ else if (compare > 0)\r
+ return LazyBinarySearch (a, p, q, b);\r
+ else\r
return q;\r
- }\r
}\r
\r
- internal void AddRef()\r
+ internal void AddRef ()\r
{\r
_refCount++;\r
}\r
\r
- internal void RemoveRef()\r
+ internal void RemoveRef ()\r
{\r
_refCount--;\r
}\r
/*\r
// Prints indexes. For debugging.\r
internal void Print ()\r
- {\r
- for (int i=0; i < Size; i++) {\r
- Console.Write ("Index {0} record {1}: ", i, Array [i]);\r
- for (int j=0; j < Key.Table.Columns.Count; j++) {\r
- DataColumn col = Key.Table.Columns [j];\r
- if (Array [i] >= 0)\r
- Console.Write ("{0,15} ", col [Array [i]]);\r
- }\r
- Console.WriteLine ();\r
- }\r
- }\r
+ {\r
+ for (int i=0; i < Size; i++) {\r
+ Console.Write ("Index {0} record {1}: ", i, Array [i]);\r
+ for (int j=0; j < Key.Table.Columns.Count; j++) {\r
+ DataColumn col = Key.Table.Columns [j];\r
+ if (Array [i] >= 0)\r
+ Console.Write ("{0,15} ", col [Array [i]]);\r
+ }\r
+ Console.WriteLine ();\r
+ }\r
+ }\r
*/\r
\r
#endregion // Methods\r
+2007-10-20 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * OdbcCommand.cs: Added constant for default CommandTimeout, instead
+ of using a magic number. Avoid unnecessary initialization. Fixed
+ default value for DesignTimeVisible. Return zero-length string if
+ CommandText is null. Spaces to tabs and code formatting.
+ * OdbcError.cs: Fixed typo in exception message.
+ * OdbcConnection.cs: Return zero-length string if ConnectionString is
+ null. In getters for Database, DataSource and Driver return a
+ zero-length string if connection is closed. In BeginTransaction and
+ GetSchema throw InvalidOperationException if connection is closed.
+ Added override for GetSchema (string, string []). Use string.Empty
+ instead of "".
+ * OdbcDataAdapter.cs: Avoid unnecessary initializations. Use direct
+ assignment in IDbDataAdapter implementation. In default ctor, set
+ SelectCommand to null.
+
+2007-10-19 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * OdbcTransaction.cs: Clear connection in Commit and Rollback.
+ In IsolationLevel, throw IOE if transaction is no longer open.
+
+2007-10-19 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * OdbcTransaction.cs: Keep state of the transaction, and update it
+ when performing commit or rollback. In Dispose (bool), only perform
+ a rollback if transaction was not committed or rollback before.
+ In Commit and Rollback, throw an InvalidOperationException if
+ transaction is no longer open.
+
+2007-10-19 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * OdbcTransaction.cs: Use OdbcIsolationLevel enum value instead of
+ magic numbers. For Snapshot isolation level, the attribute
+ SQL_COPT_SS_TXN_ISOLATION must be used instead. When isolation level
+ is Unspecified, then do not modify the isolation level at all and
+ lazy initlization the IsolationLevel property. Modified exceptions
+ for invalid / not supported isolation levels to match MS.
+ * libodbc.cs: Added attribute for changing SQL Server specific
+ connection option. Added enum for ODBC isolation level options.
+ Added SQLGetConnectAttr method.
+
+2007-10-19 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * libodbc.cs: Spaces to tabs. Code formatting.
+ * OdbcConnection.cs: Spaces to tabs. Code formatting.
+ * OdbcTransaction.cs: Code formatting.
+
+2007-10-19 Nagappan <anagappan@novell.com>
+
+ * OdbcCommandBuilder.cs, OdbcParameterCollection.cs: Code alignment.
+ * OdbcDataReader.cs: Fixes numeric columns, bug # 332404.
+
+2007-10-19 Nagappan <anagappan@novell.com>
+
+ * OdbcCommand.cs: (Clone): Implemented new method. Code alignment.
+
2007-10-12 Nagappan <anagappan@novell.com>
* OdbcDataReader.cs: Bug 332400 - ODBC and LONGBLOB columns. Thanks to
namespace System.Data.Odbc
{
- /// <summary>
+ /// <summary>
/// Represents an SQL statement or stored procedure to execute against a data source.
/// </summary>
[DesignerAttribute ("Microsoft.VSDesigner.Data.VS.OdbcCommandDesigner, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.ComponentModel.Design.IDesigner")]
- [ToolboxItemAttribute ("System.Drawing.Design.ToolboxItem, "+ Consts.AssemblySystem_Drawing)]
+ [ToolboxItemAttribute ("System.Drawing.Design.ToolboxItem, "+ Consts.AssemblySystem_Drawing)]
#if NET_2_0
[DefaultEvent ("RecordsAffected")]
public sealed class OdbcCommand : DbCommand, ICloneable
{
#region Fields
+ const int DEFAULT_COMMAND_TIMEOUT = 30;
+
string commandText;
int timeout;
CommandType commandType;
- UpdateRowSource updateRowSource = UpdateRowSource.Both;
+ UpdateRowSource updateRowSource;
OdbcConnection connection;
OdbcTransaction transaction;
OdbcParameterCollection _parameters;
bool designTimeVisible;
- bool prepared=false;
+ bool prepared;
IntPtr hstmt = IntPtr.Zero;
- bool disposed = false;
+ bool disposed;
#endregion // Fields
public OdbcCommand ()
{
- this.CommandText = String.Empty;
- this.CommandTimeout = 30; // default timeout
- this.CommandType = CommandType.Text;
- Connection = null;
+ timeout = DEFAULT_COMMAND_TIMEOUT;
+ commandType = CommandType.Text;
_parameters = new OdbcParameterCollection ();
- Transaction = null;
- designTimeVisible = false;
-#if ONLY_1_1
+ designTimeVisible = true;
updateRowSource = UpdateRowSource.Both;
-#endif // ONLY_1_1
}
public OdbcCommand (string cmdText) : this ()
{
- CommandText = cmdText;
+ commandText = cmdText;
}
public OdbcCommand (string cmdText, OdbcConnection connection)
Connection = connection;
}
- public OdbcCommand (string cmdText,
- OdbcConnection connection,
+ public OdbcCommand (string cmdText, OdbcConnection connection,
OdbcTransaction transaction) : this (cmdText, connection)
{
this.Transaction = transaction;
#region Properties
- internal IntPtr hStmt
- {
+ internal IntPtr hStmt {
get { return hstmt; }
}
- [OdbcCategory ("Data")]
- [DefaultValue ("")]
- [OdbcDescriptionAttribute ("Command text to execute")]
- [EditorAttribute ("Microsoft.VSDesigner.Data.Odbc.Design.OdbcCommandTextEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
- [RefreshPropertiesAttribute (RefreshProperties.All)]
- public
+ [OdbcCategory ("Data")]
+ [DefaultValue ("")]
+ [OdbcDescriptionAttribute ("Command text to execute")]
+ [EditorAttribute ("Microsoft.VSDesigner.Data.Odbc.Design.OdbcCommandTextEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
+ [RefreshPropertiesAttribute (RefreshProperties.All)]
+ public
#if NET_2_0
override
#endif
- string CommandText
- {
- get { return commandText; }
- set {
- prepared=false;
+ string CommandText {
+ get {
+ if (commandText == null)
+ return string.Empty;
+ return commandText;
+ }
+ set {
+ prepared = false;
commandText = value;
}
}
[OdbcDescriptionAttribute ("Time to wait for command to execute")]
#if NET_1_0 || ONLY_1_1
- [DefaultValue (30)]
+ [DefaultValue (DEFAULT_COMMAND_TIMEOUT)]
#endif
- public
+ public
#if NET_2_0
override
#endif
}
[OdbcCategory ("Data")]
- [DefaultValue ("Text")]
- [OdbcDescriptionAttribute ("How to interpret the CommandText")]
- [RefreshPropertiesAttribute (RefreshProperties.All)]
+ [DefaultValue ("Text")]
+ [OdbcDescriptionAttribute ("How to interpret the CommandText")]
+ [RefreshPropertiesAttribute (RefreshProperties.All)]
public
#if NET_2_0
override
#endif
- CommandType CommandType {
+ CommandType CommandType {
get { return commandType; }
set { commandType = value; }
}
#if ONLY_1_1
[OdbcCategory ("Behavior")]
- [OdbcDescriptionAttribute ("Connection used by the command")]
- [DefaultValue (null)]
- [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
- public OdbcConnection Connection {
+ [OdbcDescriptionAttribute ("Connection used by the command")]
+ [DefaultValue (null)]
+ [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
+ public OdbcConnection Connection {
get {
return connection;
}
#endif // ONLY_1_1
#if NET_2_0
- [DefaultValue (null)]
- [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
- public new OdbcConnection Connection
- {
- get { return DbConnection as OdbcConnection; }
- set { DbConnection = value; }
- }
-
+ [DefaultValue (null)]
+ [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
+ public new OdbcConnection Connection {
+ get { return DbConnection as OdbcConnection; }
+ set { DbConnection = value; }
+ }
#endif // NET_2_0
[BrowsableAttribute (false)]
- [DesignOnlyAttribute (true)]
- [DefaultValue (true)]
+ [DesignOnlyAttribute (true)]
+ [DefaultValue (true)]
#if NET_2_0
- [EditorBrowsable (EditorBrowsableState.Never)]
+ [EditorBrowsable (EditorBrowsableState.Never)]
#endif
- public
+ public
#if NET_2_0
override
#endif
- bool DesignTimeVisible {
+ bool DesignTimeVisible {
get {
return designTimeVisible;
}
[OdbcCategory ("Data")]
- [OdbcDescriptionAttribute ("The parameters collection")]
- [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
+ [OdbcDescriptionAttribute ("The parameters collection")]
+ [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
public
#if NET_2_0
- new
+ new
#endif // NET_2_0
- OdbcParameterCollection Parameters {
+ OdbcParameterCollection Parameters {
get {
#if ONLY_1_1
return _parameters;
- #else
- return base.Parameters as OdbcParameterCollection;
+#else
+ return base.Parameters as OdbcParameterCollection;
#endif // ONLY_1_1
-
}
}
[BrowsableAttribute (false)]
- [OdbcDescriptionAttribute ("The transaction used by the command")]
- [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
+ [OdbcDescriptionAttribute ("The transaction used by the command")]
+ [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
public
#if NET_2_0
- new
+ new
#endif // NET_2_0
- OdbcTransaction Transaction {
+ OdbcTransaction Transaction {
get {
return transaction;
}
}
[OdbcCategory ("Behavior")]
- [DefaultValue (UpdateRowSource.Both)]
- [OdbcDescriptionAttribute ("When used by a DataAdapter.Update, how command results are applied to the current DataRow")]
- public
+ [DefaultValue (UpdateRowSource.Both)]
+ [OdbcDescriptionAttribute ("When used by a DataAdapter.Update, how command results are applied to the current DataRow")]
+ public
#if NET_2_0
override
#endif
- UpdateRowSource UpdatedRowSource {
+ UpdateRowSource UpdatedRowSource {
get {
return updateRowSource;
}
}
#if NET_2_0
- protected override DbConnection DbConnection
- {
- get { return connection; }
- set {
- connection = (OdbcConnection) value;
- }
- }
+ protected override DbConnection DbConnection {
+ get { return connection; }
+ set { connection = (OdbcConnection) value;}
+ }
#endif // NET_2_0
#if ONLY_1_1
-
IDbConnection IDbCommand.Connection {
get {
return Connection;
}
}
- IDataParameterCollection IDbCommand.Parameters {
+ IDataParameterCollection IDbCommand.Parameters {
get {
return Parameters;
}
}
- #else
- protected override DbParameterCollection DbParameterCollection
- {
- get { return _parameters as DbParameterCollection;}
- }
-
+#else
+ protected override DbParameterCollection DbParameterCollection {
+ get { return _parameters as DbParameterCollection;}
+ }
#endif // NET_2_0
#if ONLY_1_1
- IDbTransaction IDbCommand.Transaction {
+ IDbTransaction IDbCommand.Transaction {
get {
return (IDbTransaction) Transaction;
}
set {
- if (value is OdbcTransaction)
- {
- Transaction = (OdbcTransaction)value;
- }
- else
- {
- throw new ArgumentException ();
- }
+ if (value is OdbcTransaction) {
+ Transaction = (OdbcTransaction) value;
+ } else {
+ throw new ArgumentException ();
+ }
}
}
#else
- protected override DbTransaction DbTransaction
- {
+ protected override DbTransaction DbTransaction {
get { return transaction; }
- set {
- transaction = (OdbcTransaction)value;
- }
+ set { transaction = (OdbcTransaction) value; }
}
#endif // ONLY_1_1
-
-
#endregion // Properties
#region Methods
public
#if NET_2_0
- override
+ override
#endif // NET_2_0
- void Cancel ()
+ void Cancel ()
{
if (hstmt!=IntPtr.Zero)
{
}
#else
- protected override DbParameter CreateDbParameter ()
- {
- return CreateParameter ();
- }
-
+ protected override DbParameter CreateDbParameter ()
+ {
+ return CreateParameter ();
+ }
#endif // ONLY_1_1
public new OdbcParameter CreateParameter ()
hstmt = IntPtr.Zero;
}
- private void ExecSQL(string sql)
+ private void ExecSQL (string sql)
{
OdbcReturn ret;
if (! prepared && Parameters.Count <= 0) {
public
#if NET_2_0
- override
+ override
#endif // NET_2_0
- int ExecuteNonQuery ()
+ int ExecuteNonQuery ()
{
return ExecuteNonQuery (true);
}
ExecSQL(CommandText);
// .NET documentation says that except for INSERT, UPDATE and
- // DELETE where the return value is the number of rows affected
- // for the rest of the commands the return value is -1.
- if ((CommandText.ToUpper().IndexOf("UPDATE")!=-1) ||
+ // DELETE where the return value is the number of rows affected
+ // for the rest of the commands the return value is -1.
+ if ((CommandText.ToUpper().IndexOf("UPDATE")!=-1) ||
(CommandText.ToUpper().IndexOf("INSERT")!=-1) ||
(CommandText.ToUpper().IndexOf("DELETE")!=-1)) {
-
int numrows = 0;
OdbcReturn ret = libodbc.SQLRowCount(hstmt,ref numrows);
records = numrows;
- }
- else
+ } else
records = -1;
if (freeHandle && !prepared)
public
#if NET_2_0
- override
+ override
#endif // NET_2_0
- void Prepare()
+ void Prepare()
{
ReAllocStatment ();
}
}
-
public
#if NET_2_0
- new
+ new
#endif // NET_2_0
- OdbcDataReader ExecuteReader ()
+ OdbcDataReader ExecuteReader ()
{
return ExecuteReader (CommandBehavior.Default);
}
{
return ExecuteReader ();
}
- #else
- protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
- {
- return ExecuteReader (behavior);
- }
-
+#else
+ protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
+ {
+ return ExecuteReader (behavior);
+ }
#endif // ONLY_1_1
public
#if NET_2_0
- new
+ new
#endif // NET_2_0
- OdbcDataReader ExecuteReader (CommandBehavior behavior)
+ OdbcDataReader ExecuteReader (CommandBehavior behavior)
{
int recordsAffected = ExecuteNonQuery(false);
OdbcDataReader dataReader=new OdbcDataReader(this, behavior, recordsAffected);
}
#if ONLY_1_1
- IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
+ IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
{
return ExecuteReader (behavior);
}
#endif // ONLY_1_1
- public
+ public
#if NET_2_0
override
#endif
{
object val = null;
OdbcDataReader reader=ExecuteReader();
- try
- {
+ try {
if (reader.Read ())
val=reader[0];
- }
- finally
- {
+ } finally {
reader.Close();
}
return val;
}
- [MonoTODO]
object ICloneable.Clone ()
{
- throw new NotImplementedException ();
+ OdbcCommand command = new OdbcCommand ();
+ command.CommandText = this.CommandText;
+ command.CommandTimeout = this.CommandTimeout;
+ command.CommandType = this.CommandType;
+ command.Connection = this.Connection;
+ command.DesignTimeVisible = this.DesignTimeVisible;
+ foreach (OdbcParameter parameter in this.Parameters)
+ command.Parameters.Add (parameter);
+ command.Transaction = this.Transaction;
+ return command;
}
public void ResetCommandTimeout ()
{
- CommandTimeout = 30;
+ CommandTimeout = DEFAULT_COMMAND_TIMEOUT;
}
#endregion
/// </summary>
#if NET_2_0
- public sealed class OdbcCommandBuilder : DbCommandBuilder
+ public sealed class OdbcCommandBuilder : DbCommandBuilder
#else // 1_1
public sealed class OdbcCommandBuilder : Component
#endif // NET_2_0
{
#region Fields
- private OdbcDataAdapter _adapter;
+ private OdbcDataAdapter _adapter;
private string _quotePrefix;
private string _quoteSuffix;
[DefaultValue (null)]
public
#if NET_2_0
- new
+ new
#endif // NET_2_0
- OdbcDataAdapter DataAdapter {
+ OdbcDataAdapter DataAdapter {
get {
return _adapter;
}
_adapter = value;
if (_adapter != null)
_adapter.RowUpdating += new OdbcRowUpdatingEventHandler (OnRowUpdating);
-
}
}
[BrowsableAttribute (false)]
[OdbcDescriptionAttribute ("The prefix string wrapped around sql objects")]
- [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
+ [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
#if ONLY_1_1
public
#else
- new
+ new
#endif
- string QuotePrefix {
+ string QuotePrefix {
get {
return _quotePrefix;
}
}
[BrowsableAttribute (false)]
- [OdbcDescriptionAttribute ("The suffix string wrapped around sql objects")]
- [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
+ [OdbcDescriptionAttribute ("The suffix string wrapped around sql objects")]
+ [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
#if ONLY_1_1
public
#else
public
#if NET_2_0
- new
+ new
#endif // NET_2_0
- OdbcCommand GetInsertCommand ()
+ OdbcCommand GetInsertCommand ()
{
// FIXME: check validity of adapter
if (_insertCommand != null)
#if NET_2_0
[MonoTODO]
- public new OdbcCommand GetUpdateCommand (bool option)
+ public new OdbcCommand GetUpdateCommand (bool option)
{
// FIXME: check validity of adapter
if (_updateCommand != null)
#if NET_2_0
[MonoTODO]
- public new OdbcCommand GetDeleteCommand (bool option)
+ public new OdbcCommand GetDeleteCommand (bool option)
{
// FIXME: check validity of adapter
if (_deleteCommand != null)
}
#if NET_2_0
- protected override void ApplyParameterInfo (DbParameter dbParameter,
- DataRow row,
- StatementType statementType,
- bool whereClause)
- {
+ protected override void ApplyParameterInfo (DbParameter dbParameter,
+ DataRow row,
+ StatementType statementType,
+ bool whereClause)
+ {
OdbcParameter parameter = (OdbcParameter) dbParameter;
parameter.Size = int.Parse (row ["ColumnSize"].ToString ());
if (row ["NumericPrecision"] != DBNull.Value) {
parameter.Scale = byte.Parse (row ["NumericScale"].ToString ());
}
parameter.DbType = (DbType) row ["ProviderType"];
- }
+ }
- protected override string GetParameterName (int position)
- {
+ protected override string GetParameterName (int position)
+ {
return String.Format("@p{0}", position);
- }
+ }
- protected override string GetParameterName (string parameterName)
- {
+ protected override string GetParameterName (string parameterName)
+ {
return String.Format("@{0}", parameterName);
- }
+ }
- protected override string GetParameterPlaceholder (int position)
- {
+ protected override string GetParameterPlaceholder (int position)
+ {
return GetParameterName (position);
- }
+ }
- [MonoTODO]
- protected override void SetRowUpdatingHandler (DbDataAdapter adapter)
- {
- throw new NotImplementedException ();
- }
+ [MonoTODO]
+ protected override void SetRowUpdatingHandler (DbDataAdapter adapter)
+ {
+ throw new NotImplementedException ();
+ }
#endif // NET_2_0
if (unquotedIdentifier == null || unquotedIdentifier == String.Empty)
return unquotedIdentifier;
return String.Format ("{0}{1}{2}", QuotePrefix,
- unquotedIdentifier, QuoteSuffix);
+ unquotedIdentifier, QuoteSuffix);
}
#if NET_2_0
{
[DefaultEvent ("InfoMessage")]
#if NET_2_0
- public sealed class OdbcConnection : DbConnection, ICloneable
+ public sealed class OdbcConnection : DbConnection, ICloneable
#else
public sealed class OdbcConnection : Component, ICloneable, IDbConnection
#endif //NET_2_0
string connectionString;
int connectionTimeout;
internal OdbcTransaction transaction;
- IntPtr henv=IntPtr.Zero, hdbc=IntPtr.Zero;
- bool disposed = false;
+ IntPtr henv =IntPtr.Zero, hdbc=IntPtr.Zero;
+ bool disposed;
#endregion
public OdbcConnection (string connectionString)
{
- Init (connectionString);
+ connectionTimeout = 15;
+ ConnectionString = connectionString;
}
- private void Init (string connectionString)
- {
- connectionTimeout = 15;
- ConnectionString = connectionString;
- }
-
#endregion // Constructors
#region Properties
- internal IntPtr hDbc
- {
+ internal IntPtr hDbc {
get { return hdbc; }
}
- [OdbcCategoryAttribute ("DataCategory_Data")]
+ [OdbcCategoryAttribute ("DataCategory_Data")]
[DefaultValue ("")]
[OdbcDescriptionAttribute ("Information used to connect to a Data Source")]
[RefreshPropertiesAttribute (RefreshProperties.All)]
[EditorAttribute ("Microsoft.VSDesigner.Data.Odbc.Design.OdbcConnectionStringEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
- [RecommendedAsConfigurableAttribute (true)]
- public
+ [RecommendedAsConfigurableAttribute (true)]
+ public
#if NET_2_0
override
#endif
string ConnectionString {
get {
+ if (connectionString == null)
+ return string.Empty;
return connectionString;
}
- set {
- connectionString = value;
- }
+ set { connectionString = value; }
}
[OdbcDescriptionAttribute ("Current connection timeout value, not settable in the ConnectionString")]
#endif
public
#if NET_2_0
- new
+ new
#endif // NET_2_0
- int ConnectionTimeout {
+ int ConnectionTimeout {
get {
return connectionTimeout;
}
set {
- if (value < 0) {
+ if (value < 0)
throw new ArgumentException("Timout should not be less than zero.");
- }
connectionTimeout = value;
}
}
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
- [OdbcDescriptionAttribute ("Current data source Catlog value, 'Database=X' in the ConnectionString")]
+ [OdbcDescriptionAttribute ("Current data source Catlog value, 'Database=X' in the ConnectionString")]
public
#if NET_2_0
- override
+ override
#endif // NET_2_0
- string Database {
+ string Database {
get {
- return GetInfo (OdbcInfo.DatabaseName);
+ if (State == ConnectionState.Closed)
+ return string.Empty;
+ return GetInfo (OdbcInfo.DatabaseName);
}
}
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
- [OdbcDescriptionAttribute ("The ConnectionState indicating whether the connection is open or closed")]
- [BrowsableAttribute (false)]
+ [OdbcDescriptionAttribute ("The ConnectionState indicating whether the connection is open or closed")]
+ [BrowsableAttribute (false)]
public
#if NET_2_0
- override
+ override
#endif // NET_2_0
- ConnectionState State
- {
+ ConnectionState State {
get {
- if (hdbc!=IntPtr.Zero) {
+ if (hdbc!=IntPtr.Zero)
return ConnectionState.Open;
- }
else
return ConnectionState.Closed;
}
}
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
- [OdbcDescriptionAttribute ("Current data source, 'Server=X' in the ConnectionString")]
+ [OdbcDescriptionAttribute ("Current data source, 'Server=X' in the ConnectionString")]
#if NET_2_0
- [Browsable (false)]
+ [Browsable (false)]
#endif
public
#if NET_2_0
- override
+ override
#endif // NET_2_0
- string DataSource {
+ string DataSource {
get {
- return GetInfo (OdbcInfo.DataSourceName);
+ if (State == ConnectionState.Closed)
+ return string.Empty;
+ return GetInfo (OdbcInfo.DataSourceName);
}
}
#if NET_2_0
- [Browsable (false)]
+ [Browsable (false)]
#endif
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
- [OdbcDescriptionAttribute ("Current ODBC Driver")]
- public string Driver {
- get {
- return GetInfo (OdbcInfo.DriverName);
- }
- }
+ [OdbcDescriptionAttribute ("Current ODBC Driver")]
+ public string Driver {
+ get {
+ if (State == ConnectionState.Closed)
+ return string.Empty;
+ return GetInfo (OdbcInfo.DriverName);
+ }
+ }
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
- [OdbcDescriptionAttribute ("Version of the product accessed by the ODBC Driver")]
- [BrowsableAttribute (false)]
- public
+ [OdbcDescriptionAttribute ("Version of the product accessed by the ODBC Driver")]
+ [BrowsableAttribute (false)]
+ public
#if NET_2_0
- override
+ override
#endif // NET_2_0
- string ServerVersion {
- get {
- return GetInfo (OdbcInfo.DbmsVersion);
- }
- }
+ string ServerVersion {
+ get {
+ return GetInfo (OdbcInfo.DbmsVersion);
+ }
+ }
-
#endregion // Properties
#region Methods
public
#if NET_2_0
- new
+ new
#endif // NET_2_0
- OdbcTransaction BeginTransaction ()
+ OdbcTransaction BeginTransaction ()
{
return BeginTransaction(IsolationLevel.Unspecified);
- }
+ }
-#if ONLY_1_1
+#if ONLY_1_1
IDbTransaction IDbConnection.BeginTransaction ()
{
return (IDbTransaction) BeginTransaction();
public
#if NET_2_0
- new
+ new
#endif // NET_2_0
- OdbcTransaction BeginTransaction (IsolationLevel level)
+ OdbcTransaction BeginTransaction (IsolationLevel level)
{
- if (transaction==null)
- {
- transaction=new OdbcTransaction(this,level);
+ if (State == ConnectionState.Closed)
+ throw ExceptionHelper.ConnectionClosed ();
+
+ if (transaction == null) {
+ transaction = new OdbcTransaction (this,level);
return transaction;
- }
- else
+ } else
throw new InvalidOperationException();
}
#if ONLY_1_1
IDbTransaction IDbConnection.BeginTransaction (IsolationLevel level)
{
- return (IDbTransaction) BeginTransaction(level);
+ return (IDbTransaction) BeginTransaction (level);
}
#endif // ONLY_1_1
public
#if NET_2_0
- override
+ override
#endif // NET_2_0
- void Close ()
+ void Close ()
{
OdbcReturn ret = OdbcReturn.Error;
if (State == ConnectionState.Open) {
// disconnect
ret = libodbc.SQLDisconnect (hdbc);
- if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo)) {
+ if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
throw new OdbcException (new OdbcError ("SQLDisconnect", OdbcHandleType.Dbc, hdbc));
- }
FreeHandles ();
-
transaction = null;
-
- RaiseStateChange (ConnectionState.Open, ConnectionState.Closed);
+ RaiseStateChange (ConnectionState.Open, ConnectionState.Closed);
}
}
public
#if NET_2_0
- new
+ new
#endif // NET_2_0
- OdbcCommand CreateCommand ()
+ OdbcCommand CreateCommand ()
{
- return new OdbcCommand ("", this, transaction);
+ return new OdbcCommand (string.Empty, this, transaction);
}
public
#if NET_2_0
- override
+ override
#endif // NET_2_0
- void ChangeDatabase(string Database)
+ void ChangeDatabase(string Database)
{
IntPtr ptr = IntPtr.Zero;
OdbcReturn ret = OdbcReturn.Error;
protected override void Dispose (bool disposing)
{
if (!this.disposed) {
- try
- {
+ try {
// release the native unmananged resources
this.Close();
this.disposed = true;
- }
- finally
- {
+ } finally {
// call Dispose on the base class
- base.Dispose(disposing);
+ base.Dispose(disposing);
}
}
}
public
#if NET_2_0
- override
+ override
#endif // NET_2_0
- void Open ()
+ void Open ()
{
if (State == ConnectionState.Open)
throw new InvalidOperationException ();
OdbcReturn ret = OdbcReturn.Error;
OdbcException e = null;
- try {
- // allocate Environment handle
- ret = libodbc.SQLAllocHandle (OdbcHandleType.Env, IntPtr.Zero, ref henv);
- if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo)) {
- e = new OdbcException (new OdbcError ("SQLAllocHandle"));
+ try {
+ // allocate Environment handle
+ ret = libodbc.SQLAllocHandle (OdbcHandleType.Env, IntPtr.Zero, ref henv);
+ if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo)) {
+ e = new OdbcException (new OdbcError ("SQLAllocHandle"));
MessageHandler (e);
throw e;
}
- ret = libodbc.SQLSetEnvAttr (henv, OdbcEnv.OdbcVersion, (IntPtr) libodbc.SQL_OV_ODBC3 , 0);
- if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
- throw new OdbcException (new OdbcError ("SQLSetEnvAttr", OdbcHandleType.Env, henv));
-
- // allocate connection handle
- ret = libodbc.SQLAllocHandle (OdbcHandleType.Dbc, henv, ref hdbc);
- if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
- throw new OdbcException (new OdbcError ("SQLAllocHandle", OdbcHandleType.Env, henv));
-
- // DSN connection
- if (ConnectionString.ToLower ().IndexOf ("dsn=") >= 0)
- {
- string _uid = "", _pwd = "", _dsn = "";
- string [] items = ConnectionString.Split (new char[1]{';'});
- foreach (string item in items)
- {
- string [] parts = item.Split (new char[1] {'='});
- switch (parts [0].Trim ().ToLower ())
- {
+ ret = libodbc.SQLSetEnvAttr (henv, OdbcEnv.OdbcVersion, (IntPtr) libodbc.SQL_OV_ODBC3 , 0);
+ if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
+ throw new OdbcException (new OdbcError ("SQLSetEnvAttr", OdbcHandleType.Env, henv));
+
+ // allocate connection handle
+ ret = libodbc.SQLAllocHandle (OdbcHandleType.Dbc, henv, ref hdbc);
+ if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
+ throw new OdbcException (new OdbcError ("SQLAllocHandle", OdbcHandleType.Env, henv));
+
+ // DSN connection
+ if (ConnectionString.ToLower ().IndexOf ("dsn=") >= 0)
+ {
+ string _uid = string.Empty, _pwd = string.Empty, _dsn = string.Empty;
+ string [] items = ConnectionString.Split (new char[1]{';'});
+ foreach (string item in items)
+ {
+ string [] parts = item.Split (new char[1] {'='});
+ switch (parts [0].Trim ().ToLower ())
+ {
case "dsn":
_dsn = parts [1].Trim ();
break;
case "pwd":
_pwd = parts [1].Trim ();
break;
- }
- }
- ret = libodbc.SQLConnect(hdbc, _dsn, -3, _uid, -3, _pwd, -3);
- if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
- throw new OdbcException (new OdbcError ("SQLConnect", OdbcHandleType.Dbc, hdbc));
- }
- else
- {
- // DSN-less Connection
- string OutConnectionString = new String (' ',1024);
- short OutLen = 0;
- ret = libodbc.SQLDriverConnect (hdbc, IntPtr.Zero, ConnectionString, -3,
- OutConnectionString, (short) OutConnectionString.Length, ref OutLen, 0);
- if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
- throw new OdbcException (new OdbcError ("SQLDriverConnect", OdbcHandleType.Dbc, hdbc));
- }
-
- RaiseStateChange (ConnectionState.Closed, ConnectionState.Open);
- } catch (Exception) {
- // free handles if any.
- FreeHandles ();
- throw;
- }
+ }
+ }
+ ret = libodbc.SQLConnect(hdbc, _dsn, -3, _uid, -3, _pwd, -3);
+ if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
+ throw new OdbcException (new OdbcError ("SQLConnect", OdbcHandleType.Dbc, hdbc));
+ }
+ else
+ {
+ // DSN-less Connection
+ string OutConnectionString = new String (' ',1024);
+ short OutLen = 0;
+ ret = libodbc.SQLDriverConnect (hdbc, IntPtr.Zero, ConnectionString, -3,
+ OutConnectionString, (short) OutConnectionString.Length, ref OutLen, 0);
+ if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
+ throw new OdbcException (new OdbcError ("SQLDriverConnect", OdbcHandleType.Dbc, hdbc));
+ }
+
+ RaiseStateChange (ConnectionState.Closed, ConnectionState.Open);
+ } catch {
+ // free handles if any.
+ FreeHandles ();
+ throw;
+ }
disposed = false;
}
throw new NotImplementedException ();
}
- private void FreeHandles ()
- {
- OdbcReturn ret = OdbcReturn.Error;
- if (hdbc != IntPtr.Zero) {
- ret = libodbc.SQLFreeHandle ((ushort) OdbcHandleType.Dbc, hdbc);
- if ( (ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
- throw new OdbcException (new OdbcError ("SQLFreeHandle", OdbcHandleType.Dbc, hdbc));
- }
- hdbc = IntPtr.Zero;
-
- if (henv != IntPtr.Zero) {
- ret = libodbc.SQLFreeHandle ((ushort) OdbcHandleType.Env, henv);
- if ( (ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
- throw new OdbcException (new OdbcError ("SQLFreeHandle", OdbcHandleType.Env, henv));
- }
- henv = IntPtr.Zero;
- }
+ private void FreeHandles ()
+ {
+ OdbcReturn ret = OdbcReturn.Error;
+ if (hdbc != IntPtr.Zero) {
+ ret = libodbc.SQLFreeHandle ((ushort) OdbcHandleType.Dbc, hdbc);
+ if ( (ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
+ throw new OdbcException (new OdbcError ("SQLFreeHandle", OdbcHandleType.Dbc, hdbc));
+ }
+ hdbc = IntPtr.Zero;
+
+ if (henv != IntPtr.Zero) {
+ ret = libodbc.SQLFreeHandle ((ushort) OdbcHandleType.Env, henv);
+ if ( (ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
+ throw new OdbcException (new OdbcError ("SQLFreeHandle", OdbcHandleType.Env, henv));
+ }
+ henv = IntPtr.Zero;
+ }
#if NET_2_0
- public new DataTable GetSchema ()
+ public override DataTable GetSchema ()
{
- if (State == ConnectionState.Open)
- throw new InvalidOperationException ();
+ if (State == ConnectionState.Closed)
+ throw ExceptionHelper.ConnectionClosed ();
return MetaDataCollections.Instance;
}
- public new DataTable GetSchema (string collectionName)
+ public override DataTable GetSchema (string collectionName)
{
- if (State == ConnectionState.Open)
- throw new InvalidOperationException ();
+ return GetSchema (collectionName, null);
+ }
+
+ public override DataTable GetSchema (string collectionName, string [] restrictionValues)
+ {
+ if (State == ConnectionState.Closed)
+ throw ExceptionHelper.ConnectionClosed ();
return GetSchema (collectionName, null);
}
throw new NotImplementedException ();
}
- internal string GetInfo (OdbcInfo info)
- {
- if (State == ConnectionState.Closed)
- throw new InvalidOperationException ("The connection is closed.");
-
- OdbcReturn ret = OdbcReturn.Error;
- short max_length = 256;
- byte [] buffer = new byte [max_length];
- short actualLength = 0;
-
- ret = libodbc.SQLGetInfo (hdbc, info, buffer, max_length, ref actualLength);
- if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
- throw new OdbcException (new OdbcError ("SQLGetInfo",
- OdbcHandleType.Dbc,
- hdbc));
-
- return System.Text.Encoding.Default.GetString (buffer);
- }
-
- private void RaiseStateChange (ConnectionState from, ConnectionState to)
- {
+ internal string GetInfo (OdbcInfo info)
+ {
+ if (State == ConnectionState.Closed)
+ throw new InvalidOperationException ("The connection is closed.");
+
+ OdbcReturn ret = OdbcReturn.Error;
+ short max_length = 256;
+ byte [] buffer = new byte [max_length];
+ short actualLength = 0;
+
+ ret = libodbc.SQLGetInfo (hdbc, info, buffer, max_length, ref actualLength);
+ if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
+ throw new OdbcException (new OdbcError ("SQLGetInfo",
+ OdbcHandleType.Dbc,
+ hdbc));
+
+ return System.Text.Encoding.Default.GetString (buffer);
+ }
+
+ private void RaiseStateChange (ConnectionState from, ConnectionState to)
+ {
#if ONLY_1_1
- if (StateChange != null)
- StateChange (this, new StateChangeEventArgs (from, to));
+ if (StateChange != null)
+ StateChange (this, new StateChangeEventArgs (from, to));
#else
base.OnStateChange (new StateChangeEventArgs (from, to));
#endif
- }
+ }
private OdbcInfoMessageEventArgs CreateOdbcInfoMessageEvent (OdbcErrorCollection errors)
{
}
private void OnOdbcInfoMessage (OdbcInfoMessageEventArgs e) {
- if (null != InfoMessage) {
+ if (InfoMessage != null)
InfoMessage (this, e);
- }
}
#endregion
#if ONLY_1_1
[OdbcDescription ("DbConnection_StateChange")]
- [OdbcCategory ("DataCategory_StateChange")]
+ [OdbcCategory ("DataCategory_StateChange")]
public event StateChangeEventHandler StateChange;
#endif // ONLY_1_1
[OdbcDescription ("DbConnection_InfoMessage")]
- [OdbcCategory ("DataCategory_InfoMessage")]
+ [OdbcCategory ("DataCategory_InfoMessage")]
public event OdbcInfoMessageEventHandler InfoMessage;
private void MessageHandler (OdbcException e)
#region Fields
#if ONLY_1_1
- bool disposed = false;
+ bool disposed;
#endif
OdbcCommand deleteCommand;
OdbcCommand insertCommand;
#region Constructors
- public OdbcDataAdapter () : this (new OdbcCommand ())
+ public OdbcDataAdapter () : this ((OdbcCommand) null)
{
}
public OdbcDataAdapter (OdbcCommand selectCommand)
{
- DeleteCommand = null;
- InsertCommand = null;
SelectCommand = selectCommand;
- UpdateCommand = null;
}
public OdbcDataAdapter (string selectCommandText, OdbcConnection selectConnection)
IDbCommand IDbDataAdapter.DeleteCommand {
get { return DeleteCommand; }
- set {
- if (!(value is OdbcCommand))
- throw new ArgumentException ();
- DeleteCommand = (OdbcCommand)value;
- }
+ set { DeleteCommand = (OdbcCommand) value; }
}
IDbCommand IDbDataAdapter.InsertCommand {
get { return InsertCommand; }
- set {
- if (!(value is OdbcCommand))
- throw new ArgumentException ();
- InsertCommand = (OdbcCommand)value;
- }
+ set { InsertCommand = (OdbcCommand) value; }
}
IDbCommand IDbDataAdapter.SelectCommand {
get { return SelectCommand; }
- set {
- if (!(value is OdbcCommand))
- throw new ArgumentException ();
- SelectCommand = (OdbcCommand)value;
- }
+ set { SelectCommand = (OdbcCommand) value; }
}
IDbCommand IDbDataAdapter.UpdateCommand {
get { return UpdateCommand; }
- set {
- if (!(value is OdbcCommand))
- throw new ArgumentException ();
- UpdateCommand = (OdbcCommand)value;
- }
+ set { UpdateCommand = (OdbcCommand) value; }
}
// Release unmanaged resources
disposed = true;
}
+ base.Dispose (true);
}
#endif
byte [] temp = new byte [outsize];
for (int i = 0;i<outsize;i++)
temp[i] = buffer[i];
- DataValue = Decimal.Parse(System.Text.Encoding.Default.GetString(temp));
+ DataValue = Decimal.Parse (System.Text.Encoding.Default.GetString (temp),
+ System.Globalization.CultureInfo.InvariantCulture);
}
break;
case OdbcType.TinyInt:
{
_nativeerror = 1;
_source = Source;
- _message = "Unable to retreive error information from ODBC driver manager";
+ _message = "Unable to retrieve error information from ODBC driver manager";
_state = "";
}
else
[ListBindable (false)]
[EditorAttribute ("Microsoft.VSDesigner.Data.Design.DBParametersEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
#if NET_2_0
- public sealed class OdbcParameterCollection : DbParameterCollection
+ public sealed class OdbcParameterCollection : DbParameterCollection
#else
public sealed class OdbcParameterCollection : MarshalByRefObject,
IDataParameterCollection, IList, ICollection, IEnumerable
#if ONLY_1_1
[Browsable (false)]
- [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
+ [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
#endif
public
#if NET_2_0
get { return list.Count; }
}
- [Browsable (false)]
- [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
+ [Browsable (false)]
+ [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public new OdbcParameter this [int index] {
get { return (OdbcParameter) list[index]; }
set { list[index] = value; }
}
- [Browsable (false)]
- [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
+ [Browsable (false)]
+ [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public new OdbcParameter this [string parameterName] {
get {
- foreach (OdbcParameter p in list)
- if (p.ParameterName.Equals (parameterName))
- return p;
- throw new IndexOutOfRangeException ("The specified name does not exist: " + parameterName);
- }
- set {
- if (!Contains (parameterName))
- throw new IndexOutOfRangeException("The specified name does not exist: " + parameterName);
- this [IndexOf (parameterName)] = value;
- }
-
+ foreach (OdbcParameter p in list)
+ if (p.ParameterName.Equals (parameterName))
+ return p;
+ throw new IndexOutOfRangeException ("The specified name does not exist: " + parameterName);
+ }
+ set {
+ if (!Contains (parameterName))
+ throw new IndexOutOfRangeException("The specified name does not exist: " + parameterName);
+ this [IndexOf (parameterName)] = value;
+ }
}
#if ONLY_1_1
}
#if ONLY_1_1
- object IList.this[int index] {
- get { return list[index]; }
- set { list[index] = value; }
+ object IList.this [int index] {
+ get { return list [index]; }
+ set { list [index] = value; }
}
- object IDataParameterCollection.this[string name]
+ object IDataParameterCollection.this [string name]
{
- get { return this[name]; }
- set {
- if (!(value is OdbcParameter))
- throw new InvalidCastException ("Only OdbcParameter objects can be used.");
- this [name] = (OdbcParameter) value;
- }
+ get { return this [name]; }
+ set {
+ if (!(value is OdbcParameter))
+ throw new InvalidCastException ("Only OdbcParameter objects can be used.");
+ this [name] = (OdbcParameter) value;
+ }
}
#endif // ONLY_1_1
// Brian Ritchie (brianlritchie@hotmail.com)
//
// Copyright (C) Brian Ritchie, 2002
-//
-
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
//
using System;
using System.Data;
-
-#if NET_2_0
using System.Data.Common;
-#endif // NET_2_0
+using System.Globalization;
namespace System.Data.Odbc
{
public sealed class OdbcTransaction : DbTransaction, IDisposable
#else
public sealed class OdbcTransaction : MarshalByRefObject, IDbTransaction
-#endif // NET_2_0
+#endif
{
- private bool disposed = false;
+ private bool disposed;
private OdbcConnection connection;
private IsolationLevel isolationlevel;
+ private bool isOpen;
- internal OdbcTransaction(OdbcConnection conn, IsolationLevel isolationlevel)
+ internal OdbcTransaction (OdbcConnection conn, IsolationLevel isolationlevel)
{
// Set Auto-commit (102) to false
- SetAutoCommit(conn, false);
+ SetAutoCommit (conn, false);
// Handle isolation level
- int lev=0;
- switch (isolationlevel)
- {
- case IsolationLevel.ReadUncommitted:
- lev=1;
- break;
- case IsolationLevel.ReadCommitted:
- lev=2;
- break;
- case IsolationLevel.RepeatableRead:
- lev=3;
- break;
- case IsolationLevel.Serializable:
- lev=4;
- break;
- case IsolationLevel.Unspecified:
- lev=0;
- break;
- default:
- throw new NotSupportedException();
+ OdbcIsolationLevel lev = OdbcIsolationLevel.ReadCommitted;
+ OdbcConnectionAttribute attr = OdbcConnectionAttribute.TransactionIsolation;
+ switch (isolationlevel) {
+ case IsolationLevel.ReadUncommitted:
+ lev = OdbcIsolationLevel.ReadUncommitted;
+ break;
+ case IsolationLevel.ReadCommitted:
+ lev = OdbcIsolationLevel.ReadCommitted;
+ break;
+ case IsolationLevel.RepeatableRead:
+ lev = OdbcIsolationLevel.RepeatableRead;
+ break;
+ case IsolationLevel.Serializable:
+ lev = OdbcIsolationLevel.Serializable;
+ break;
+#if NET_2_0
+ case IsolationLevel.Snapshot:
+ // badly broken on MS:
+ // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=305736
+ lev = OdbcIsolationLevel.Snapshot;
+
+ // SQL_ATTR_TXN_ISOLATION can be used to set all other isolation
+ // levels except for SQL_TXN_SS_SNAPSHOT. If you want to use snapshot
+ // isolation, you must set SQL_TXN_SS_SNAPSHOT through
+ // SQL_COPT_SS_TXN_ISOLATION. However, you can retrieve the
+ // isolation level by using either SQL_ATTR_TXN_ISOLATION or
+ // SQL_COPT_SS_TXN_ISOLATION.
+ // Source:
+ // http://msdn2.microsoft.com/en-us/library/ms131709.aspx
+ attr = OdbcConnectionAttribute.CoptTransactionIsolation;
+ break;
+#endif
+ case IsolationLevel.Unspecified:
+ // when isolationlevel is not specified, then use
+ // default isolation level of the driver and
+ // lazy initialize it in the IsolationLevel property
+ break;
+#if NET_2_0
+ case IsolationLevel.Chaos:
+ throw new ArgumentOutOfRangeException ("IsolationLevel",
+ string.Format (CultureInfo.CurrentCulture,
+ "The IsolationLevel enumeration " +
+ "value, {0}, is not supported by " +
+ "the .Net Framework Odbc Data " +
+ "Provider.", (int) isolationlevel));
+#endif
+ default:
+#if NET_2_0
+ throw new ArgumentOutOfRangeException ("IsolationLevel",
+ string.Format (CultureInfo.CurrentCulture,
+ "The IsolationLevel enumeration value, {0}, is invalid.",
+ (int) isolationlevel));
+#else
+ throw new ArgumentException (string.Format (
+ CultureInfo.InvariantCulture,
+ "Not supported isolationlevel - {0}",
+ isolationlevel));
+#endif
+ }
+
+ // only change isolation level if it was explictly set
+ if (isolationlevel != IsolationLevel.Unspecified) {
+ // mbd: Getting the return code of the second call to SQLSetConnectAttr is missing from original code!
+ OdbcReturn ret = libodbc.SQLSetConnectAttr (conn.hDbc,
+ attr, (IntPtr) lev, 0);
+ if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
+ throw new OdbcException (new OdbcError ("SQLSetConnectAttr", OdbcHandleType.Dbc, conn.hDbc));
}
- // mbd: Getting the return code of the second call to SQLSetConnectAttr is missing from original code!
- OdbcReturn ret = libodbc.SQLSetConnectAttr(conn.hDbc, OdbcConnectionAttribute.TransactionIsolation, (IntPtr) lev, 0);
- if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
- throw new OdbcException(new OdbcError("SQLSetConnectAttr",OdbcHandleType.Dbc,conn.hDbc));
- this.isolationlevel=isolationlevel;
- connection=conn;
+ this.isolationlevel = isolationlevel;
+ connection = conn;
+ isOpen = true;
}
-
+
// Set Auto-commit (102) connection attribute
// [MonoTODO]: nice to have before svn: define libodbc.SQL_IS_UINTEGER = -5
- private static void SetAutoCommit(OdbcConnection conn, bool isAuto)
+ private static void SetAutoCommit (OdbcConnection conn, bool isAuto)
{
- OdbcReturn ret=libodbc.SQLSetConnectAttr(
- conn.hDbc, OdbcConnectionAttribute.AutoCommit, (IntPtr)(isAuto ? 1 : 0), -5
- );
- if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
- throw new OdbcException(new OdbcError("SQLSetConnectAttr",OdbcHandleType.Dbc,conn.hDbc));
+ OdbcReturn ret = libodbc.SQLSetConnectAttr (conn.hDbc,
+ OdbcConnectionAttribute.AutoCommit,
+ (IntPtr) (isAuto ? 1 : 0), -5);
+ if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
+ throw new OdbcException (new OdbcError ("SQLSetConnectAttr", OdbcHandleType.Dbc, conn.hDbc));
+ }
+
+ private static IsolationLevel GetIsolationLevel (OdbcConnection conn)
+ {
+ int lev;
+ int length;
+ OdbcReturn ret = libodbc.SQLGetConnectAttr (conn.hDbc,
+ OdbcConnectionAttribute.TransactionIsolation,
+ out lev, 0, out length);
+ if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
+ throw new OdbcException (new OdbcError ("SQLGetConnectAttr",
+ OdbcHandleType.Dbc, conn.hDbc));
+ return MapOdbcIsolationLevel ((OdbcIsolationLevel) lev);
+ }
+
+ private static IsolationLevel MapOdbcIsolationLevel (OdbcIsolationLevel odbcLevel)
+ {
+ IsolationLevel isoLevel = IsolationLevel.Unspecified;
+
+ switch (odbcLevel) {
+ case OdbcIsolationLevel.ReadUncommitted:
+ isoLevel = IsolationLevel.ReadUncommitted;
+ break;
+ case OdbcIsolationLevel.ReadCommitted:
+ isoLevel = IsolationLevel.ReadCommitted;
+ break;
+ case OdbcIsolationLevel.RepeatableRead:
+ isoLevel = IsolationLevel.RepeatableRead;
+ break;
+ case OdbcIsolationLevel.Serializable:
+ isoLevel = IsolationLevel.Serializable;
+ break;
+#if NET_2_0
+ case OdbcIsolationLevel.Snapshot:
+ isoLevel = IsolationLevel.Snapshot;
+ break;
+#else
+ default:
+ throw new NotSupportedException (string.Format (
+ CultureInfo.InvariantCulture,
+ "Isolation level {0} is not supported.",
+ odbcLevel));
+#endif
+ }
+ return isoLevel;
}
#region Implementation of IDisposable
#if NET_2_0
protected override
#endif
- void Dispose(bool disposing)
+ void Dispose (bool disposing)
{
if (!disposed) {
- if (disposing) {
- Rollback();
- }
+ if (disposing && isOpen)
+ Rollback ();
disposed = true;
}
}
- void IDisposable.Dispose()
+ void IDisposable.Dispose ()
{
- Dispose(true);
- GC.SuppressFinalize(this);
+ Dispose (true);
+ GC.SuppressFinalize (this);
}
#endregion Implementation of IDisposable
#region Implementation of IDbTransaction
- public
+ public
#if NET_2_0
override
#endif //NET_2_0
- void Commit()
+ void Commit ()
{
- if (connection.transaction==this)
- {
- OdbcReturn ret=libodbc.SQLEndTran((short) OdbcHandleType.Dbc, connection.hDbc, 0);
- if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
+ if (!isOpen)
+ throw ExceptionHelper.TransactionNotUsable (GetType ());
+
+ if (connection.transaction == this) {
+ OdbcReturn ret = libodbc.SQLEndTran ((short) OdbcHandleType.Dbc, connection.hDbc, 0);
+ if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
throw new OdbcException (new OdbcError ("SQLEndTran", OdbcHandleType.Dbc, connection.hDbc));
- SetAutoCommit(connection, true); // restore default auto-commit
- connection.transaction=null;
- }
- else
- throw new InvalidOperationException();
+ SetAutoCommit (connection, true); // restore default auto-commit
+ connection.transaction = null;
+ connection = null;
+ isOpen = false;
+ } else
+ throw new InvalidOperationException ();
}
- public
+ public
#if NET_2_0
override
#endif //NET_2_0
void Rollback()
{
- if (connection.transaction==this)
- {
- OdbcReturn ret=libodbc.SQLEndTran((short) OdbcHandleType.Dbc, connection.hDbc, 1);
- if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
- throw new OdbcException(new OdbcError("SQLEndTran",OdbcHandleType.Dbc,connection.hDbc));
- SetAutoCommit(connection, true); // restore default auto-commit
- connection.transaction=null;
- }
- else
- throw new InvalidOperationException();
+ if (!isOpen)
+ throw ExceptionHelper.TransactionNotUsable (GetType ());
+
+ if (connection.transaction == this) {
+ OdbcReturn ret = libodbc.SQLEndTran ((short) OdbcHandleType.Dbc, connection.hDbc, 1);
+ if (ret!=OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
+ throw new OdbcException (new OdbcError ("SQLEndTran", OdbcHandleType.Dbc, connection.hDbc));
+ SetAutoCommit (connection, true); // restore default auto-commit
+ connection.transaction = null;
+ connection = null;
+ isOpen = false;
+ } else
+ throw new InvalidOperationException ();
}
-#if ONLY_1_1
- IDbConnection IDbTransaction.Connection {
+#if NET_2_0
+ protected override DbConnection DbConnection {
get {
return Connection;
}
}
-
-#endif // ONLY_1_1
-#if NET_2_0
- protected override DbConnection DbConnection {
+#else
+ IDbConnection IDbTransaction.Connection {
get {
return Connection;
}
}
-#endif // NET_2_0
- public
+#endif
+
+ public
#if NET_2_0
override
-#endif //NET_2_0
+#endif
IsolationLevel IsolationLevel {
get {
+ if (!isOpen)
+ throw ExceptionHelper.TransactionNotUsable (GetType ());
+
+ if (isolationlevel == IsolationLevel.Unspecified)
+ isolationlevel = GetIsolationLevel (Connection);
return isolationlevel;
}
}
// Authors:
// Brian Ritchie (brianlritchie@hotmail.com)
// Sureshkumar T (tsureshkumar@novell.com)
-//
//
// Copyright (C) Brian Ritchie, 2002
-//
-//
-
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
namespace System.Data.Odbc
{
- internal enum OdbcHandleType : short {
+ internal enum OdbcHandleType : short
+ {
Env = 1,
Dbc = 2,
Stmt = 3,
Desc = 4
- };
+ }
- internal enum OdbcReturn : short {
+ internal enum OdbcReturn : short
+ {
Error = -1,
InvalidHandle = -2,
StillExecuting = 2,
NoData = 100
}
- internal enum OdbcEnv : ushort {
+ internal enum OdbcEnv : ushort
+ {
OdbcVersion = 200,
ConnectionPooling = 201,
CPMatch = 202
}
- internal enum OdbcConnectionAttribute : int \r
+ internal enum OdbcConnectionAttribute : int
{
- AutoCommit=102,
- TransactionIsolation=108,
- CurrentCatalog=109
+ AutoCommit = 102,
+ TransactionIsolation = 108,
+ CurrentCatalog = 109,
+#if NET_2_0
+ CoptTransactionIsolation = 1227 /* SQL_COPT_SS_TXN_ISOLATION */
+#endif
}
- internal enum OdbcInfo : ushort
- {
- DataSourceName = 2,
- DriverName = 6,
- DriverVersion = 7,
- DatabaseName = 16,
- DbmsVersion = 18
- }
+ internal enum OdbcInfo : ushort
+ {
+ DataSourceName = 2,
+ DriverName = 6,
+ DriverVersion = 7,
+ DatabaseName = 16,
+ DbmsVersion = 18
+ }
internal enum OdbcInputOutputDirection : short
{
- Input=1,
- InputOutput=2,
- ResultCol=3,
- Output=4,
- ReturnValue=5
+ Input = 1,
+ InputOutput = 2,
+ ResultCol = 3,
+ Output = 4,
+ ReturnValue = 5
}
- internal enum OdbcLengthIndicator : short
- {
- NoTotal = -4,
- NullData = -1
- }
-
- // Keep this sorted.
- internal enum FieldIdentifier : short
- {
- AutoUniqueValue = 11, /* SQL_DESC_AUTO_UNIQUE_VALUE */
- BaseColumnName = 22, /* SQL_DESC_BASE_COLUMN_NAME */
- BaseTableName = 23, /* SQL_DESC_BASE_TABLE_NAME */
- CaseSensitive = 12, /* SQL_DESC_CASE_SENSITIVE */
- CatelogName = 17, /* SQL_DESC_CATALOG_NAME */
- ConsiseType = 2, /* SQL_DESC_CONCISE_TYPE */
- Count = 1001, /* SQL_DESC_COUNT */
- DisplaySize = 6, /* SQL_DESC_DISPLAY_SIZE */
- FixedPrecScale = 9, /* SQL_DESC_FIXED_PREC_SCALE */
- Label = 18, /* SQL_DESC_LABEL */
- Length = 1003, /* SQL_DESC_LENGTH */
- LiteralPrefix = 27, /* SQL_DESC_LITERAL_PREFIX */
- LiteralSuffix = 28, /* SQL_DESC_LITERAL_SUFFIX */
- LocalTypeName = 29, /* SQL_DESC_LOCAL_TYPE_NAME */
- Name = 1011, /* SQL_DESC_NAME */
- Nullable = 1008, /* SQL_DESC_NULLABLE */
- NumPrecRadix = 32, /* SQL_DESC_NUM_PREC_RADIX */
- OctetLength = 1013, /* SQL_DESC_OCTET_LENGTH */
- Precision = 1005, /* SQL_DESC_PRECISION */
- Scale = 1006, /* SQL_DESC_SCALE */
- SchemaName = 16, /* SQL_DESC_SCHEMA_NAME */
- Searchable = 13, /* SQL_DESC_SEARCHABLE */
- TableName = 15, /* SQL_DESC_TABLE_NAME */
- Type = 1002, /* SQL_DESC_TYPE */
- TypeName = 14, /* SQL_DESC_TYPE_NAME */
- Unnamed = 1012, /* SQL_DESC_UNNAMED */
- Unsigned = 8, /* SQL_DESC_UNSIGNED */
- Updatable = 10 /* SQL_DESC_UPDATABLE */
- }
-
- [StructLayout(LayoutKind.Sequential)]
+ internal enum OdbcIsolationLevel
+ {
+ ReadUncommitted = 1,
+ ReadCommitted = 2,
+ RepeatableRead = 4,
+ Serializable = 8,
+ Snapshot = 32 /* SQL_TXN_SS_SNAPSHOT */
+ }
+
+ internal enum OdbcLengthIndicator : short
+ {
+ NoTotal = -4,
+ NullData = -1
+ }
+
+ // Keep this sorted.
+ internal enum FieldIdentifier : short
+ {
+ AutoUniqueValue = 11, /* SQL_DESC_AUTO_UNIQUE_VALUE */
+ BaseColumnName = 22, /* SQL_DESC_BASE_COLUMN_NAME */
+ BaseTableName = 23, /* SQL_DESC_BASE_TABLE_NAME */
+ CaseSensitive = 12, /* SQL_DESC_CASE_SENSITIVE */
+ CatelogName = 17, /* SQL_DESC_CATALOG_NAME */
+ ConsiseType = 2, /* SQL_DESC_CONCISE_TYPE */
+ Count = 1001, /* SQL_DESC_COUNT */
+ DisplaySize = 6, /* SQL_DESC_DISPLAY_SIZE */
+ FixedPrecScale = 9, /* SQL_DESC_FIXED_PREC_SCALE */
+ Label = 18, /* SQL_DESC_LABEL */
+ Length = 1003, /* SQL_DESC_LENGTH */
+ LiteralPrefix = 27, /* SQL_DESC_LITERAL_PREFIX */
+ LiteralSuffix = 28, /* SQL_DESC_LITERAL_SUFFIX */
+ LocalTypeName = 29, /* SQL_DESC_LOCAL_TYPE_NAME */
+ Name = 1011, /* SQL_DESC_NAME */
+ Nullable = 1008, /* SQL_DESC_NULLABLE */
+ NumPrecRadix = 32, /* SQL_DESC_NUM_PREC_RADIX */
+ OctetLength = 1013, /* SQL_DESC_OCTET_LENGTH */
+ Precision = 1005, /* SQL_DESC_PRECISION */
+ Scale = 1006, /* SQL_DESC_SCALE */
+ SchemaName = 16, /* SQL_DESC_SCHEMA_NAME */
+ Searchable = 13, /* SQL_DESC_SEARCHABLE */
+ TableName = 15, /* SQL_DESC_TABLE_NAME */
+ Type = 1002, /* SQL_DESC_TYPE */
+ TypeName = 14, /* SQL_DESC_TYPE_NAME */
+ Unnamed = 1012, /* SQL_DESC_UNNAMED */
+ Unsigned = 8, /* SQL_DESC_UNSIGNED */
+ Updatable = 10 /* SQL_DESC_UPDATABLE */
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
internal struct OdbcTimestamp
{
internal short year;
internal ulong fraction;
}
-
-// sealed internal class libodbc
internal class libodbc
{
- #region global constants
+ #region global constants
internal const int SQL_OV_ODBC2 = 2;
internal const int SQL_OV_ODBC3 = 3;
- internal const string SQLSTATE_RIGHT_TRUNC = "01004";
- internal const char C_NULL = '\0';
+ internal const string SQLSTATE_RIGHT_TRUNC = "01004";
+ internal const char C_NULL = '\0';
internal const int SQL_NTS = -3;
internal const short SQL_TRUE = 1;
internal const short SQL_ATTR_READONLY = 0;
internal const short SQL_ATTR_WRITE = 1;
internal const short SQL_ATTR_READWRITE_UNKNOWN = 2;
- #endregion
+ #endregion
internal static OdbcInputOutputDirection ConvertParameterDirection(
ParameterDirection dir)
{
- switch (dir)
- {
- case ParameterDirection.Input:
- return OdbcInputOutputDirection.Input;
- case ParameterDirection.InputOutput:
- return OdbcInputOutputDirection.InputOutput;
- case ParameterDirection.Output:
- return OdbcInputOutputDirection.Output;
- case ParameterDirection.ReturnValue:
- return OdbcInputOutputDirection.ReturnValue;
- default:
- return OdbcInputOutputDirection.Input;
+ switch (dir) {
+ case ParameterDirection.Input:
+ return OdbcInputOutputDirection.Input;
+ case ParameterDirection.InputOutput:
+ return OdbcInputOutputDirection.InputOutput;
+ case ParameterDirection.Output:
+ return OdbcInputOutputDirection.Output;
+ case ParameterDirection.ReturnValue:
+ return OdbcInputOutputDirection.ReturnValue;
+ default:
+ return OdbcInputOutputDirection.Input;
}
}
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLAllocHandle (OdbcHandleType HandleType, IntPtr InputHandle, ref IntPtr OutputHandlePtr);
+ internal static extern OdbcReturn SQLAllocHandle (
+ OdbcHandleType HandleType,
+ IntPtr InputHandle,
+ ref IntPtr OutputHandlePtr);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLSetEnvAttr (IntPtr EnvHandle, OdbcEnv Attribute, IntPtr Value, int StringLength);
+ internal static extern OdbcReturn SQLSetEnvAttr (
+ IntPtr EnvHandle,
+ OdbcEnv Attribute,
+ IntPtr Value,
+ int StringLength);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLConnect (IntPtr ConnectionHandle, string ServerName, short NameLength1, string UserName, short NameLength2, string Authentication, short NameLength3);
+ internal static extern OdbcReturn SQLConnect (
+ IntPtr ConnectionHandle,
+ string ServerName,
+ short NameLength1,
+ string UserName,
+ short NameLength2,
+ string Authentication,
+ short NameLength3);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLDriverConnect(IntPtr ConnectionHandle, IntPtr WindowHandle, string InConnectionString, short StringLength1, string OutConnectionString, short BufferLength, ref short StringLength2Ptr, ushort DriverCompletion);
+ internal static extern OdbcReturn SQLDriverConnect (
+ IntPtr ConnectionHandle,
+ IntPtr WindowHandle,
+ string InConnectionString,
+ short StringLength1,
+ string OutConnectionString,
+ short BufferLength,
+ ref short StringLength2Ptr,
+ ushort DriverCompletion);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLExecDirect (IntPtr StatementHandle, string StatementText, int TextLength);
+ internal static extern OdbcReturn SQLExecDirect (
+ IntPtr StatementHandle,
+ string StatementText,
+ int TextLength);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLRowCount (IntPtr StatementHandle, ref int RowCount);
+ internal static extern OdbcReturn SQLRowCount (
+ IntPtr StatementHandle,
+ ref int RowCount);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLNumResultCols (IntPtr StatementHandle, ref short ColumnCount);
+ internal static extern OdbcReturn SQLNumResultCols (
+ IntPtr StatementHandle,
+ ref short ColumnCount);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLFetch (IntPtr StatementHandle);
+ internal static extern OdbcReturn SQLFetch (
+ IntPtr StatementHandle);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLGetData (IntPtr StatementHandle, ushort ColumnNumber, SQL_C_TYPE TargetType, ref bool TargetPtr, int BufferLen, ref int Len);
+ internal static extern OdbcReturn SQLGetData (
+ IntPtr StatementHandle,
+ ushort ColumnNumber,
+ SQL_C_TYPE TargetType,
+ ref bool TargetPtr,
+ int BufferLen,
+ ref int Len);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLGetData (IntPtr StatementHandle, ushort ColumnNumber, SQL_C_TYPE TargetType, ref double TargetPtr, int BufferLen, ref int Len);
+ internal static extern OdbcReturn SQLGetData (
+ IntPtr StatementHandle,
+ ushort ColumnNumber,
+ SQL_C_TYPE TargetType,
+ ref double TargetPtr,
+ int BufferLen,
+ ref int Len);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLGetData (IntPtr StatementHandle, ushort ColumnNumber, SQL_C_TYPE TargetType, ref long TargetPtr, int BufferLen, ref int Len);
+ internal static extern OdbcReturn SQLGetData (
+ IntPtr StatementHandle,
+ ushort ColumnNumber,
+ SQL_C_TYPE TargetType,
+ ref long TargetPtr,
+ int BufferLen,
+ ref int Len);
- [DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLGetData (IntPtr StatementHandle, ushort ColumnNumber, SQL_C_TYPE TargetType, ref short TargetPtr, int BufferLen, ref int Len);
+ [DllImport("odbc32.dll")]
+ internal static extern OdbcReturn SQLGetData (
+ IntPtr StatementHandle,
+ ushort ColumnNumber,
+ SQL_C_TYPE TargetType,
+ ref short TargetPtr,
+ int BufferLen,
+ ref int Len);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLGetData (IntPtr StatementHandle, ushort ColumnNumber, SQL_C_TYPE TargetType, ref float TargetPtr, int BufferLen, ref int Len);
+ internal static extern OdbcReturn SQLGetData (
+ IntPtr StatementHandle,
+ ushort ColumnNumber,
+ SQL_C_TYPE TargetType,
+ ref float TargetPtr,
+ int BufferLen,
+ ref int Len);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLGetData (IntPtr StatementHandle, ushort ColumnNumber, SQL_C_TYPE TargetType, ref OdbcTimestamp TargetPtr, int BufferLen, ref int Len);
+ internal static extern OdbcReturn SQLGetData (
+ IntPtr StatementHandle,
+ ushort ColumnNumber,
+ SQL_C_TYPE TargetType,
+ ref OdbcTimestamp TargetPtr,
+ int BufferLen,
+ ref int Len);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLGetData (IntPtr StatementHandle, ushort ColumnNumber, SQL_C_TYPE TargetType, ref int TargetPtr, int BufferLen, ref int Len);
+ internal static extern OdbcReturn SQLGetData (
+ IntPtr StatementHandle,
+ ushort ColumnNumber,
+ SQL_C_TYPE TargetType,
+ ref int TargetPtr,
+ int BufferLen,
+ ref int Len);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLGetData (IntPtr StatementHandle, ushort ColumnNumber, SQL_C_TYPE TargetType, byte[] TargetPtr, int BufferLen, ref int Len);
+ internal static extern OdbcReturn SQLGetData (
+ IntPtr StatementHandle,
+ ushort ColumnNumber,
+ SQL_C_TYPE TargetType,
+ byte[] TargetPtr,
+ int BufferLen,
+ ref int Len);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLDescribeCol(IntPtr StatementHandle, ushort ColumnNumber, byte[] ColumnName, short BufferLength, ref short NameLength, ref short DataType, ref uint ColumnSize, ref short DecimalDigits, ref short Nullable);
+ internal static extern OdbcReturn SQLDescribeCol (
+ IntPtr StatementHandle,
+ ushort ColumnNumber,
+ byte[] ColumnName,
+ short BufferLength,
+ ref short NameLength,
+ ref short DataType,
+ ref uint ColumnSize,
+ ref short DecimalDigits,
+ ref short Nullable);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLFreeHandle(ushort HandleType, IntPtr SqlHandle);
+ internal static extern OdbcReturn SQLFreeHandle (
+ ushort HandleType,
+ IntPtr SqlHandle);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLDisconnect(IntPtr ConnectionHandle);
+ internal static extern OdbcReturn SQLDisconnect (
+ IntPtr ConnectionHandle);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLPrepare(IntPtr StatementHandle, string Statement, int TextLength);
+ internal static extern OdbcReturn SQLPrepare (
+ IntPtr StatementHandle,
+ string Statement,
+ int TextLength);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLExecute(IntPtr StatementHandle);
+ internal static extern OdbcReturn SQLExecute (
+ IntPtr StatementHandle);
+
+ [DllImport ("odbc32.dll")]
+ internal static extern OdbcReturn SQLGetConnectAttr (
+ IntPtr ConnectionHandle,
+ OdbcConnectionAttribute Attribute,
+ out int value,
+ int BufferLength,
+ out int StringLength);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLSetConnectAttr(IntPtr ConnectionHandle, OdbcConnectionAttribute Attribute, IntPtr Value, int Length);
+ internal static extern OdbcReturn SQLSetConnectAttr (
+ IntPtr ConnectionHandle,
+ OdbcConnectionAttribute Attribute,
+ IntPtr Value,
+ int Length);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLEndTran(int HandleType, IntPtr Handle, short CompletionType);
+ internal static extern OdbcReturn SQLEndTran (
+ int HandleType,
+ IntPtr Handle,
+ short CompletionType);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLBindParameter(IntPtr StatementHandle, ushort ParamNum,
- short InputOutputType, SQL_C_TYPE ValueType, SQL_TYPE ParamType, uint ColSize,
- short DecimalDigits, IntPtr ParamValue, int BufLen, IntPtr StrLen);
+ internal static extern OdbcReturn SQLBindParameter (
+ IntPtr StatementHandle,
+ ushort ParamNum,
+ short InputOutputType,
+ SQL_C_TYPE ValueType,
+ SQL_TYPE ParamType,
+ uint ColSize,
+ short DecimalDigits,
+ IntPtr ParamValue,
+ int BufLen,
+ IntPtr StrLen);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLCancel(IntPtr StatementHandle);
+ internal static extern OdbcReturn SQLCancel (
+ IntPtr StatementHandle);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLCloseCursor(IntPtr StatementHandle);
+ internal static extern OdbcReturn SQLCloseCursor (
+ IntPtr StatementHandle);
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLError(IntPtr EnvironmentHandle,\r
- IntPtr ConnectionHandle, IntPtr StatementHandle,\r
- byte[] Sqlstate, ref int NativeError,\r
- byte[] MessageText, short BufferLength,\r
- ref short TextLength);\r
-\r
+ internal static extern OdbcReturn SQLError (
+ IntPtr EnvironmentHandle,
+ IntPtr ConnectionHandle,
+ IntPtr StatementHandle,
+ byte[] Sqlstate,
+ ref int NativeError,
+ byte[] MessageText,
+ short BufferLength,
+ ref short TextLength);
+
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLGetStmtAttr(IntPtr StatementHandle,\r
- int Attribute, ref IntPtr Value, int BufLen, int StrLen);\r
-\r
+ internal static extern OdbcReturn SQLGetStmtAttr (
+ IntPtr StatementHandle,
+ int Attribute,
+ ref IntPtr Value,
+ int BufLen,
+ int StrLen);
+
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLSetDescField(IntPtr DescriptorHandle,\r
- short RecNumber, short FieldIdentifier, byte[] Value, int BufLen);\r
-
+ internal static extern OdbcReturn SQLSetDescField (
+ IntPtr DescriptorHandle,
+ short RecNumber,
+ short FieldIdentifier,
+ byte[] Value,
+ int BufLen);
+
[DllImport("odbc32.dll")]
- internal static extern OdbcReturn SQLGetDiagRec (OdbcHandleType HandleType,\r
- IntPtr Handle, ushort RecordNumber,\r
- byte [] Sqlstate, ref int NativeError,\r
- byte [] MessageText, short BufferLength,\r
- ref short TextLength);\r
+ internal static extern OdbcReturn SQLGetDiagRec (
+ OdbcHandleType HandleType,
+ IntPtr Handle,
+ ushort RecordNumber,
+ byte [] Sqlstate,
+ ref int NativeError,
+ byte [] MessageText,
+ short BufferLength,
+ ref short TextLength);
[DllImport ("odbc32.dll")]
- internal static extern OdbcReturn SQLMoreResults (IntPtr Handle);
+ internal static extern OdbcReturn SQLMoreResults (
+ IntPtr Handle);
internal enum SQLFreeStmtOptions : short
{
}
[DllImport ("odbc32.dll")]
- internal static extern OdbcReturn SQLFreeStmt (IntPtr Handle, SQLFreeStmtOptions option);
+ internal static extern OdbcReturn SQLFreeStmt (
+ IntPtr Handle,
+ SQLFreeStmtOptions option);
+
+ [DllImport ("odbc32.dll")]
+ internal static extern OdbcReturn SQLGetInfo (
+ IntPtr connHandle,
+ OdbcInfo info,
+ byte [] buffer,
+ short buffLength,
+ ref short remainingStrLen);
+
+ [DllImport ("odbc32.dll")]
+ internal static extern OdbcReturn SQLColAttribute (
+ IntPtr StmtHandle,
+ short column,
+ FieldIdentifier fieldId,
+ byte [] charAttributePtr,
+ short bufferLength,
+ ref short strLengthPtr,
+ ref int numericAttributePtr);
+
+ [DllImport ("odbc32.dll")]
+ internal static extern OdbcReturn SQLPrimaryKeys (
+ IntPtr StmtHandle,
+ string catalog,
+ short catalogLength,
+ string schema,
+ short schemaLength,
+ string tableName,
+ short tableLength);
+
+ [DllImport ("odbc32.dll")]
+ internal static extern OdbcReturn SQLStatistics (
+ IntPtr StmtHandle,
+ string catalog,
+ short catalogLength,
+ string schema,
+ short schemaLength,
+ string tableName,
+ short tableLength,
+ short unique,
+ short Reserved);
[DllImport ("odbc32.dll")]
- internal static extern OdbcReturn SQLGetInfo (IntPtr connHandle,
- OdbcInfo info,
- byte [] buffer,
- short buffLength,
- ref short remainingStrLen);
- [DllImport ("odbc32.dll")]
- internal static extern OdbcReturn SQLColAttribute (IntPtr StmtHandle,
- short column,
- FieldIdentifier fieldId,
- byte [] charAttributePtr,
- short bufferLength,
- ref short strLengthPtr,
- ref int numericAttributePtr
- );
- [DllImport ("odbc32.dll")]
- internal static extern OdbcReturn SQLPrimaryKeys (IntPtr StmtHandle,
- string catalog,
- short catalogLength,
- string schema,
- short schemaLength,
- string tableName,
- short tableLength
- );
-
- [DllImport ("odbc32.dll")]
- internal static extern OdbcReturn SQLStatistics (IntPtr StmtHandle,
- string catalog,
- short catalogLength,
- string schema,
- short schemaLength,
- string tableName,
- short tableLength,
- short unique,
- short Reserved
- );
-
- [DllImport ("odbc32.dll")]
- internal static extern OdbcReturn SQLBindCol (IntPtr StmtHandle,
- short column,
- SQL_C_TYPE targetType,
- byte [] buffer,
- int bufferLength,
- ref int indicator
- );
+ internal static extern OdbcReturn SQLBindCol (
+ IntPtr StmtHandle,
+ short column,
+ SQL_C_TYPE targetType,
+ byte [] buffer,
+ int bufferLength,
+ ref int indicator);
[DllImport ("odbc32.dll")]
- internal static extern OdbcReturn SQLBindCol (IntPtr StmtHandle,
- short column,
- SQL_C_TYPE targetType,
- ref short value,
- int bufferLength,
- ref int indicator
- );
+ internal static extern OdbcReturn SQLBindCol (
+ IntPtr StmtHandle,
+ short column,
+ SQL_C_TYPE targetType,
+ ref short value,
+ int bufferLength,
+ ref int indicator);
}
}
+2007-10-21 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * OleDbCommand.cs: Use ExceptionHelper.CheckEnumValue for enum checks.
+
+2007-10-20 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * OleDbDataAdapter.cs: In default ctor, set SelectCommand to null.
+ Only initialize SelectCommand in ctors. Use direct assignment in
+ IDbDataAdapter implementation.
+ * OleDbCommand.cs: Added constant for default CommandTimeout, instead
+ of using a magic number. Avoid unnecessary initialization. Fixed
+ default value for DesignTimeVisible. Return zero-length string if
+ CommandText is null. Added implementation for UpdatedRowSource.
+ * OleDbConnection.cs: Moved initialization of gda to Open ().
+ Avoid unnecessary initialization. Return zero-length string if
+ ConnectionString is null. If getters to Database, DataSource and
+ Provider return zero-length string if the connection is closed.
+ In ServerVersion, BeginTransaction and GetSchema, throw an
+ InvalidOperationException if connection is closed.
+
+2007-10-19 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * OleDbTransaction.cs: Clear connection in Commit and Rollback. In
+ IsolationLevel and Begin overloads, throw IOE if transaction is no
+ longer open.
+
+2007-10-19 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * OleDbTransaction.cs: Keep track of whether transaction is open and
+ whether it's disposed. In Commit an Rollback, throw an IOE if the
+ transaction is no longer open. In Dispose (bool), perform a rollback
+ if the transaction is still open.
+
+2007-10-19 Nagappan <anagappan@novell.com>
+
+ * OleDbCommandBuilder.cs: Implemented ApplyParameterInfo, Dispose,
+ GetParameterName, GetParameterPlaceholder, RefreshSchema methods.
+
+2007-10-19 Nagappan <anagappan@novell.com>
+
+ * OleDbCommand.cs: Implemented Clone, Dispose methods.
+ Implemented CreateDbParameter, DbConnection, DbParameterCollection,
+ DbTransaction, ExecuteDbDataReader properties.
+
+ * OleDbParameterCollection.cs: Fixed 1.0 API compatibility.
+
2007-09-27 Nagappan A <anagappan@novell.com>
* OleDbDataReader.cs: Removed bogus MonoTODO.
{
#region Fields
+ const int DEFAULT_COMMAND_TIMEOUT = 30;
+
string commandText;
int timeout;
CommandType commandType;
OleDbDataReader dataReader;
CommandBehavior behavior;
IntPtr gdaCommand;
+ UpdateRowSource updatedRowSource;
+ bool disposed;
+
#endregion // Fields
#region Constructors
public OleDbCommand ()
{
- commandText = String.Empty;
- timeout = 30; // default timeout per .NET
+ timeout = DEFAULT_COMMAND_TIMEOUT;
commandType = CommandType.Text;
parameters = new OleDbParameterCollection ();
behavior = CommandBehavior.Default;
gdaCommand = IntPtr.Zero;
+ designTimeVisible = true;
+ this.updatedRowSource = UpdateRowSource.Both;
}
public OleDbCommand (string cmdText) : this ()
#if NET_2_0
override
#endif
- string CommandText
- {
+ string CommandText {
get {
+ if (commandText == null)
+ return string.Empty;
return commandText;
}
set {
#if !NET_2_0
[DataSysDescriptionAttribute ("Time to wait for command to execute.")]
- [DefaultValue (30)]
+ [DefaultValue (DEFAULT_COMMAND_TIMEOUT)]
#endif
public
#if NET_2_0
}
[DataCategory ("Data")]
-#if !NET_2_0
+#if ONLY_1_1
[DataSysDescriptionAttribute ("The parameters collection.")]
#endif
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
public new OleDbParameterCollection Parameters {
- get {
- return parameters;
- }
+ get { return parameters; }
+ internal set { parameters = value; }
}
[BrowsableAttribute (false)]
-#if !NET_2_0
+#if ONLY_1_1
[DataSysDescriptionAttribute ("The transaction used by the command.")]
#endif
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
#if !NET_2_0
[DataSysDescriptionAttribute ("When used by a DataAdapter.Update, how command results are applied to the current DataRow.")]
#endif
+ [MonoTODO]
public
#if NET_2_0
override
#endif
UpdateRowSource UpdatedRowSource {
- [MonoTODO]
- get {
- throw new NotImplementedException ();
- }
- [MonoTODO]
+ get { return updatedRowSource; }
set {
- throw new NotImplementedException ();
+ ExceptionHelper.CheckEnumValue (typeof (UpdateRowSource), value);
+ updatedRowSource = value;
}
}
}
#endif
- [MonoTODO]
protected override void Dispose (bool disposing)
{
- throw new NotImplementedException ();
+ if (disposed)
+ return;
+
+ Connection = null;
+ Transaction = null;
+ disposed = true;
}
private void SetupGdaCommand ()
}
if (gdaCommand != IntPtr.Zero) {
- libgda.gda_command_set_text (gdaCommand, commandText);
+ libgda.gda_command_set_text (gdaCommand, CommandText);
libgda.gda_command_set_command_type (gdaCommand, type);
} else {
- gdaCommand = libgda.gda_command_new (commandText, type, 0);
+ gdaCommand = libgda.gda_command_new (CommandText, type, 0);
}
//libgda.gda_command_set_transaction
}
#if NET_2_0
- [MonoTODO]
- public OleDbCommand Clone ()
+ public
+#else
+ internal
+#endif
+ OleDbCommand Clone ()
{
- throw new NotImplementedException ();
+ OleDbCommand command = new OleDbCommand ();
+ command.CommandText = this.CommandText;
+ command.CommandTimeout = this.CommandTimeout;
+ command.CommandType = this.CommandType;
+ command.Connection = this.Connection;
+ command.DesignTimeVisible = this.DesignTimeVisible;
+ command.Parameters = this.Parameters;
+ command.Transaction = this.Transaction;
+ return command;
}
-#endif
- [MonoTODO]
object ICloneable.Clone ()
{
- throw new NotImplementedException ();
+ return Clone ();
}
[MonoTODO]
public void ResetCommandTimeout ()
{
- timeout = 30;
+ timeout = DEFAULT_COMMAND_TIMEOUT;
}
#if NET_2_0
- [MonoTODO]
protected override DbParameter CreateDbParameter ()
{
- throw new NotImplementedException ();
+ return (DbParameter) CreateParameter ();
}
- [MonoTODO]
protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
{
- throw new NotImplementedException ();
+ return (DbDataReader) ExecuteReader (behavior);
}
- [MonoTODO]
protected override DbConnection DbConnection {
- get { throw new NotImplementedException (); }
- set { throw new NotImplementedException (); }
+ get { return Connection; }
+ set { Connection = (OleDbConnection) value; }
}
- [MonoTODO]
protected override DbParameterCollection DbParameterCollection {
- get { throw new NotImplementedException (); }
+ get { return Parameters; }
}
- [MonoTODO]
protected override DbTransaction DbTransaction {
- get { throw new NotImplementedException (); }
- set { throw new NotImplementedException (); }
+ get { return Transaction; }
+ set { Transaction = (OleDbTransaction) value; }
}
#endif
#region Fields
OleDbDataAdapter adapter;
-#if !NET_2_0
+#if ONLY_1_1
string quotePrefix;
string quoteSuffix;
#endif
+ private DataTable _schema;
+ private string _tableName;
+ private OleDbCommand _insertCommand;
+ private OleDbCommand _updateCommand;
+ private OleDbCommand _deleteCommand;
+
+ bool _disposed;
#endregion // Fields
#region Constructors
#region Methods
#if NET_2_0
- [MonoTODO]
- protected override void ApplyParameterInfo (DbParameter parameter, DataRow datarow, StatementType statementType, bool whereClause)
+ protected override void ApplyParameterInfo (DbParameter dbParameter,
+ DataRow row,
+ StatementType statementType,
+ bool whereClause)
{
- throw new NotImplementedException ();
+ OleDbParameter parameter = (OleDbParameter) dbParameter;
+ parameter.Size = int.Parse (row ["ColumnSize"].ToString ());
+ if (row ["NumericPrecision"] != DBNull.Value) {
+ parameter.Precision = byte.Parse (row ["NumericPrecision"].ToString ());
+ }
+ if (row ["NumericScale"] != DBNull.Value) {
+ parameter.Scale = byte.Parse (row ["NumericScale"].ToString ());
+ }
+ parameter.DbType = (DbType) row ["ProviderType"];
}
#endif
+ [MonoTODO]
public static void DeriveParameters (OleDbCommand command)
{
+ if (command.CommandType != CommandType.StoredProcedure) {
+ throw new InvalidOperationException ("You can perform this " +
+ "operation only on CommandTye" +
+ " StoredProcedure");
+ }
+ // FIXME: Retrive info from server
throw new NotImplementedException ();
}
#if ONLY_1_1
- [MonoTODO]
protected override void Dispose (bool disposing)
{
- throw new NotImplementedException ();
+ if (_disposed)
+ return;
+
+ if (disposing) {
+ // dispose managed resource
+ if (_insertCommand != null) _insertCommand.Dispose ();
+ if (_updateCommand != null) _updateCommand.Dispose ();
+ if (_deleteCommand != null) _deleteCommand.Dispose ();
+
+ _insertCommand = null;
+ _updateCommand = null;
+ _deleteCommand = null;
+ _schema = null;
+ }
+ _disposed = true;
}
#endif
throw new NotImplementedException ();
}
- [MonoTODO]
- protected override string GetParameterName (int parameterOrdinal)
+ protected override string GetParameterName (int position)
{
- throw new NotImplementedException ();
+ return String.Format("@p{0}", position);
}
protected override string GetParameterName (string parameterName)
{
- return parameterName;
+ return String.Format("@{0}", parameterName);
}
-
- [MonoTODO]
- protected override string GetParameterPlaceholder(int parameterOrdinal)
+
+ protected override string GetParameterPlaceholder (int position)
{
- throw new NotImplementedException ();
+ return GetParameterName (position);
}
+
#endif
[MonoTODO]
throw new NotImplementedException ();
}
+ private OleDbCommand SelectCommand
+ {
+ get {
+ if (DataAdapter == null)
+ return null;
+ return DataAdapter.SelectCommand;
+ }
+ }
+
#if NET_2_0
[MonoTODO]
public new OleDbCommand GetUpdateCommand (bool useColumnsForParameterNames)
throw new NotImplementedException ();
}
#else
- [MonoTODO]
public void RefreshSchema ()
{
- throw new NotImplementedException ();
+ // creates metadata
+ if (SelectCommand == null)
+ throw new InvalidOperationException ("SelectCommand should be valid");
+ if (SelectCommand.Connection == null)
+ throw new InvalidOperationException ("SelectCommand's Connection should be valid");
+
+ CommandBehavior behavior = CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
+ if (SelectCommand.Connection.State != ConnectionState.Open) {
+ SelectCommand.Connection.Open ();
+ behavior |= CommandBehavior.CloseConnection;
+ }
+
+ OleDbDataReader reader = SelectCommand.ExecuteReader (behavior);
+ _schema = reader.GetSchemaTable ();
+ reader.Close ();
+
+ // force creation of commands
+ _insertCommand = null;
+ _updateCommand = null;
+ _deleteCommand = null;
+ _tableName = String.Empty;
}
#endif
public OleDbConnection ()
{
- libgda.gda_init ("System.Data.OleDb", "1.0", 0, new string [0]);
gdaConnection = IntPtr.Zero;
connectionTimeout = 15;
- connectionString = null;
}
public OleDbConnection (string connectionString) : this ()
#endif
string ConnectionString {
get {
+ if (connectionString == null)
+ return string.Empty;
return connectionString;
}
set {
return libgda.gda_connection_get_database (gdaConnection);
}
- return null;
+ return string.Empty;
}
}
return libgda.gda_connection_get_dsn (gdaConnection);
}
- return null;
+ return string.Empty;
}
}
return libgda.gda_connection_get_provider (gdaConnection);
}
- return null;
+ return string.Empty;
}
}
#endif
string ServerVersion {
get {
- if (gdaConnection != IntPtr.Zero
- && libgda.gda_connection_is_open (gdaConnection)) {
- return libgda.gda_connection_get_server_version (gdaConnection);
- }
-
- return null;
+ if (State == ConnectionState.Closed)
+ throw ExceptionHelper.ConnectionClosed ();
+ return libgda.gda_connection_get_server_version (gdaConnection);
}
}
public new OleDbTransaction BeginTransaction ()
{
- if (gdaConnection != IntPtr.Zero)
- return new OleDbTransaction (this);
-
- return null;
+ if (State == ConnectionState.Closed)
+ throw ExceptionHelper.ConnectionClosed ();
+ return new OleDbTransaction (this);
}
public new OleDbTransaction BeginTransaction (IsolationLevel level)
{
- if (gdaConnection != IntPtr.Zero)
- return new OleDbTransaction (this, level);
-
- return null;
+ if (State == ConnectionState.Closed)
+ throw ExceptionHelper.ConnectionClosed ();
+ return new OleDbTransaction (this, level);
}
#if NET_2_0
#endif
void ChangeDatabase (string name)
{
- if (gdaConnection == IntPtr.Zero)
- throw new ArgumentException ();
if (State != ConnectionState.Open)
throw new InvalidOperationException ();
void Open ()
{
string provider = "Default";
- string gdaCncStr = "";
+ string gdaCncStr = string.Empty;
string[] args;
int len;
char [] separator = { ';' };
if (State == ConnectionState.Open)
throw new InvalidOperationException ();
+ libgda.gda_init ("System.Data.OleDb", "1.0", 0, new string [0]);
+
gdaConnection = libgda.gda_client_open_connection (libgda.GdaClient,
- connectionString, "", "", 0);
+ ConnectionString, string.Empty, string.Empty, 0);
- if (gdaConnection==IntPtr.Zero)
- throw new OleDbException (this);
+ if (gdaConnection == IntPtr.Zero)
+ throw new OleDbException (this);
/* convert the connection string to its GDA equivalent */
//args = connectionString.Split (';');
//len = args.Length;
[MonoTODO]
public override DataTable GetSchema ()
{
+ if (State == ConnectionState.Closed)
+ throw ExceptionHelper.ConnectionClosed ();
throw new NotImplementedException ();
}
[MonoTODO]
public override DataTable GetSchema (String collectionName, string [] restrictionValues)
{
+ if (State == ConnectionState.Closed)
+ throw ExceptionHelper.ConnectionClosed ();
throw new NotImplementedException ();
}
#region Constructors
- public OleDbDataAdapter ()
- : this (new OleDbCommand ())
+ public OleDbDataAdapter () : this ((OleDbCommand) null)
{
}
public OleDbDataAdapter (OleDbCommand selectCommand)
{
- DeleteCommand = new OleDbCommand ();
- InsertCommand = new OleDbCommand ();
SelectCommand = selectCommand;
- UpdateCommand = new OleDbCommand ();
}
public OleDbDataAdapter (string selectCommandText, OleDbConnection selectConnection)
#endif
[EditorAttribute ("Microsoft.VSDesigner.Data.Design.DBCommandEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing)]
public new OleDbCommand UpdateCommand {
- get {
- return updateCommand;
- }
- set {
- updateCommand = value;
- }
+ get { return updateCommand; }
+ set { updateCommand = value; }
}
IDbCommand IDbDataAdapter.DeleteCommand {
- get {
- return DeleteCommand;
- }
- set {
- if (!(value is OleDbCommand))
- throw new ArgumentException ();
- DeleteCommand = (OleDbCommand)value;
- }
+ get { return DeleteCommand; }
+ set { DeleteCommand = (OleDbCommand) value; }
}
IDbCommand IDbDataAdapter.InsertCommand {
- get {
- return InsertCommand;
- }
- set {
- if (!(value is OleDbCommand))
- throw new ArgumentException ();
- InsertCommand = (OleDbCommand)value;
- }
+ get { return InsertCommand; }
+ set { InsertCommand = (OleDbCommand) value; }
}
IDbCommand IDbDataAdapter.SelectCommand {
return SelectCommand;
}
set {
- if (!(value is OleDbCommand))
- throw new ArgumentException ();
- SelectCommand = (OleDbCommand)value;
+ SelectCommand = (OleDbCommand) value;
}
}
MissingMappingAction IDataAdapter.MissingMappingAction {
- get {
- return missingMappingAction;
- }
- set {
- missingMappingAction = value;
- }
+ get { return missingMappingAction; }
+ set { missingMappingAction = value; }
}
MissingSchemaAction IDataAdapter.MissingSchemaAction {
- get {
- return missingSchemaAction;
- }
- set {
- missingSchemaAction = value;
- }
+ get { return missingSchemaAction; }
+ set { missingSchemaAction = value; }
}
IDbCommand IDbDataAdapter.UpdateCommand {
- get {
- return UpdateCommand;
- }
- set {
- if (!(value is OleDbCommand))
- throw new ArgumentException ();
- UpdateCommand = (OleDbCommand)value;
- }
+ get { return UpdateCommand; }
+ set { UpdateCommand = (OleDbCommand) value; }
}
ITableMappingCollection IDataAdapter.TableMappings {
- get {
- return TableMappings;
- }
+ get { return TableMappings; }
}
#endregion // Properties
#region Properties
-#if !NET_2_0
+#if ONLY_1_1
[Browsable (false)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
#endif
[Browsable (false)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public new OleDbParameter this[int index] {
- get { return (OleDbParameter) list[index]; }
- set { list[index] = value; }
+ get { return (OleDbParameter) list [index]; }
+ set { list[index] = (OleDbParameter) value; }
}
[Browsable (false)]
set {
if (!Contains (parameterName))
throw new IndexOutOfRangeException("The specified name does not exist: " + parameterName);
- this [IndexOf (parameterName)] = value;
+ this [IndexOf (parameterName)] = (OleDbParameter) value;
}
}
{
#region Fields
+ bool disposed;
OleDbConnection connection;
IntPtr gdaTransaction;
int depth;
+ bool isOpen;
#endregion // Fields
}
libgda.gda_connection_begin_transaction (connection.GdaConnection, gdaTransaction);
+ isOpen = true;
}
internal OleDbTransaction (OleDbConnection connection, IsolationLevel isolevel)
#endif
IsolationLevel IsolationLevel {
get {
+ if (!isOpen)
+ throw ExceptionHelper.TransactionNotUsable (GetType ());
+
switch (libgda.gda_transaction_get_isolation_level (gdaTransaction)) {
case GdaTransactionIsolation.ReadCommitted :
return IsolationLevel.ReadCommitted;
public OleDbTransaction Begin ()
{
+ if (!isOpen)
+ throw ExceptionHelper.TransactionNotUsable (GetType ());
return new OleDbTransaction (connection, depth + 1);
}
public OleDbTransaction Begin (IsolationLevel isolevel)
{
+ if (!isOpen)
+ throw ExceptionHelper.TransactionNotUsable (GetType ());
return new OleDbTransaction (connection, depth + 1, isolevel);
}
#endif
void Commit ()
{
+ if (!isOpen)
+ throw ExceptionHelper.TransactionNotUsable (GetType ());
+
if (!libgda.gda_connection_commit_transaction (connection.GdaConnection,
- gdaTransaction))
+ gdaTransaction))
throw new InvalidOperationException ();
+ connection = null;
+ isOpen = false;
}
#if ONLY_1_1
#endif
#if NET_2_0
- protected override void Dispose (bool disposing)
+ protected override
+#endif
+ void Dispose (bool disposing)
{
+ if (!disposed) {
+ if (disposing && isOpen)
+ Rollback ();
+ disposed = true;
+ }
+
+#if NET_2_0
base.Dispose (disposing);
+#endif
}
-#else
+
void IDisposable.Dispose ()
{
- GC.SuppressFinalize (this);
+ Dispose (true);
}
-#endif
public
#if NET_2_0
#endif
void Rollback ()
{
+ if (!isOpen)
+ throw ExceptionHelper.TransactionNotUsable (GetType ());
+
if (!libgda.gda_connection_rollback_transaction (connection.GdaConnection,
- gdaTransaction))
+ gdaTransaction))
throw new InvalidOperationException ();
+ connection = null;
+ isOpen = false;
}
#endregion // Methods
+2007-10-21 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * SqlCommand.cs: Use ExceptionHelper.CheckEnumValue for enum checks.
+
+2007-10-20 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * SqlCommand.cs: Added constant for default CommandTimeout, instead
+ of using a magic number. Avoid unnecessary initialization. Fixed
+ default value for DesignTimeVisible. Return zero-length string if
+ CommandText is null. Use ExceptionHelper.InvalidEnumValueException
+ to avoid code duplication. Spaces to tabs and code formatting.
+ * SqlConnection.cs: Use different default package size on 2.0 profile.
+ Added constants for default values, instead of using magic numbers.
+ Avoid unnecessary initialization. In PacketSize, return default or
+ configured packet size when connection is not open. Use
+ ExceptionHelper.ConnectionClosed instead of local method. Removed
+ use of some hardcoded values in SetDefaultConnectionParameters, and
+ use Environment.MachineName as default WorkstationId instead of
+ DNS host name. Code formatting.
+ * SqlDataAdapter.cs: In default ctor, set SelectCommand to null.
+ Avoid unnecessary initializations. Use direct assignment in
+ IDbDataAdapter implementation. Fixed exception message for negative
+ UpdateBatchSize. In Dispose override, make sure to invoke base
+ method.
+
+2007-10-19 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * SqlTransaction.cs: Clear connection in commit. In IsolationLevel,
+ throw IOE if transaction is no longer open.
+
+2007-10-19 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * SqlTransaction.cs: Avoid unnecessary initialization. Remove
+ isRolledBack since its essentially the same as isOpen. Use
+ ExceptionHelper.TransactionNotUsable instead of duplicating code.
+ On 2.0 profile, ignore call to Rollback when transaction was already
+ disposed.
+
+2007-10-18 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * SqlConnection.cs: Avoid unnecessary initialization. Use string.Empty
+ for assigning zero-length string, and use String.Length to check for
+ zero-length string. Added support for IsolationLevel.Snapshot.
+ Added StructuredTypeMembers schema collection and restrictions. Fixed
+ table name for MetaDataCollections collection. Implemented
+ DataSourceInformation collection. Added missing data types (probably
+ introduced in 2.0 SP1). In GetSchema, throw InvalidOperationException
+ if connection is closed and throw NotImplementedException for
+ StructuredTypeMembers collection.
+
+2007-10-18 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * SqlConnection.cs: On 1.0 profile, IsolationLevel.Unspecified is
+ not valid. On 2.0 profile, when IsolationLevel.Unspecified is passed
+ make sure to also set SqlTransaction.IsolationLevel to
+ ReadCommitted. Modified exceptions to match MS.
+
+2007-10-17 Nagappan <anagappan@novell.com>
+
+ * SqlParameter.cs (ConvertToFrameworkType): Added SqlDbType.Image.
+
+2007-10-17 Nagappan <anagappan@novell.com>
+
+ * SqlConnection.cs: BeginTransaction does not handle
+ IsolationLevel.Unspecified, so the default is set as ReadCommited.
+ Thanks to Jerome Haltom <wasabi@larvalstage.net> for this patch. Fixes
+ bug # 333082.
+ * SqlTransaction.cs: If transaction count is greater then 0 then roll back.
+ Thanks to Jerome Haltom <wasabi@larvalstage.net> for this patch. Fixes
+ bug # 331953.
+
+2007-10-15 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * SqlException.cs: Do not hide Message on 2.0 profile. Fixes bug
+ #333901.
+
2007-10-08 Marek Safar <marek.safar@gmail.com>
* SqlParameterCollection.cs (SetParameter): Fixed missing cast.
{
#region Fields
- bool disposed = false;
+ const int DEFAULT_COMMAND_TIMEOUT = 30;
+
+ bool disposed;
int commandTimeout;
bool designTimeVisible;
string commandText;
UpdateRowSource updatedRowSource;
CommandBehavior behavior = CommandBehavior.Default;
SqlParameterCollection parameters;
- string preparedStatement = null;
+ string preparedStatement;
#if NET_2_0
SqlNotificationRequest notification;
-#endif
bool notificationAutoEnlist;
+#endif
#endregion // Fields
this.commandType = CommandType.Text;
this.updatedRowSource = UpdateRowSource.Both;
- this.designTimeVisible = false;
- this.commandTimeout = 30;
+ this.commandTimeout = DEFAULT_COMMAND_TIMEOUT;
+#if NET_2_0
notificationAutoEnlist = true;
+#endif
+ designTimeVisible = true;
parameters = new SqlParameterCollection (this);
}
override
#endif //NET_2_0
string CommandText {
- get { return commandText; }
- set {
+ get {
+ if (commandText == null)
+ return string.Empty;
+ return commandText;
+ }
+ set {
if (value != commandText && preparedStatement != null)
Unprepare ();
commandText = value;
#if !NET_2_0
[DataSysDescription ("Time to wait for command to execute.")]
- [DefaultValue (30)]
+ [DefaultValue (DEFAULT_COMMAND_TIMEOUT)]
#endif
public
#if NET_2_0
throw new ArgumentException ("CommandType.TableDirect is not supported by the Mono SqlClient Data Provider.");
#endif
- if (!Enum.IsDefined (typeof (CommandType), value))
-#if NET_2_0
- throw new ArgumentOutOfRangeException (String.Format ("The CommandType enumeration value, {0}, is invalid",
- value));
-#else
- throw ExceptionHelper.InvalidEnumValueException ("CommandType", value);
-#endif
+ ExceptionHelper.CheckEnumValue (typeof (CommandType), value);
commandType = value;
}
}
#endif // NET_2_0
UpdateRowSource UpdatedRowSource {
get { return updatedRowSource; }
- set {
- if (!Enum.IsDefined (typeof (UpdateRowSource), value))
-#if NET_2_0
- throw new ArgumentOutOfRangeException (String.Format ("The UpdateRowSource enumeration value, {0}, is invalid",
- value));
-#else
- throw ExceptionHelper.InvalidEnumValueException ("UpdateRowSource", value);
-#endif
+ set {
+ ExceptionHelper.CheckEnumValue (typeof (UpdateRowSource), value);
updatedRowSource = value;
}
}
#if NET_2_0
[Browsable (false)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
- public SqlNotificationRequest Notification {
- get { return notification; }
+ public SqlNotificationRequest Notification {
+ get { return notification; }
set { notification = value; }
}
[DefaultValue (true)]
- public bool NotificationAutoEnlist {
- get { return notificationAutoEnlist; }
+ public bool NotificationAutoEnlist {
+ get { return notificationAutoEnlist; }
set { notificationAutoEnlist = value; }
}
#endif
ValidateCommand ("DeriveParameters");
SqlParameterCollection localParameters = new SqlParameterCollection (this);
- localParameters.Add ("@procedure_name", SqlDbType.NVarChar, commandText.Length).Value = commandText;
+ localParameters.Add ("@procedure_name", SqlDbType.NVarChar, CommandText.Length).Value = CommandText;
string sql = "sp_procedure_params_rowset";
public void ResetCommandTimeout ()
{
- commandTimeout = 30;
+ commandTimeout = DEFAULT_COMMAND_TIMEOUT;
}
private void Unprepare ()
#else
throw new InvalidOperationException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
#endif
- if (commandText == String.Empty || commandText == null)
+ if (CommandText.Length == 0)
throw new InvalidOperationException ("The command text for this Command has not been set.");
if (Connection.DataReader != null)
throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
#endif // NET_2_0
{
#region Fields
- bool disposed = false;
+ bool disposed;
// The set of SQL connection pools
static TdsConnectionPoolManager sqlConnectionPools = new TdsConnectionPoolManager (TdsVersion.tds70);
+#if NET_2_0
+ const int DEFAULT_PACKETSIZE = 8000;
+#else
+ const int DEFAULT_PACKETSIZE = 8192;
+#endif
+ const int DEFAULT_CONNECTIONTIMEOUT = 15;
+ const int DEFAULT_MAXPOOLSIZE = 100;
+ const int DEFAULT_MINPOOLSIZE = 0;
+ const int DEFAULT_PORT = 1433;
// The current connection pool
TdsConnectionPool pool;
// The connection string that identifies this connection
- string connectionString = null;
+ string connectionString;
// The transaction object for the current transaction
- SqlTransaction transaction = null;
+ SqlTransaction transaction;
// Connection parameters
TdsConnectionParameters parms = new TdsConnectionParameters ();
- NameValueCollection connStringParameters = null;
+ NameValueCollection connStringParameters;
bool connectionReset;
bool pooling;
string dataSource;
int minPoolSize;
int maxPoolSize;
int packetSize;
- int port = 1433;
+ int port;
bool fireInfoMessageEventOnUserErrors;
bool statisticsEnabled;
// The current state
ConnectionState state = ConnectionState.Closed;
- SqlDataReader dataReader = null;
- XmlReader xmlReader = null;
+ SqlDataReader dataReader;
+ XmlReader xmlReader;
// The TDS object
ITds tds;
private void Init (string connectionString)
{
- connectionTimeout = 15; // default timeout
- dataSource = ""; // default datasource
- packetSize = 8192; // default packetsize
- ConnectionString = connectionString;
+ connectionTimeout = DEFAULT_CONNECTIONTIMEOUT;
+ dataSource = string.Empty;
+ packetSize = DEFAULT_PACKETSIZE;
+ port = DEFAULT_PORT;
+ ConnectionString = connectionString;
}
#endregion // Constructors
override
#endif // NET_2_0
string ConnectionString {
- get { return connectionString; }
+ get {
+ if (connectionString == null)
+ return string.Empty;
+ return connectionString;
+ }
[MonoTODO("persist security info, encrypt, enlist keyword not implemented")]
set {
if (state == ConnectionState.Open)
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public int PacketSize {
get {
- if (State == ConnectionState.Open)
- return ((Tds)tds).PacketSize ;
- return packetSize;
+ if (State == ConnectionState.Open)
+ return ((Tds) tds).PacketSize;
+ return packetSize;
}
}
string ServerVersion {
get {
if (state == ConnectionState.Closed)
- throw new InvalidOperationException ("Invalid Operation.The Connection is Closed");
+ throw ExceptionHelper.ConnectionClosed ();
else
return tds.ServerVersion;
}
internal string GetConnStringKeyValue (params string [] keys)
{
if (connStringParameters == null || connStringParameters.Count == 0)
- return "";
+ return string.Empty;
+
foreach (string key in keys) {
string value = connStringParameters [key];
if (value != null)
return value;
}
- return "";
+ return string.Empty;
}
public new SqlTransaction BeginTransaction ()
public SqlTransaction BeginTransaction (IsolationLevel iso, string transactionName)
{
if (state == ConnectionState.Closed)
- throw new InvalidOperationException ("The connection is not open.");
+ throw ExceptionHelper.ConnectionClosed ();
if (transaction != null)
throw new InvalidOperationException ("SqlConnection does not support parallel transactions.");
- if (iso == IsolationLevel.Chaos)
- throw new ArgumentException ("Invalid IsolationLevel parameter: must be ReadCommitted, ReadUncommitted, RepeatableRead, or Serializable.");
-
string isolevel = String.Empty;
switch (iso) {
- case IsolationLevel.ReadCommitted:
- isolevel = "READ COMMITTED";
- break;
case IsolationLevel.ReadUncommitted:
isolevel = "READ UNCOMMITTED";
break;
case IsolationLevel.Serializable:
isolevel = "SERIALIZABLE";
break;
+ case IsolationLevel.ReadCommitted:
+ isolevel = "READ COMMITTED";
+ break;
+#if NET_2_0
+ case IsolationLevel.Snapshot:
+ isolevel = "SNAPSHOT";
+ break;
+ case IsolationLevel.Unspecified:
+ iso = IsolationLevel.ReadCommitted;
+ isolevel = "READ COMMITTED";
+ break;
+ case IsolationLevel.Chaos:
+ throw new ArgumentOutOfRangeException ("IsolationLevel",
+ string.Format (CultureInfo.CurrentCulture,
+ "The IsolationLevel enumeration " +
+ "value, {0}, is not supported by " +
+ "the .Net Framework SqlClient " +
+ "Data Provider.", (int) iso));
+#endif
+ default:
+#if NET_2_0
+ throw new ArgumentOutOfRangeException ("IsolationLevel",
+ string.Format (CultureInfo.CurrentCulture,
+ "The IsolationLevel enumeration value, {0}, is invalid.",
+ (int) iso));
+#else
+ throw new ArgumentException ("Invalid IsolationLevel parameter: must be ReadCommitted, ReadUncommitted, RepeatableRead, or Serializable.");
+#endif
}
tds.Execute (String.Format ("SET TRANSACTION ISOLATION LEVEL {0};BEGIN TRANSACTION {1}", isolevel, transactionName));
#if NET_2_0
override
#endif // NET_2_0
- void ChangeDatabase (string database)
+ void ChangeDatabase (string database)
{
if (!IsValidDatabaseName (database))
throw new ArgumentException (String.Format ("The database name {0} is not valid.", database));
if (disposing) {
if (State == ConnectionState.Open)
Close ();
- ConnectionString = "";
+ ConnectionString = string.Empty;
SetDefaultConnectionParameters (this.connStringParameters);
}
} finally {
#endif // NET_2_0
void Open ()
{
- string serverName = "";
+ string serverName = string.Empty;
if (state == ConnectionState.Open)
throw new InvalidOperationException ("The Connection is already Open (State=Open)");
private bool ParseDataSource (string theDataSource, out int thePort, out string theServerName)
{
- theServerName = "";
- string theInstanceName = "";
+ theServerName = string.Empty;
+ string theInstanceName = string.Empty;
if (theDataSource == null)
throw new ArgumentException("Format of initialization string does not conform to specifications");
- thePort = 1433; // default TCP port for SQL Server
+ thePort = DEFAULT_PORT; // default TCP port for SQL Server
bool success = true;
int idx = 0;
theServerName = theDataSource.Substring (0, idx);
string p = theDataSource.Substring (idx + 1);
thePort = Int32.Parse (p);
- }
- else if ((idx = theDataSource.IndexOf ("\\")) > -1) {
+ } else if ((idx = theDataSource.IndexOf ("\\")) > -1) {
theServerName = theDataSource.Substring (0, idx);
theInstanceName = theDataSource.Substring (idx + 1);
// do port discovery via UDP port 1434
port = DiscoverTcpPortViaSqlMonitor (theServerName, theInstanceName);
if (port == -1)
success = false;
- }
- else if (theDataSource == "" || theDataSource == "(local)")
+ } else if (theDataSource.Length == 0 || theDataSource == "(local)")
theServerName = "localhost";
else
theServerName = theDataSource;
- if ((idx = theServerName.IndexOf ("tcp:")) > -1) {
+ if ((idx = theServerName.IndexOf ("tcp:")) > -1)
theServerName = theServerName.Substring (idx + 4);
- }
return success;
}
private bool ConvertIntegratedSecurity (string value)
{
- if (value.ToUpper() == "SSPI")
- {
+ if (value.ToUpper() == "SSPI")
return true;
- }
return ConvertToBoolean("integrated security", value);
}
- private bool ConvertToBoolean(string key, string value)
+ private bool ConvertToBoolean (string key, string value)
{
- string upperValue = value.ToUpper();
+ string upperValue = value.ToUpper ();
- if (upperValue == "TRUE" ||upperValue == "YES")
- {
+ if (upperValue == "TRUE" || upperValue == "YES")
return true;
- }
else if (upperValue == "FALSE" || upperValue == "NO")
- {
return false;
- }
- throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
+ throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
"Invalid value \"{0}\" for key '{1}'.", value, key));
}
- private int ConvertToInt32(string key, string value)
+ private int ConvertToInt32 (string key, string value)
{
- try
- {
- return int.Parse(value);
+ try {
+ return int.Parse (value);
} catch (Exception ex) {
- throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
+ throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
"Invalid value \"{0}\" for key '{1}'.", value, key));
}
}
- private int DiscoverTcpPortViaSqlMonitor(string ServerName, string InstanceName)
+ private int DiscoverTcpPortViaSqlMonitor (string ServerName, string InstanceName)
{
SqlMonitorSocket msock;
msock = new SqlMonitorSocket (ServerName, InstanceName);
void SetDefaultConnectionParameters (NameValueCollection parameters)
{
parms.Reset ();
- dataSource = "";
- connectionTimeout= 15;
+ dataSource = string.Empty;
+ connectionTimeout = DEFAULT_CONNECTIONTIMEOUT;
connectionReset = true;
pooling = true;
- maxPoolSize = 100;
- minPoolSize = 0;
- packetSize = 8192;
+ maxPoolSize = DEFAULT_MAXPOOLSIZE;
+ minPoolSize = DEFAULT_MINPOOLSIZE;
+ packetSize = DEFAULT_PACKETSIZE;
parameters["APPLICATION NAME"] = "Mono SqlClient Data Provider";
- parameters["CONNECT TIMEOUT"] = "15";
+ parameters["CONNECT TIMEOUT"] = connectionTimeout.ToString (CultureInfo.InvariantCulture);
parameters["CONNECTION LIFETIME"] = "0";
parameters["CONNECTION RESET"] = "true";
parameters["ENLIST"] = "true";
parameters["INTEGRATED SECURITY"] = "false";
- parameters["INITIAL CATALOG"] = "";
- parameters["MAX POOL SIZE"] = "100";
- parameters["MIN POOL SIZE"] = "0";
+ parameters["INITIAL CATALOG"] = string.Empty;
+ parameters["MAX POOL SIZE"] = maxPoolSize.ToString (CultureInfo.InvariantCulture);
+ parameters["MIN POOL SIZE"] = minPoolSize.ToString (CultureInfo.InvariantCulture);
parameters["NETWORK LIBRARY"] = "dbmssocn";
- parameters["PACKET SIZE"] = "8192";
+ parameters["PACKET SIZE"] = packetSize.ToString (CultureInfo.InvariantCulture);
parameters["PERSIST SECURITY INFO"] = "false";
parameters["POOLING"] = "true";
- parameters["WORKSTATION ID"] = Dns.GetHostName();
+ parameters["WORKSTATION ID"] = Environment.MachineName;
#if NET_2_0
async = false;
parameters ["ASYNCHRONOUS PROCESSING"] = "false";
private void SetProperties (string name , string value)
{
-
- switch (name)
- {
+ switch (name) {
case "APP" :
case "APPLICATION NAME" :
parms.ApplicationName = value;
break;
case "ENCRYPT":
if (ConvertToBoolean("encrypt", value))
- {
throw new NotImplementedException("SSL encryption for"
+ " data sent between client and server is not"
+ " implemented.");
- }
break;
case "ENLIST" :
if (!ConvertToBoolean("enlist", value))
- {
throw new NotImplementedException("Disabling the automatic"
+ " enlistment of connections in the thread's current"
+ " transaction context is not implemented.");
- }
break;
case "INITIAL CATALOG" :
case "DATABASE" :
if (tmpMaxPoolSize < 0)
throw new ArgumentException ("Invalid MAX POOL SIZE. Must be a intger >= 0");
else
- maxPoolSize = tmpMaxPoolSize;
+ maxPoolSize = tmpMaxPoolSize;
break;
case "MIN POOL SIZE" :
int tmpMinPoolSize = ConvertToInt32 ("min pool size" , value);
static bool IsValidDatabaseName (string database)
{
- if ( database == null || database.Trim() == String.Empty || database.Length > 128)
+ if ( database == null || database.Trim().Length == 0 || database.Length > 128)
return false ;
if (database[0] == '"' && database[database.Length] == '"')
new object [] {"Databases", 1, 1},
new object [] {"Tables", 4, 3},
new object [] {"Columns", 4, 4},
+ new object [] {"StructuredTypeMembers", 4, 4},
new object [] {"Views", 3, 3},
new object [] {"ViewColumns", 4, 4},
new object [] {"ProcedureParameters", 4, 1},
static public DataTable Instance {
get {
if (instance == null) {
- instance = new DataTable ("GetSchema");
+ instance = new DataTable ("MetaDataCollections");
foreach (ColumnInfo c in columns)
instance.Columns.Add (c.name, c.type);
foreach (object [] row in rows)
}
}
+ static class DataSourceInformation
+ {
+ static readonly ColumnInfo [] columns = {
+ new ColumnInfo ("CompositeIdentifierSeparatorPattern", typeof (string)),
+ new ColumnInfo ("DataSourceProductName", typeof(string)),
+ new ColumnInfo ("DataSourceProductVersion", typeof(string)),
+ new ColumnInfo ("DataSourceProductVersionNormalized", typeof(string)),
+ new ColumnInfo ("GroupByBehavior", typeof(GroupByBehavior)),
+ new ColumnInfo ("IdentifierPattern", typeof(string)),
+ new ColumnInfo ("IdentifierCase", typeof(IdentifierCase)),
+ new ColumnInfo ("OrderByColumnsInSelect", typeof(bool)),
+ new ColumnInfo ("ParameterMarkerFormat", typeof(string)),
+ new ColumnInfo ("ParameterMarkerPattern", typeof(string)),
+ new ColumnInfo ("ParameterNameMaxLength", typeof(int)),
+ new ColumnInfo ("ParameterNamePattern", typeof(string)),
+ new ColumnInfo ("QuotedIdentifierPattern", typeof(string)),
+ new ColumnInfo ("QuotedIdentifierCase", typeof(IdentifierCase)),
+ new ColumnInfo ("StatementSeparatorPattern", typeof(string)),
+ new ColumnInfo ("StringLiteralPattern", typeof(string)),
+ new ColumnInfo ("SupportedJoinOperators", typeof(SupportedJoinOperators))
+ };
+
+ static public DataTable GetInstance (SqlConnection conn)
+ {
+ DataTable table = new DataTable ("DataSourceInformation");
+ foreach (ColumnInfo c in columns)
+ table.Columns.Add (c.name, c.type);
+ DataRow row = table.NewRow ();
+ row [0] = "\\.";
+ row [1] = "Microsoft SQL Server";
+ row [2] = conn.ServerVersion;;
+ row [3] = conn.ServerVersion;;
+ row [4] = GroupByBehavior.Unrelated;
+ row [5] = @"(^\[\p{Lo}\p{Lu}\p{Ll}_@#][\p{Lo}\p{Lu}\p{Ll}\p{Nd}@$#_]*$)|(^\[[^\]\0]|\]\]+\]$)|(^\""[^\""\0]|\""\""+\""$)";
+ row [6] = IdentifierCase.Insensitive; // FIXME: obtain this from SQL Server
+ row [7] = false;
+ row [8] = "{0}";
+ row [9] = @"@[\p{Lo}\p{Lu}\p{Ll}\p{Lm}_@#][\p{Lo}\p{Lu}\p{Ll}\p{Lm}\p{Nd}\uff3f_@#\$]*(?=\s+|$)";
+ row [10] = 128;
+ row [11] = @"^[\p{Lo}\p{Lu}\p{Ll}\p{Lm}_@#][\p{Lo}\p{Lu}\p{Ll}\p{Lm}\p{Nd}\uff3f_@#\$]*(?=\s+|$)";
+ row [12] = @"(([^\[]|\]\])*)";
+ row [13] = IdentifierCase.Insensitive; // FIXME: obtain this from SQL Server
+ row [14] =";";
+ row [15] = "'(([^']|'')*)'";
+ row [16] = (SupportedJoinOperators.FullOuter | SupportedJoinOperators.Inner |
+ SupportedJoinOperators.LeftOuter | SupportedJoinOperators.RightOuter);
+ table.Rows.Add (row);
+ return table;
+ }
+ }
+
static class DataTypes
{
static readonly ColumnInfo [] columns = {
null, "0x", null},
new object [] {"uniqueidentifier", 14, 16, "uniqueidentifier", null,
"System.Guid", false, true, false, true, false, false, true,
- true, false, null, null, null, false, null, "'", "'"}
+ true, false, null, null, null, false, null, "'", "'"},
+ new object [] {"date", 31, 3L, "date", DBNull.Value,
+ "System.DateTime", false, false, false, true, true, false,
+ true, true, true, DBNull.Value, DBNull.Value, DBNull.Value,
+ false, DBNull.Value, "{ts '", "'}"},
+ new object [] {"time", 32, 5L, "time({0})", "scale",
+ "System.TimeSpan", false, false, false, false, false, false,
+ true, true, true, DBNull.Value, (short) 7, (short) 0,
+ false, DBNull.Value, "{ts '", "'}"},
+ new object [] {"datetime2", 33, 8L, "datetime2({0})", "scale",
+ "System.DateTime", false, true, false, false, false, false,
+ true, true, true, DBNull.Value, (short) 7, (short) 0,
+ false, DBNull.Value, "{ts '", "'}"},
+ new object [] {"datetimeoffset", 34, 10L, "datetimeoffset({0})",
+ "scale", "System.DateTimeOffset", false, true, false, false,
+ false, false, true, true, true, DBNull.Value, (short) 7, (short) 0,
+ false, DBNull.Value, "{ts '", "'}"}
};
static DataTable instance;
new object [] {"Columns", "Table", "@Table", "TABLE_NAME", 3},
new object [] {"Columns", "Column", "@Column", "COLUMN_NAME", 4},
+ new object [] {"StructuredTypeMembers", "Catalog", "@Catalog", "TYPE_CATALOG", 1},
+ new object [] {"StructuredTypeMembers", "Owner", "@Owner", "TYPE_SCHEMA", 2},
+ new object [] {"StructuredTypeMembers", "Type", "@Type", "TYPE_NAME", 3},
+ new object [] {"StructuredTypeMembers", "Member", "@Member", "MEMBER_NAME", 4},
+
new object [] {"Views", "Catalog", "@Catalog", "TABLE_CATALOG", 1},
new object [] {"Views", "Owner", "@Owner", "TABLE_SCHEMA", 2},
new object [] {"Views", "Table", "@Table", "TABLE_NAME", 3},
new object [] {"Procedures", "Name", "@Name", "SPECIFIC_NAME", 3},
new object [] {"Procedures", "Type", "@Type", "ROUTINE_TYPE", 4},
- new object [] {"IndexColumns", "Catalog", "@Catalog", "db_name(}", 1},
- new object [] {"IndexColumns", "Owner", "@Owner", "user_name(}", 2},
+ new object [] {"IndexColumns", "Catalog", "@Catalog", "db_name()", 1},
+ new object [] {"IndexColumns", "Owner", "@Owner", "user_name()", 2},
new object [] {"IndexColumns", "Table", "@Table", "o.name", 3},
new object [] {"IndexColumns", "ConstraintName", "@ConstraintName", "x.name", 4},
new object [] {"IndexColumns", "Column", "@Column", "c.name", 5},
- new object [] {"Indexes", "Catalog", "@Catalog", "db_name(}", 1},
- new object [] {"Indexes", "Owner", "@Owner", "user_name(}", 2},
+ new object [] {"Indexes", "Catalog", "@Catalog", "db_name()", 1},
+ new object [] {"Indexes", "Owner", "@Owner", "user_name()", 2},
new object [] {"Indexes", "Table", "@Table", "o.name", 3},
new object [] {"Indexes", "Name", "@Name", "x.name", 4},
public override DataTable GetSchema ()
{
+ if (state == ConnectionState.Closed)
+ throw ExceptionHelper.ConnectionClosed ();
+
return MetaDataCollections.Instance;
}
public override DataTable GetSchema (String collectionName, string [] restrictionValues)
{
- if (collectionName == null)
- //LAMESPEC: In MS.NET, if collectionName is null, it throws ArgumentException.
- throw new ArgumentException ();
+ // LAMESPEC: In MS.NET, if collectionName is null, it throws ArgumentException.
+
+ if (state == ConnectionState.Closed)
+ throw ExceptionHelper.ConnectionClosed ();
- String cName = null;
+ String cName = null;
DataTable schemaTable = MetaDataCollections.Instance;
int length = restrictionValues == null ? 0 : restrictionValues.Length;
cName = row["CollectionName"].ToString();
}
}
+
if (cName == null)
- throw new ArgumentException ("The requested collection ('" + collectionName + "') is not defined.");
+ throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
+ "The requested collection ({0}) is not defined.",
+ collectionName));
SqlCommand command = null;
DataTable dataTable = new DataTable ();
" where (name = @Name or (@Name is null))", this);
command.Parameters.Add ("@Name", SqlDbType.NVarChar, 4000);
break;
+ case "StructuredTypeMembers":
+ // Only available on SQL Server 2008
+ // Running it again SQL 2005 results in the following exception:
+ // Unable to build the 'StructuredTypeMembers' collection because
+ // execution of the SQL query failed. See the inner exception for details.
+ // ---> System.Data.SqlClient.SqlException: Invalid object name 'sys.table_types'.
+ //
+ // I don't have access to SQL Server 2008 right now,
+ // and can't find any online documentation on the 'sys.table_types'
+ // view
+ throw new NotImplementedException ();
case "Views":
command = new SqlCommand ("select TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, CHECK_OPTION, " +
"IS_UPDATABLE from INFORMATION_SCHEMA.VIEWS where (TABLE_CATALOG" +
case "MetaDataCollections":
return MetaDataCollections.Instance;
case "DataSourceInformation":
- throw new NotImplementedException ();
+ return DataSourceInformation.GetInstance (this);
case "DataTypes":
return DataTypes.Instance;
case "ReservedWords":
//
// (C) Ximian, Inc 2002
// Copyright (C) 2002 Tim Coleman
-//
-
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
#region Constructors
- public SqlDataAdapter ()
- : this (new SqlCommand ())
+ public SqlDataAdapter () : this ((SqlCommand) null)
{
}
public SqlDataAdapter (SqlCommand selectCommand)
{
- DeleteCommand = null;
- InsertCommand = null;
SelectCommand = selectCommand;
- UpdateCommand = null;
#if NET_2_0
UpdateBatchSize = 1;
#endif
public SqlDataAdapter (string selectCommandText, SqlConnection selectConnection)
: this (new SqlCommand (selectCommandText, selectConnection))
- {
+ {
}
public SqlDataAdapter (string selectCommandText, string selectConnectionString)
IDbCommand IDbDataAdapter.DeleteCommand {
get { return DeleteCommand; }
- set {
- if (!(value is SqlCommand))
- throw new ArgumentException ();
- DeleteCommand = (SqlCommand)value;
- }
+ set { DeleteCommand = (SqlCommand) value; }
}
IDbCommand IDbDataAdapter.InsertCommand {
get { return InsertCommand; }
- set {
- if (!(value is SqlCommand))
- throw new ArgumentException ();
- InsertCommand = (SqlCommand)value;
- }
+ set { InsertCommand = (SqlCommand) value; }
}
IDbCommand IDbDataAdapter.SelectCommand {
get { return SelectCommand; }
- set {
- if (!(value is SqlCommand))
- throw new ArgumentException ();
- SelectCommand = (SqlCommand)value;
- }
+ set { SelectCommand = (SqlCommand) value; }
}
IDbCommand IDbDataAdapter.UpdateCommand {
get { return UpdateCommand; }
- set {
- if (!(value is SqlCommand))
- throw new ArgumentException ();
- UpdateCommand = (SqlCommand)value;
- }
+ set { UpdateCommand = (SqlCommand) value; }
}
ITableMappingCollection IDataAdapter.TableMappings {
}
#if NET_2_0
- public override int UpdateBatchSize {
+ public override int UpdateBatchSize {
get { return updateBatchSize; }
set {
if (value < 0)
- throw new ArgumentOutOfRangeException ();
+ throw new ArgumentOutOfRangeException ("UpdateBatchSize");
updateBatchSize = value;
}
}
// Release unmanaged resources
disposed = true;
}
+ base.Dispose (disposing);
}
#endif
public event SqlRowUpdatingEventHandler RowUpdating;
#endregion // Events and Delegates
-
}
}
get { return Errors [0].LineNumber; }
}
-#if NET_1_0 || ONLY_1_1
- public
- override
-#else
- new
-#endif
- string Message {
+ public override string Message {
get {
if (Errors.Count == 0)
return base.Message;
case SqlDbType.BigInt :
return Convert.ChangeType (value, typeof (Int64));
case SqlDbType.Binary:
+ case SqlDbType.Image:
case SqlDbType.VarBinary:
if (value is byte[])
return value;
{
#region Fields
- bool disposed = false;
+ bool disposed;
SqlConnection connection;
IsolationLevel isolationLevel;
bool isOpen;
- bool isRolledBack = false;
#endregion
this.connection = connection;
this.isolationLevel = isolevel;
isOpen = true;
- isRolledBack = false;
}
#endregion // Constructors
override
#endif // NET_2_0
IsolationLevel IsolationLevel {
- get { return isolationLevel; }
+ get {
+ if (!isOpen)
+ throw ExceptionHelper.TransactionNotUsable (GetType ());
+ return isolationLevel;
+ }
}
IDbConnection IDbTransaction.Connection {
void Commit ()
{
if (!isOpen)
- throw new InvalidOperationException ("The Transaction was not open.");
+ throw ExceptionHelper.TransactionNotUsable (GetType ());
+
connection.Tds.Execute ("COMMIT TRANSACTION");
connection.Transaction = null;
+ connection = null;
isOpen = false;
}
#endif
void Dispose (bool disposing)
{
- if (!disposed) {
+ if (!disposed) {
if (disposing) {
if (isOpen) // in case it is called in the dispose of the class, then the isOpen is already false
Rollback ();
#if NET_2_0
override
#endif // NET_2_0
- void Rollback ()
+ void Rollback ()
{
Rollback (String.Empty);
}
public void Rollback (string transactionName)
{
- if (!isRolledBack) {
- if (!isOpen)
- throw new InvalidOperationException ("The Transaction was not open.");
- connection.Tds.Execute (String.Format ("ROLLBACK TRANSACTION {0}", transactionName));
- isRolledBack = true;
- isOpen = false;
- connection.Transaction = null;
- connection = null;
- }
+#if NET_2_0
+ if (disposed)
+ return;
+#endif
+
+ if (!isOpen)
+ throw ExceptionHelper.TransactionNotUsable (GetType ());
+
+ connection.Tds.Execute (String.Format ("IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION {0}",
+ transactionName));
+ isOpen = false;
+ connection.Transaction = null;
+ connection = null;
}
public void Save (string savePointName)
{
if (!isOpen)
- throw new InvalidOperationException ("The Transaction was not open.");
+ throw ExceptionHelper.TransactionNotUsable (GetType ());
connection.Tds.Execute (String.Format ("SAVE TRANSACTION {0}", savePointName));
}
+2007-10-21 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * DataColumn.cs: Fixed ParamName of ArgumentNullException. Modified
+ exception message for invalid DateTimeMode value to match MS. Code
+ formatting.
+
+2007-10-19 Nagappan <anagappan@novell.com>
+
+ * DataRelation.cs: Removed bogus TODO.
+
2007-09-27 Nagappan A <anagappan@novell.com>
* DataRelationCollection.cs: Added LAME spec comment as there is no
{\r
ColumnName = (columnName == null ? String.Empty : columnName);\r
\r
- if(dataType == null) {\r
- throw new ArgumentNullException("dataType can't be null.");\r
- }\r
+ if (dataType == null)\r
+ throw new ArgumentNullException("dataType");\r
\r
DataType = dataType;\r
Expression = expr == null ? String.Empty : expr;\r
throw new InvalidOperationException ("The DateTimeMode can be set only on DataColumns of type DateTime.");\r
\r
if (!Enum.IsDefined (typeof (DataSetDateTime), value))\r
- throw new InvalidEnumArgumentException ("The DataSetDateTime enumeration value, " + \r
- (int)value + ", is invalid.");\r
- \r
+ throw new InvalidEnumArgumentException (\r
+ string.Format (CultureInfo.InvariantCulture,\r
+ "The {0} enumeration value, {1}, is invalid",\r
+ typeof (DataSetDateTime).Name, value));\r
+\r
if (_datetimeMode == value)\r
return;\r
if (_table == null || _table.Rows.Count == 0) {\r
_allowDBNull = value;\r
}\r
}\r
- \r
+\r
/// <summary>\r
/// Gets or sets a value indicating whether the column automatically increments the value of the column for new rows added to the table.\r
/// </summary>\r
#endif\r
[DefaultValue (false)]\r
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]\r
- public bool Unique \r
+ public bool Unique \r
{\r
get {\r
return _unique;\r
copy._columnName = _columnName;\r
//Copy.Container\r
copy.DataType = DataType;\r
- copy._defaultValue = _defaultValue; \r
+ copy._defaultValue = _defaultValue;\r
copy._expression = _expression;\r
//Copy.ExtendedProperties\r
copy._maxLength = _maxLength;\r
// Returns true if all the same collumns are in columnSet and compareSet\r
internal static bool AreColumnSetsTheSame(DataColumn[] columnSet, DataColumn[] compareSet)\r
{\r
- if (null == columnSet && null == compareSet) {\r
+ if (null == columnSet && null == compareSet)\r
return true;\r
- }\r
\r
- if (null == columnSet || null == compareSet) {\r
+ if (null == columnSet || null == compareSet)\r
return false;\r
- }\r
\r
- if (columnSet.Length != compareSet.Length) { \r
+ if (columnSet.Length != compareSet.Length)\r
return false;\r
- }\r
\r
foreach (DataColumn col in columnSet) {\r
bool matchFound = false;\r
foreach (DataColumn compare in compareSet) {\r
- if (col == compare) {\r
- matchFound = true; \r
- }\r
+ if (col == compare)\r
+ matchFound = true;\r
}\r
- if (! matchFound) {\r
+ if (!matchFound)\r
return false;\r
- }\r
- } \r
+ }\r
return true;\r
}\r
\r
#if !NET_2_0
[Serializable]
#endif
- [MonoTODO]
[TypeConverterAttribute (typeof (RelationshipConverter))]
public class DataRelation {
private DataSet dataSet;
<HintPath>..\lib\J2SE.Helpers.dll</HintPath>\r
<Private>False</Private>\r
</Reference>\r
- <Reference Include="rt">\r
- <HintPath>..\lib\rt.dll</HintPath>\r
- <Private>False</Private>\r
- </Reference>\r
+ <Reference Include="rt, Version=1.4.2.65535, Culture=neutral, processorArchitecture=MSIL" />\r
<Reference Include="System" />\r
<Reference Include="System.Configuration" />\r
<Reference Include="System.Xml" />\r
-->\r
<ProjectExtensions>\r
<VisualStudio>\r
- <UserProperties REFS-JarPath-system-configuration="..\..\..\..\..\Program Files\Mainsoft\Visual MainWin for J2EE 2\java_refs\framework\System.Configuration.jar" REFS-JarPath-mscorlib="..\..\..\..\..\Program Files\Mainsoft\Visual MainWin for J2EE 2\java_refs\framework\mscorlib.jar" REFS-JarPath-j2se-helpers="..\lib\J2SE.Helpers.jar" REFS-JarPath-rt="..\lib\rt.jar" REFS-JarPath-system-xml="..\..\..\..\..\..\Program Files\Mainsoft\Visual MainWin for J2EE 2\java_refs\framework\System.Xml.jar" REFS-JarPath-system-data="..\..\..\..\..\..\Program Files\Mainsoft\Visual MainWin for J2EE 2\java_refs\framework\System.Data.jar" REFS-JarPath-system="..\..\..\..\..\..\Program Files\Mainsoft\Visual MainWin for J2EE 2\java_refs\framework\System.jar" />\r
+ <UserProperties REFS-RefInfo-rt="repository:jre:sun:1.4.2" REFS-JarPath-system-configuration="..\..\..\..\..\Program Files\Mainsoft\Visual MainWin for J2EE 2\java_refs\framework\System.Configuration.jar" REFS-JarPath-mscorlib="..\..\..\..\..\Program Files\Mainsoft\Visual MainWin for J2EE 2\java_refs\framework\mscorlib.jar" REFS-JarPath-j2se-helpers="..\lib\J2SE.Helpers.jar" REFS-JarPath-rt="..\lib\rt.jar" REFS-JarPath-system-xml="..\..\..\..\..\..\Program Files\Mainsoft\Visual MainWin for J2EE 2\java_refs\framework\System.Xml.jar" REFS-JarPath-system-data="..\..\..\..\..\..\Program Files\Mainsoft\Visual MainWin for J2EE 2\java_refs\framework\System.Data.jar" REFS-JarPath-system="..\..\..\..\..\..\Program Files\Mainsoft\Visual MainWin for J2EE 2\java_refs\framework\System.jar" />\r
</VisualStudio>\r
</ProjectExtensions>\r
<PropertyGroup>\r
<PreBuildEvent>$(ProjectDir)\jay.bat $(ProjectDir)</PreBuildEvent>\r
</PropertyGroup>\r
-</Project>
\ No newline at end of file
+</Project>\r
+++ /dev/null
-<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
- <PropertyGroup>\r
- <JREPath>C:\views\trunk\studio\GH\Redist\j2sdk1.4.full</JREPath>\r
- <VMArguments>\r
- </VMArguments>\r
- </PropertyGroup>\r
-</Project>
\ No newline at end of file
System.Data/VersionNotFoundException.cs
System.Data/XmlDataLoaderTest.cs
System.Data/XmlDataReaderTest.cs
-System.Data.Common/DbProviderFactoriesConfigurationHandlerTest.cs
System.Data.Common/ConnectionStringsSectionTest.cs
+System.Data.Common/DataAdapterTest.cs
System.Data.Common/DataColumnMappingCollectionTest.cs
System.Data.Common/DataTableMappingCollectionTest.cs
System.Data.Common/DBDataPermissionAttributeTest.cs
System.Data.Common/DBDataPermissionTest.cs
System.Data.Common/DbConnectionStringBuilderTest.cs
-System.Data.Common/DataAdapterTest.cs
+System.Data.Common/DbDataAdapterTest.cs
+System.Data.Common/DbProviderFactoriesConfigurationHandlerTest.cs
+System.Data.Common/DbTransactionTest.cs
+System.Data.Odbc/OdbcCommandTest.cs
+System.Data.Odbc/OdbcConnectionTest.cs
+System.Data.Odbc/OdbcDataAdapterTest.cs
+System.Data.Odbc/OdbcParameterCollectionTest.cs
+System.Data.Odbc/OdbcParameterTest.cs
System.Data.Odbc/OdbcPermissionAttributeTest.cs
System.Data.Odbc/OdbcPermissionTest.cs
-System.Data.Odbc/OdbcParameterTest.cs
-System.Data.Odbc/OdbcParameterCollectionTest.cs
+System.Data.OleDb/OleDbCommandTest.cs
+System.Data.OleDb/OleDbConnectionTest.cs
+System.Data.OleDb/OleDbDataAdapterTest.cs
System.Data.OleDb/OleDbParameterCollectionTest.cs
System.Data.OleDb/OleDbPermissionAttributeTest.cs
System.Data.OleDb/OleDbPermissionTest.cs
System.Data.SqlClient/SqlConnectionStringBuilderTest.cs
System.Data.SqlClient/SqlClientPermissionAttributeTest.cs
System.Data.SqlClient/SqlClientPermissionTest.cs
+System.Data.SqlClient/SqlDataAdapterTest.cs
Mono.Data.SqlExpressions/DataColumnExpressionTest.cs
+2007-10-19 Nagappan A <anagappan@novell.com>
+
+ * OdbcDataReaderTest.cs (Bug332404Test): Bug 332404 - ODBC and
+ numeric columns. Thanks to Ernesto Carrea <equistango@gmail.com>
+ for the patch and the test case.
+ Fixed compilation issues in Bug332400Test method.
+
2007-10-12 Nagappan A <anagappan@novell.com>
* OdbcDataReaderTest.cs (Bug332400Test): Bug 332400 - ODBC and
OdbcCmd.CommandText = "Drop table foo";
try {
OdbcCmd.ExecuteNonQuery ();
+#if NET_2_0
+ } catch (Exception e) {
+#else
} catch (OdbcException e) {
+#endif
Assert.Fail ("Exception thrown: " + e.Message);
}
// Create table
ConnectionManager.Singleton.CloseConnection ();
}
}
+
+ [Test]
+ public void Bug332404Test ()
+ {
+ IDbConnection conn = ConnectionManager.Singleton.Connection;
+ try {
+ ConnectionManager.Singleton.OpenConnection ();
+
+ OdbcCommand TempCmd;
+
+ TempCmd = new OdbcCommand ("DROP TABLE IF EXISTS odbc_test");
+ TempCmd.Connection = (OdbcConnection) conn;
+ TempCmd.ExecuteNonQuery ();
+
+ TempCmd = new OdbcCommand ("CREATE TABLE odbc_test (id_test INTEGER NOT NULL, payload DECIMAL (14,4) NOT NULL)");
+ TempCmd.Connection = (OdbcConnection) conn;
+
+ TempCmd.ExecuteNonQuery ();
+
+ TempCmd = new OdbcCommand ("INSERT INTO odbc_test (id_test, payload) VALUES (1, 1.23456789)");
+ TempCmd.Connection = (OdbcConnection) conn;
+ TempCmd.ExecuteNonQuery ();
+
+ OdbcDataAdapter Adaptador = new OdbcDataAdapter ();
+
+ DataSet Lector = new DataSet ();
+
+ Adaptador.SelectCommand = new OdbcCommand ("SELECT * FROM odbc_test WHERE id_test=1", (OdbcConnection) conn);
+ Adaptador.Fill (Lector);
+ Assert.AreEqual (Lector.Tables[0].Rows[0]["payload"], 1.2346);
+ } finally {
+ ConnectionManager.Singleton.CloseConnection ();
+ }
+ }
[Test]
public void Bug332400Test ()
{
IDbConnection conn = ConnectionManager.Singleton.Connection;
try {
ConnectionManager.Singleton.OpenConnection ();
- System.Data.Odbc.OdbcCommand TempCmd;
+ OdbcCommand TempCmd;
- TempCmd = new System.Data.Odbc.OdbcCommand("DROP TABLE IF EXISTS blob_test");
- TempCmd.Connection = conn;
+ TempCmd = new OdbcCommand("DROP TABLE IF EXISTS blob_test");
+ TempCmd.Connection = (OdbcConnection) conn;
TempCmd.ExecuteNonQuery();
- TempCmd = new System.Data.Odbc.OdbcCommand("CREATE TABLE blob_test (id_test INTEGER NOT NULL, payload LONGBLOB NOT NULL)");
- TempCmd.Connection = conn;
+ TempCmd = new OdbcCommand("CREATE TABLE blob_test (id_test INTEGER NOT NULL, payload LONGBLOB NOT NULL)");
+ TempCmd.Connection = (OdbcConnection) conn;
TempCmd.ExecuteNonQuery();
- TempCmd = new System.Data.Odbc.OdbcCommand("INSERT INTO blob_test (id_test, payload) VALUES (1, 'test')");
- TempCmd.Connection = conn;
+ TempCmd = new OdbcCommand("INSERT INTO blob_test (id_test, payload) VALUES (1, 'test')");
+ TempCmd.Connection = (OdbcConnection) conn;
TempCmd.ExecuteNonQuery();
- System.Data.Odbc.OdbcDataAdapter Adaptador = new System.Data.Odbc.OdbcDataAdapter();
- System.Data.DataSet Lector = new System.Data.DataSet();
+ OdbcDataAdapter Adaptador = new OdbcDataAdapter();
+ DataSet Lector = new DataSet();
- Adaptador.SelectCommand = new System.Data.Odbc.OdbcCommand("SELECT * FROM blob_test WHERE id_test=1", conn);
+ Adaptador.SelectCommand = new OdbcCommand("SELECT * FROM blob_test WHERE id_test=1", (OdbcConnection) conn);
Adaptador.Fill(Lector);
} finally {
ConnectionManager.Singleton.CloseConnection ();
}
}
+
#if NET_2_0
[Test]
public void GetDataTypeNameTest ()
+2007-10-19 Nagappan A <anagappan@novell.com>
+
+ * SqlCommandBuilderTest.cs: Fixed compilation warnings.
+
2007-07-31 Nagappan A <anagappan@novell.com>
* SqlConnectionTest.cs (InterfaceTransactionTest): Fixes bug
[Test]
public void GetUpdateDeleteCommandBoolTest_CheckParameters ()
{
- IDbConnection conn = ConnectionManager.Singleton.Connection;
try {
ConnectionManager.Singleton.OpenConnection ();
+ IDbConnection conn = ConnectionManager.Singleton.Connection;
SqlDataAdapter adapter = new SqlDataAdapter ("select id, type_varchar from string_family",
(SqlConnection)conn);
SqlCommandBuilder cb = new SqlCommandBuilder (adapter);
[ExpectedException (typeof (DBConcurrencyException))]
public void GetUpdateCommandDBConcurrencyExceptionTest ()
{
- IDbConnection conn = ConnectionManager.Singleton.Connection;
try {
ConnectionManager.Singleton.OpenConnection ();
+ IDbConnection conn = ConnectionManager.Singleton.Connection;
string selectQuery = "select id, fname from employee where id = 1";
SqlDataAdapter da = new SqlDataAdapter (selectQuery, (SqlConnection) conn);
DataSet ds = new DataSet ();
[ExpectedException (typeof (DBConcurrencyException))]
public void GetDeleteCommandDBConcurrencyExceptionTest ()
{
- IDbConnection conn = ConnectionManager.Singleton.Connection;
try {
ConnectionManager.Singleton.OpenConnection ();
+ IDbConnection conn = ConnectionManager.Singleton.Connection;
string selectQuery = "select id, fname from employee where id = 1";
SqlDataAdapter da = new SqlDataAdapter (selectQuery, (SqlConnection) conn);
DataSet ds = new DataSet ();
[Test]
public void GetDeleteCommandTest ()
{
- IDbConnection conn = ConnectionManager.Singleton.Connection;
try {
ConnectionManager.Singleton.OpenConnection ();
+ IDbConnection conn = ConnectionManager.Singleton.Connection;
string selectQuery = "select id, fname, lname, id+1 as next_id from employee where id = 1";
SqlDataAdapter da = new SqlDataAdapter (selectQuery, (SqlConnection) conn);
DataSet ds = new DataSet ();
[Test]
public void DefaultPropertiesTest ()
{
- SqlCommandBuilder cb = new SqlCommandBuilder ();
-#if NET_1_0
- Assert.AreEqual (ConflictOption.CompareAllSearchableValues, cb.ConflictDetection);
- Assert.AreEqual ("", cb.QuotePrefix, "#5");
- Assert.AreEqual ("", cb.QuoteSuffix, "#6");
-#endif
-#if NET_2_0
- Assert.AreEqual ("[", cb.QuotePrefix, "#5");
- Assert.AreEqual ("]", cb.QuoteSuffix, "#6");
- Assert.AreEqual (".", cb.CatalogSeparator, "#2");
- //Assert.AreEqual ("", cb.DecimalSeparator, "#3");
- Assert.AreEqual (".", cb.SchemaSeparator, "#4");
- Assert.AreEqual (CatalogLocation.Start, cb.CatalogLocation, "#1");
- IDbConnection conn = ConnectionManager.Singleton.Connection;
try {
- conn.Open ();
- cb = new SqlCommandBuilder ();
+ ConnectionManager.Singleton.OpenConnection ();
+ //IDbConnection conn = ConnectionManager.Singleton.Connection;
+ SqlCommandBuilder cb = new SqlCommandBuilder ();
#if NET_2_0
+ Assert.AreEqual ("[", cb.QuotePrefix, "#5");
+ Assert.AreEqual ("]", cb.QuoteSuffix, "#6");
+ Assert.AreEqual (".", cb.CatalogSeparator, "#2");
+ //Assert.AreEqual ("", cb.DecimalSeparator, "#3");
+ Assert.AreEqual (".", cb.SchemaSeparator, "#4");
+ Assert.AreEqual (CatalogLocation.Start, cb.CatalogLocation, "#1");
Assert.AreEqual ("[monotest]", cb.QuoteIdentifier ("monotest"), "#7");
Assert.AreEqual ("\"monotest\"", cb.UnquoteIdentifier ("\"monotest\""), "#8");
+ //Assert.AreEqual (cb.ConflictOption.CompareAllSearchableValues, cb.ConflictDetection);
#else
- Assert.AreEqual ("\"monotest\"", cb.QuoteIdentifier ("monotest"), "#7");
- Assert.AreEqual ("monotest", cb.UnquoteIdentifier ("\"monotest\""), "#8");
+ Assert.AreEqual ("", cb.QuotePrefix, "#5");
+ Assert.AreEqual ("", cb.QuoteSuffix, "#6");
+ //Assert.AreEqual ("\"monotest\"", cb.QuoteIdentifier ("monotest"), "#7");
+ //Assert.AreEqual ("monotest", cb.UnquoteIdentifier ("\"monotest\""), "#8");
#endif
- conn.Close ();
} finally {
ConnectionManager.Singleton.CloseConnection ();
}
// FIXME: test SetAllValues
-#endif // NET_2_0
}
// FIXME: Add tests for examining RowError
[Test]
public void CheckParameters_BuiltCommand ()
{
- using (IDbConnection conn = ConnectionManager.Singleton.Connection) {
+ try {
+ ConnectionManager.Singleton.OpenConnection ();
+ IDbConnection conn = ConnectionManager.Singleton.Connection;
SqlDataAdapter adapter = new SqlDataAdapter ("select id,type_varchar from string_family", (SqlConnection)conn);
SqlCommandBuilder cb = new SqlCommandBuilder(adapter);
DataSet ds = new DataSet ();
Assert.AreEqual (2, cb.GetInsertCommand().Parameters.Count, "#3");
}
+ finally {
+ ConnectionManager.Singleton.CloseConnection ();
+ }
}
}
}
+2007-10-21 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * DBDataPermissionAttributeTest.cs: Improved test for invalid
+ KeyRestrictionBehavior. Fixed line endings.
+
+2007-10-20 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * DbDataAdapterTest.cs: Added test for UpdateBatchSize.
+ * DataAdapterTest.cs: Added tests for AcceptChangesDuringFile,
+ AcceptChangesDuringUpdate, ContinueUpdateOnError, FillLoadOption,
+ MissingMappingAction, MissingSchemaAction and
+ ReturnProviderSpecificTypes.
+
+2007-10-19 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * DbTransactionTest.cs: Enabled test for bug #325397.
+
+2007-10-16 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * DbTransactionTest.cs: Added test for bug #325397.
+
2007-03-03 Gert Driesen <drieseng@users.sourceforge.net>
* DbProviderFactoriesConfigurationHandlerTest.cs: Changed test to also
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
//\r
\r
-using NUnit.Framework;\r
using System;\r
using System.Data;\r
using System.Data.Common;\r
using System.Security;\r
using System.Security.Permissions;\r
\r
-namespace MonoTests.System.Data.Common {\r
-\r
- public class NonAbstractDBDataPermissionAttribute : DBDataPermissionAttribute {\r
+using NUnit.Framework;\r
\r
+namespace MonoTests.System.Data.Common\r
+{\r
+ public class NonAbstractDBDataPermissionAttribute : DBDataPermissionAttribute\r
+ {\r
public NonAbstractDBDataPermissionAttribute (SecurityAction action)\r
: base (action)\r
{\r
}\r
\r
- public override IPermission CreatePermission()
- {
- return null;
- }
+ public override IPermission CreatePermission()\r
+ {\r
+ return null;\r
+ }\r
}\r
\r
[TestFixture]\r
- public class DBDataPermissionAttributeTest {\r
-\r
+ public class DBDataPermissionAttributeTest\r
+ {\r
[Test]\r
public void Default ()\r
{\r
DBDataPermissionAttribute a = new NonAbstractDBDataPermissionAttribute (SecurityAction.Assert);\r
-#if !TARGET_JVM \r
+#if !TARGET_JVM\r
Assert.AreEqual (a.ToString (), a.TypeId.ToString (), "TypeId");\r
#endif \r
Assert.IsFalse (a.Unrestricted, "Unrestricted");\r
[Test]\r
public void Action_Invalid ()\r
{\r
- DBDataPermissionAttribute a = new NonAbstractDBDataPermissionAttribute ((SecurityAction)Int32.MinValue);\r
+ new NonAbstractDBDataPermissionAttribute ((SecurityAction)Int32.MinValue);\r
// no validation in attribute\r
}\r
\r
}\r
\r
[Test]\r
-#if NET_2_0\r
- [ExpectedException (typeof (ArgumentOutOfRangeException))]\r
-#else\r
- [ExpectedException (typeof (ArgumentException))]\r
-#endif\r
public void KeyRestrictionBehavior_Invalid ()\r
{\r
DBDataPermissionAttribute a = new NonAbstractDBDataPermissionAttribute (SecurityAction.Assert);\r
- a.KeyRestrictionBehavior = (KeyRestrictionBehavior)Int32.MinValue;\r
+ try {\r
+ a.KeyRestrictionBehavior = (KeyRestrictionBehavior) 666;\r
+ Assert.Fail ("#1");\r
+#if NET_2_0\r
+ } catch (ArgumentOutOfRangeException ex) {\r
+ // The KeyRestrictionBehavior enumeration value, 666, is invalid\r
+ Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");\r
+ Assert.IsNull (ex.InnerException, "#3");\r
+ Assert.IsNotNull (ex.Message, "#4");\r
+ Assert.IsTrue (ex.Message.IndexOf ("KeyRestrictionBehavior") != -1, "#5");\r
+ Assert.IsTrue (ex.Message.IndexOf ("666") != -1, "#6");\r
+ Assert.IsNotNull (ex.ParamName, "#7");\r
+ Assert.AreEqual ("KeyRestrictionBehavior", ex.ParamName, "#8");\r
+ }\r
+#else\r
+ } catch (ArgumentException ex) {\r
+ // The KeyRestrictionBehavior enumeration value, 666, is invalid\r
+ Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");\r
+ Assert.IsNull (ex.InnerException, "#3");\r
+ Assert.IsNotNull (ex.Message, "#4");\r
+ //Assert.IsTrue (ex.Message.IndexOf ("KeyRestrictionBehavior") != -1, "#5");\r
+ //Assert.IsTrue (ex.Message.IndexOf ("666") != -1, "#6");\r
+ //Assert.IsNull (ex.ParamName, "#7");\r
+ }\r
+#endif\r
}\r
\r
[Test]\r
\r
object [] attrs = t.GetCustomAttributes (typeof (AttributeUsageAttribute), false);\r
Assert.AreEqual (1, attrs.Length, "AttributeUsage");\r
- AttributeUsageAttribute aua = (AttributeUsageAttribute)attrs [0];\r
+ AttributeUsageAttribute aua = (AttributeUsageAttribute) attrs [0];\r
Assert.IsTrue (aua.AllowMultiple, "AllowMultiple");\r
Assert.IsFalse (aua.Inherited, "Inherited");\r
AttributeTargets at = AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method;\r
//
// Author:
// Miguel de Icaza (miguel@novell.com)
+// Gert Driesen (drieseng@users.sourceforge.net)
//
// Copyright (c) 2006 Novell Inc., and the individuals listed
// on the ChangeLog entries.
namespace MonoTests.System.Data.Common
{
+ [TestFixture]
+ public class DataAdapterTest
+ {
+ [Test]
+ public void AcceptChangesDuringFill ()
+ {
+ DataAdapter da = new MyAdapter ();
+ da.AcceptChangesDuringFill = true;
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+ da.AcceptChangesDuringFill = false;
+ Assert.IsFalse (da.AcceptChangesDuringFill, "#2");
+ da.AcceptChangesDuringFill = true;
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#3");
+ }
#if NET_2_0
+ [Test]
+ public void AcceptChangesDuringUpdate ()
+ {
+ DataAdapter da = new MyAdapter ();
+ da.AcceptChangesDuringUpdate = true;
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#1");
+ da.AcceptChangesDuringUpdate = false;
+ Assert.IsFalse (da.AcceptChangesDuringUpdate, "#2");
+ da.AcceptChangesDuringUpdate = true;
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#3");
+ }
+#endif
- class MyAdapter : DataAdapter {
-
- }
+ [Test]
+ public void ContinueUpdateOnError ()
+ {
+ DataAdapter da = new MyAdapter ();
+ da.ContinueUpdateOnError = true;
+ Assert.IsTrue (da.ContinueUpdateOnError, "#1");
+ da.ContinueUpdateOnError = false;
+ Assert.IsFalse (da.ContinueUpdateOnError, "#2");
+ da.ContinueUpdateOnError = true;
+ Assert.IsTrue (da.ContinueUpdateOnError, "#3");
+ }
- [TestFixture]
- public class DataAdapterTest {
-
- [Test] [ExpectedException(typeof (NotSupportedException))]
- public void TestFillDirect ()
+#if NET_2_0
+ [Test]
+ public void Fill_Direct ()
{
- MyAdapter m = new MyAdapter ();
+ DataAdapter da = new MyAdapter ();
DataSet ds = new DataSet ();
-
- m.Fill (ds);
+ try {
+ da.Fill (ds);
+ Assert.Fail ("#1");
+ } catch (NotSupportedException ex) {
+ // Specified method is not supported
+ Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ }
+ }
+
+ [Test]
+ public void FillLoadOption ()
+ {
+ DataAdapter da = new MyAdapter ();
+ da.FillLoadOption = LoadOption.PreserveChanges;
+ Assert.AreEqual (LoadOption.PreserveChanges, da.FillLoadOption, "#1");
+ da.FillLoadOption = LoadOption.OverwriteChanges;
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#2");
+ da.FillLoadOption = LoadOption.Upsert;
+ Assert.AreEqual (LoadOption.Upsert, da.FillLoadOption, "#3");
+ }
+
+ [Test]
+ public void FillLoadOption_Invalid ()
+ {
+ DataAdapter da = new MyAdapter ();
+ try {
+ da.FillLoadOption = (LoadOption) 666;
+ Assert.Fail ("#1");
+ } catch (ArgumentOutOfRangeException ex) {
+ // The LoadOption enumeration value, 666, is invalid
+ Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsTrue (ex.Message.IndexOf ("LoadOption") != -1, "#5");
+ Assert.IsTrue (ex.Message.IndexOf ("666") != -1, "#6");
+ Assert.IsNotNull (ex.ParamName, "#7");
+ Assert.AreEqual ("LoadOption", ex.ParamName, "#8");
+ }
+ }
+#endif
+
+ [Test]
+ public void MissingMappingAction_Valid ()
+ {
+ DataAdapter da = new MyAdapter ();
+ da.MissingMappingAction = MissingMappingAction.Passthrough;
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#1");
+ da.MissingMappingAction = MissingMappingAction.Ignore;
+ Assert.AreEqual (MissingMappingAction.Ignore, da.MissingMappingAction, "#2");
+ da.MissingMappingAction = MissingMappingAction.Error;
+ Assert.AreEqual (MissingMappingAction.Error, da.MissingMappingAction, "#3");
+ }
+
+ [Test]
+ public void MissingMappingAction_Invalid ()
+ {
+ DataAdapter da = new MyAdapter ();
+ try {
+ da.MissingMappingAction = (MissingMappingAction) 666;
+ Assert.Fail ("#1");
+#if NET_2_0
+ } catch (ArgumentOutOfRangeException ex) {
+ // The MissingMappingAction enumeration value, 666, is invalid
+ Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsTrue (ex.Message.IndexOf ("MissingMappingAction") != -1, "#5");
+ Assert.IsTrue (ex.Message.IndexOf ("666") != -1, "#6");
+ Assert.IsNotNull (ex.ParamName, "#7");
+ Assert.AreEqual ("MissingMappingAction", ex.ParamName, "#8");
+ }
+#else
+ } catch (ArgumentException ex) {
+ // The MissingMappingAction enumeration value, 666, is invalid
+ Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsTrue (ex.Message.IndexOf ("MissingMappingAction") != -1, "#5");
+ Assert.IsTrue (ex.Message.IndexOf ("666") != -1, "#6");
+ Assert.IsNull (ex.ParamName, "#7");
+ }
+#endif
}
+
+ [Test]
+ public void MissingSchemaAction_Valid ()
+ {
+ DataAdapter da = new MyAdapter ();
+ da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
+ Assert.AreEqual (MissingSchemaAction.AddWithKey, da.MissingSchemaAction, "#1");
+ da.MissingSchemaAction = MissingSchemaAction.Ignore;
+ Assert.AreEqual (MissingSchemaAction.Ignore, da.MissingSchemaAction, "#2");
+ da.MissingSchemaAction = MissingSchemaAction.Error;
+ Assert.AreEqual (MissingSchemaAction.Error, da.MissingSchemaAction, "#3");
+ }
+
+ [Test]
+ public void MissingSchemaAction_Invalid ()
+ {
+ DataAdapter da = new MyAdapter ();
+ try {
+ da.MissingSchemaAction = (MissingSchemaAction) 666;
+ Assert.Fail ("#1");
+#if NET_2_0
+ } catch (ArgumentOutOfRangeException ex) {
+ // The MissingSchemaAction enumeration value, 666, is invalid
+ Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsTrue (ex.Message.IndexOf ("MissingSchemaAction") != -1, "#5");
+ Assert.IsTrue (ex.Message.IndexOf ("666") != -1, "#6");
+ Assert.IsNotNull (ex.ParamName, "#7");
+ Assert.AreEqual ("MissingSchemaAction", ex.ParamName, "#8");
+ }
+#else
+ } catch (ArgumentException ex) {
+ // The MissingSchemaAction enumeration value, 666, is invalid
+ Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsTrue (ex.Message.IndexOf ("MissingSchemaAction") != -1, "#5");
+ Assert.IsTrue (ex.Message.IndexOf ("666") != -1, "#6");
+ Assert.IsNull (ex.ParamName, "#7");
+ }
+#endif
+ }
+
+#if NET_2_0
+ [Test]
+ public void ReturnProviderSpecificTypes ()
+ {
+ DataAdapter da = new MyAdapter ();
+ da.ReturnProviderSpecificTypes = true;
+ Assert.IsTrue (da.ReturnProviderSpecificTypes, "#1");
+ da.ReturnProviderSpecificTypes = false;
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#2");
+ da.ReturnProviderSpecificTypes = true;
+ Assert.IsTrue (da.ReturnProviderSpecificTypes, "#3");
+ }
+#endif
}
+
+ class MyAdapter : DataAdapter
+ {
+#if ONLY_1_1
+ public override int Fill (DataSet dataSet)
+ {
+ throw new NotImplementedException ();
+ }
+
+ public override DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType)
+ {
+ throw new NotImplementedException ();
+ }
+
+ public override IDataParameter[] GetFillParameters ()
+ {
+ throw new NotImplementedException ();
+ }
+
+ public override int Update (DataSet dataSet)
+ {
+ throw new NotImplementedException ();
+ }
#endif
+ }
}
--- /dev/null
+//
+// DbDataAdapterTest.cs - NUnit Test Cases for testing the DbDataAdapter class
+//
+// Author:
+// Gert Driesen (drieseng@users.sourceforge.net)
+//
+// Copyright (c) 2007 Gert Driesen
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Data;
+using System.Data.Common;
+
+using NUnit.Framework;
+
+namespace MonoTests.System.Data.Common
+{
+ [TestFixture]
+ public class DbDataAdapterTest
+ {
+#if NET_2_0
+ [Test]
+ public void UpdateBatchSize ()
+ {
+ MyAdapter da = new MyAdapter ();
+ try {
+ da.UpdateBatchSize = 0;
+ Assert.Fail ("#A1");
+ } catch (NotSupportedException ex) {
+ // Specified method is not supported
+ Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#A2");
+ Assert.IsNull (ex.InnerException, "#A3");
+ Assert.IsNotNull (ex.Message, "#A4");
+ }
+ Assert.AreEqual (1, da.UpdateBatchSize, "#A5");
+
+ try {
+ da.UpdateBatchSize = int.MaxValue;
+ Assert.Fail ("#B1");
+ } catch (NotSupportedException ex) {
+ // Specified method is not supported
+ Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+ Assert.AreEqual (1, da.UpdateBatchSize, "#B5");
+
+ da.UpdateBatchSize = 1;
+ Assert.AreEqual (1, da.UpdateBatchSize, "#C");
+ }
+
+ [Test]
+ public void UpdateBatchSize_Negative ()
+ {
+ MyAdapter da = new MyAdapter ();
+ try {
+ da.UpdateBatchSize = -1;
+ Assert.Fail ("#1");
+ } catch (NotSupportedException ex) {
+ // Specified method is not supported
+ Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ }
+ }
+#endif
+
+ class MyAdapter : DbDataAdapter
+ {
+#if ONLY_1_1
+ protected override RowUpdatedEventArgs CreateRowUpdatedEvent (DataRow dataRow, IDbCommand command,
+ StatementType statementType,
+ DataTableMapping tableMapping)
+ {
+ throw new NotImplementedException ();
+ }
+
+ protected override RowUpdatingEventArgs CreateRowUpdatingEvent (DataRow dataRow, IDbCommand command,
+ StatementType statementType,
+ DataTableMapping tableMapping)
+ {
+ throw new NotImplementedException ();
+ }
+
+ protected override void OnRowUpdated (RowUpdatedEventArgs value)
+ {
+ throw new NotImplementedException ();
+ }
+
+ protected override void OnRowUpdating (RowUpdatingEventArgs value)
+ {
+ throw new NotImplementedException ();
+ }
+#endif
+ }
+ }
+}
--- /dev/null
+//
+// DbTransactionTest.cs - NUnit Test Cases for testing the DbTransaction class
+//
+// Author:
+// Gert Driesen (drieseng@users.sourceforge.net)
+//
+// Copyright (c) 2007 Gert Driesen
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+#if NET_2_0
+using System;
+using System.Data;
+using System.Data.Common;
+
+using NUnit.Framework;
+
+namespace MonoTests.System.Data.Common
+{
+ [TestFixture]
+ public class DbTransactionTest
+ {
+ [Test] // bug #325397
+ public void DisposeTest ()
+ {
+ MockTransaction trans = new MockTransaction ();
+ trans.Dispose ();
+
+ Assert.IsFalse (trans.IsCommitted, "#1");
+ Assert.IsFalse (trans.IsRolledback, "#2");
+ Assert.IsTrue (trans.IsDisposed, "#3");
+ Assert.IsTrue (trans.Disposing, "#4");
+ }
+
+ class MockTransaction : DbTransaction
+ {
+ protected override DbConnection DbConnection {
+ get { return null; }
+ }
+
+ public override IsolationLevel IsolationLevel {
+ get { return IsolationLevel.RepeatableRead; }
+ }
+
+ public bool IsCommitted {
+ get { return _isCommitted; }
+ }
+
+ public bool IsRolledback {
+ get { return _isRolledback; }
+ }
+
+ public bool IsDisposed {
+ get { return _isDisposed; }
+ }
+
+ public bool Disposing {
+ get { return _disposing; }
+ }
+
+ public override void Commit ()
+ {
+ _isCommitted = true;
+ }
+
+ public override void Rollback ()
+ {
+ _isRolledback = true;
+ }
+
+ protected override void Dispose (bool disposing)
+ {
+ _isDisposed = true;
+ _disposing = disposing;
+ base.Dispose (disposing);
+ }
+
+ private bool _isCommitted;
+ private bool _isRolledback;
+ private bool _isDisposed;
+ private bool _disposing;
+ }
+ }
+}
+#endif
+2007-10-21 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * OdbcDataAdapterTest.cs: Added tests for ctors, DeleteCommand,
+ InsertCommand, SelectCommand, UpdateCommand and Dispose.
+ * OdbcDataReaderTest.cs: fixed line endings.
+ * OdbcCommandTest.cs: Added tests for ctors and CommantText.
+ * OdbcConnectionTest.cs: Removed original test that relied on MySQL.
+ Added ctor tests. Added tests for BeginTransaction, GetSchema and
+ ServerVersion with connection that is closed.
+
2007-06-08 Nagappan A <anagappan@novell.com>
* OdbcParameterTest.cs (OdbcTypeTest): The default data type of
--- /dev/null
+//
+// OdbcCommandTest.cs - NUnit Test Cases for testing
+// System.Data.Odbc.OdbcCommand
+//
+// Author:
+// Gert Driesen (drieseng@users.sourceforge.net)
+//
+// Copyright (c) 2007 Gert Driesen
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Data;
+using System.Data.Odbc;
+
+using NUnit.Framework;
+
+namespace MonoTests.System.Data.Odbc
+{
+ [TestFixture]
+ public class OdbcCommandTest
+ {
+ const string COMMAND_TEXT = "SELECT * FROM Authors";
+
+ [Test] // OdbcCommand ()
+ public void Constructor1 ()
+ {
+ OdbcCommand cmd = new OdbcCommand ();
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#3");
+ Assert.IsNull (cmd.Connection, "#4");
+ Assert.IsNull (cmd.Container, "#5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#6");
+ Assert.IsNotNull (cmd.Parameters, "#7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#8");
+ Assert.IsNull (cmd.Site, "#9");
+ Assert.IsNull (cmd.Transaction, "#10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#11");
+ }
+
+ [Test] // OdbcCommand (string)
+ public void Constructor2 ()
+ {
+ OdbcCommand cmd = new OdbcCommand (COMMAND_TEXT);
+ Assert.AreEqual (COMMAND_TEXT, cmd.CommandText, "#A1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#A2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#A3");
+ Assert.IsNull (cmd.Connection, "#A4");
+ Assert.IsNull (cmd.Container, "#A5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#A6");
+ Assert.IsNotNull (cmd.Parameters, "#A7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#A8");
+ Assert.IsNull (cmd.Site, "#A9");
+ Assert.IsNull (cmd.Transaction, "#A10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#A11");
+
+ cmd = new OdbcCommand ((string) null);
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#B1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#B2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#B3");
+ Assert.IsNull (cmd.Connection, "#B4");
+ Assert.IsNull (cmd.Container, "#B5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#B6");
+ Assert.IsNotNull (cmd.Parameters, "#B7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#B8");
+ Assert.IsNull (cmd.Site, "#B9");
+ Assert.IsNull (cmd.Transaction, "#B10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#B11");
+ }
+
+ [Test] // OdbcCommand (string, OdbcConnection)
+ public void Constructor3 ()
+ {
+ OdbcConnection conn = new OdbcConnection ();
+ OdbcCommand cmd;
+
+ cmd = new OdbcCommand (COMMAND_TEXT, conn);
+ Assert.AreEqual (COMMAND_TEXT, cmd.CommandText, "#A1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#A2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#A3");
+ Assert.AreSame (conn, cmd.Connection, "#A4");
+ Assert.IsNull (cmd.Container, "#A5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#A6");
+ Assert.IsNotNull (cmd.Parameters, "#A7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#A8");
+ Assert.IsNull (cmd.Site, "#A9");
+ Assert.IsNull (cmd.Transaction, "#A10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#A11");
+
+ cmd = new OdbcCommand ((string) null, conn);
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#B1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#B2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#B3");
+ Assert.AreSame (conn, cmd.Connection, "#B4");
+ Assert.IsNull (cmd.Container, "#B5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#B6");
+ Assert.IsNotNull (cmd.Parameters, "#B7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#B8");
+ Assert.IsNull (cmd.Site, "#B9");
+ Assert.IsNull (cmd.Transaction, "#B10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#B11");
+
+ cmd = new OdbcCommand (COMMAND_TEXT, (OdbcConnection) null);
+ Assert.AreEqual (COMMAND_TEXT, cmd.CommandText, "#C1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#C2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#C3");
+ Assert.IsNull (cmd.Connection, "#C4");
+ Assert.IsNull (cmd.Container, "#C5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#C6");
+ Assert.IsNotNull (cmd.Parameters, "#C7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#C8");
+ Assert.IsNull (cmd.Site, "#C9");
+ Assert.IsNull (cmd.Transaction, "#C10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#C11");
+ }
+
+ [Test] // OdbcCommand (string, OdbcConnection, OdbcTransaction)
+ public void Constructor4 ()
+ {
+ OdbcConnection conn = new OdbcConnection ();
+ OdbcCommand cmd;
+
+ cmd = new OdbcCommand (COMMAND_TEXT, conn, (OdbcTransaction) null);
+ Assert.AreEqual (COMMAND_TEXT, cmd.CommandText, "#A1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#A2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#A3");
+ Assert.AreSame (conn, cmd.Connection, "#A4");
+ Assert.IsNull (cmd.Container, "#A5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#A6");
+ Assert.IsNotNull (cmd.Parameters, "#A7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#A8");
+ Assert.IsNull (cmd.Site, "#A9");
+ Assert.IsNull (cmd.Transaction, "#A10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#A11");
+
+ cmd = new OdbcCommand ((string) null, conn, (OdbcTransaction) null);
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#B1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#B2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#B3");
+ Assert.AreSame (conn, cmd.Connection, "#B4");
+ Assert.IsNull (cmd.Container, "#B5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#B6");
+ Assert.IsNotNull (cmd.Parameters, "#B7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#B8");
+ Assert.IsNull (cmd.Site, "#B9");
+ Assert.IsNull (cmd.Transaction, "#B10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#B11");
+
+ cmd = new OdbcCommand (COMMAND_TEXT, (OdbcConnection) null, (OdbcTransaction) null);
+ Assert.AreEqual (COMMAND_TEXT, cmd.CommandText, "#C1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#C2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#C3");
+ Assert.IsNull (cmd.Connection, "#C4");
+ Assert.IsNull (cmd.Container, "#C5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#C6");
+ Assert.IsNotNull (cmd.Parameters, "#C7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#C8");
+ Assert.IsNull (cmd.Site, "#C9");
+ Assert.IsNull (cmd.Transaction, "#C10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#C11");
+ }
+
+ [Test]
+ public void CommandText ()
+ {
+ OdbcCommand cmd = new OdbcCommand ();
+ cmd.CommandText = COMMAND_TEXT;
+ Assert.AreSame (COMMAND_TEXT, cmd.CommandText, "#1");
+ cmd.CommandText = null;
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#2");
+ cmd.CommandText = COMMAND_TEXT;
+ Assert.AreSame (COMMAND_TEXT, cmd.CommandText, "#3");
+ cmd.CommandText = string.Empty;
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#4");
+ }
+ }
+}
-//\r
-// OdbcConnectionTest.cs - NUnit Test Cases for testing the\r
-// OdbcConnectionTest class\r
-// Author:\r
-// Sureshkumar T (TSureshkumar@novell.com)\r
-//\r
-// Copyright (c) 2004 Novell Inc., and the individuals listed\r
-// on the ChangeLog entries.\r
-//\r
-// Permission is hereby granted, free of charge, to any person obtaining\r
-// a copy of this software and associated documentation files (the\r
-// "Software"), to deal in the Software without restriction, including\r
-// without limitation the rights to use, copy, modify, merge, publish,\r
-// distribute, sublicense, and/or sell copies of the Software, and to\r
-// permit persons to whom the Software is furnished to do so, subject to\r
-// the following conditions:\r
-//\r
-// The above copyright notice and this permission notice shall be\r
-// included in all copies or substantial portions of the Software.\r
-//\r
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\r
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\r
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\r
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\r
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-//\r
-\r
-using System;\r
-using System.Data;\r
-using System.Data.Odbc;\r
-\r
-using NUnit.Framework;\r
-\r
-namespace MonoTests.System.Data.Odbc\r
-{\r
-\r
- [TestFixture]\r
- public class OdbcConnectionTest : MySqlOdbcBaseClient \r
- {\r
- [Test]\r
- public void MaximumConnectionsLeakTest () {\r
- OdbcConnection conn = new OdbcConnection (connectionString);\r
- // if your db allows a maximum no. of simultaneous connections\r
- // below 200, this test will work. Otherwise, change this limit\r
- for (int i=0; i < 200; i++) {\r
- conn.Open ();\r
- conn.Close ();\r
- }\r
- }\r
- }\r
-}\r
+//
+// OdbcConnectionTest.cs - NUnit Test Cases for testing the
+// OdbcConnectionTest class
+// Author:
+// Gert Driesen (drieseng@users.sourceforge.net)
+//
+// Copyright (c) 2007 Gert Driesen
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Data;
+using System.Data.Odbc;
+
+using NUnit.Framework;
+
+namespace MonoTests.System.Data.Odbc
+{
+ [TestFixture]
+ public class OdbcConnectionTest
+ {
+ const string CONNECTION_STRING = "Driver={SQL Server};Server=SQLSRV;Database=Mono;";
+
+ [Test] // OdbcConnection ()
+ public void Constructor1 ()
+ {
+ OdbcConnection cn = new OdbcConnection ();
+
+ Assert.AreEqual (string.Empty, cn.ConnectionString, "#1");
+ Assert.AreEqual (15, cn.ConnectionTimeout, "#2");
+ Assert.IsNull (cn.Container, "#3");
+ Assert.AreEqual (string.Empty, cn.Database, "#4");
+ Assert.AreEqual (string.Empty, cn.DataSource, "#5");
+ Assert.AreEqual (string.Empty, cn.Driver, "#6");
+ Assert.IsNull (cn.Site, "#7");
+ Assert.AreEqual (ConnectionState.Closed, cn.State, "#8");
+ }
+
+ [Test] // OdbcConnection (string)
+ public void Constructor2 ()
+ {
+ OdbcConnection cn = new OdbcConnection (CONNECTION_STRING);
+ Assert.AreEqual (CONNECTION_STRING, cn.ConnectionString, "#A1");
+ Assert.AreEqual (15, cn.ConnectionTimeout, "#A2");
+ Assert.IsNull (cn.Container, "#A3");
+ Assert.AreEqual (string.Empty, cn.Database, "#A4");
+ Assert.AreEqual (string.Empty, cn.DataSource, "#A5");
+ Assert.AreEqual (string.Empty, cn.Driver, "#A6");
+ Assert.IsNull (cn.Site, "#A7");
+ Assert.AreEqual (ConnectionState.Closed, cn.State, "#A8");
+
+ cn = new OdbcConnection ((string) null);
+ Assert.AreEqual (string.Empty, cn.ConnectionString, "#B1");
+ Assert.AreEqual (15, cn.ConnectionTimeout, "#B2");
+ Assert.IsNull (cn.Container, "#B3");
+ Assert.AreEqual (string.Empty, cn.Database, "#B4");
+ Assert.AreEqual (string.Empty, cn.DataSource, "#B5");
+ Assert.AreEqual (string.Empty, cn.Driver, "#B6");
+ Assert.IsNull (cn.Site, "#B7");
+ Assert.AreEqual (ConnectionState.Closed, cn.State, "#B8");
+ }
+
+ [Test]
+ public void BeginTransaction_Connection_Closed ()
+ {
+ OdbcConnection cn = new OdbcConnection ();
+
+ try {
+ cn.BeginTransaction ();
+ Assert.Fail ("#A1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2");
+ Assert.IsNull (ex.InnerException, "#A3");
+ Assert.IsNotNull (ex.Message, "#A4");
+ }
+
+ try {
+ cn.BeginTransaction ((IsolationLevel) 666);
+ Assert.Fail ("#B1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+
+ try {
+ cn.BeginTransaction (IsolationLevel.Serializable);
+ Assert.Fail ("#C1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#C2");
+ Assert.IsNull (ex.InnerException, "#C3");
+ Assert.IsNotNull (ex.Message, "#C4");
+ }
+ }
+
+ [Test]
+ public void ConnectionString ()
+ {
+ OdbcConnection cn = new OdbcConnection ();
+ cn.ConnectionString = CONNECTION_STRING;
+ Assert.AreEqual (CONNECTION_STRING, cn.ConnectionString, "#1");
+ cn.ConnectionString = null;
+ Assert.AreEqual (string.Empty, cn.ConnectionString, "#2");
+ cn.ConnectionString = CONNECTION_STRING;
+ Assert.AreEqual (CONNECTION_STRING, cn.ConnectionString, "#3");
+ cn.ConnectionString = string.Empty;
+ Assert.AreEqual (string.Empty, cn.ConnectionString, "#4");
+ }
+
+#if NET_2_0
+ [Test]
+ public void GetSchema_Connection_Closed ()
+ {
+ OdbcConnection cn = new OdbcConnection ();
+
+ try {
+ cn.GetSchema ();
+ Assert.Fail ("#A1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+
+ try {
+ cn.GetSchema ("Tables");
+ Assert.Fail ("#B1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+
+ try {
+ cn.GetSchema ((string) null);
+ Assert.Fail ("#C1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#C2");
+ Assert.IsNull (ex.InnerException, "#C3");
+ Assert.IsNotNull (ex.Message, "#C4");
+ }
+
+ try {
+ cn.GetSchema ("Tables", new string [] { "master" });
+ Assert.Fail ("#D1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#D2");
+ Assert.IsNull (ex.InnerException, "#D3");
+ Assert.IsNotNull (ex.Message, "#D4");
+ }
+
+ try {
+ cn.GetSchema ((string) null, new string [] { "master" });
+ Assert.Fail ("#E1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#E2");
+ Assert.IsNull (ex.InnerException, "#E3");
+ Assert.IsNotNull (ex.Message, "#E4");
+ }
+
+ try {
+ cn.GetSchema ("Tables", (string []) null);
+ Assert.Fail ("#F1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#F2");
+ Assert.IsNull (ex.InnerException, "#F3");
+ Assert.IsNotNull (ex.Message, "#F4");
+ }
+
+ try {
+ cn.GetSchema ((string) null, (string []) null);
+ Assert.Fail ("#G1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#G2");
+ Assert.IsNull (ex.InnerException, "#G3");
+ Assert.IsNotNull (ex.Message, "#G4");
+ }
+ }
+#endif
+
+ [Test]
+ public void ServerVersion_Connection_Closed ()
+ {
+ OdbcConnection cn = new OdbcConnection ();
+ try {
+ Assert.Fail ("#A1:" + cn.ServerVersion);
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2");
+ Assert.IsNull (ex.InnerException, "#A3");
+ Assert.IsNotNull (ex.Message, "#A4");
+ }
+
+ cn = new OdbcConnection (CONNECTION_STRING);
+ try {
+ Assert.Fail ("#B1:" + cn.ServerVersion);
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+ }
+ }
+}
--- /dev/null
+//
+// OdbcDataAdapterTest.cs - NUnit Test Cases for testing the
+// OdbcDataAdapter class
+// Author:
+// Gert Driesen (drieseng@users.sourceforge.net)
+//
+// Copyright (c) 2007 Gert Driesen
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Data;
+using System.Data.Odbc;
+using System.Data.OleDb;
+
+using NUnit.Framework;
+
+namespace MonoTests.System.Data.Odbc
+{
+ [TestFixture]
+ public class OdbcDataAdapterTest
+ {
+ [Test] // OdbcDataAdapter ()
+ public void Constructor1 ()
+ {
+ OdbcDataAdapter da = new OdbcDataAdapter ();
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNull (da.SelectCommand, "#11");
+ Assert.IsNull (da.Site, "#12");
+ Assert.IsNotNull (da.TableMappings, "#13");
+ Assert.AreEqual (0, da.TableMappings.Count, "#14");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#15");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#16");
+ }
+
+ [Test] // OdbcDataAdapter (OdbcCommand)
+ public void Constructor2 ()
+ {
+ OdbcCommand cmd = new OdbcCommand ();
+ OdbcDataAdapter da = new OdbcDataAdapter (cmd);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.AreSame (cmd, da.SelectCommand, "#12");
+ Assert.IsNull (da.Site, "#13");
+ Assert.IsNotNull (da.TableMappings, "#14");
+ Assert.AreEqual (0, da.TableMappings.Count, "#15");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#16");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#17");
+ }
+
+ [Test] // OdbcDataAdapter (OdbcCommand)
+ public void Constructor2_SelectCommand_Null ()
+ {
+ OdbcDataAdapter da = new OdbcDataAdapter ((OdbcCommand) null);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNull (da.SelectCommand, "#11");
+ Assert.IsNull (da.Site, "#12");
+ Assert.IsNotNull (da.TableMappings, "#13");
+ Assert.AreEqual (0, da.TableMappings.Count, "#14");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#15");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#16");
+ }
+
+ [Test] // OdbcDataAdapter (string, OdbcCommand)
+ public void Constructor3 ()
+ {
+ string selectCommandText = "SELECT * FROM Authors";
+ OdbcConnection selectConnection = new OdbcConnection ();
+
+ OdbcDataAdapter da = new OdbcDataAdapter (selectCommandText,
+ selectConnection);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.AreSame (selectCommandText, da.SelectCommand.CommandText, "#12");
+ Assert.AreSame (selectConnection, da.SelectCommand.Connection, "#13");
+ Assert.IsNull (da.Site, "#14");
+ Assert.IsNotNull (da.TableMappings, "#15");
+ Assert.AreEqual (0, da.TableMappings.Count, "#16");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#17");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#18");
+ }
+
+ [Test] // OdbcDataAdapter (string, OdbcConnection)
+ public void Constructor3_SelectCommandText_Null ()
+ {
+ OdbcConnection selectConnection = new OdbcConnection ();
+
+ OdbcDataAdapter da = new OdbcDataAdapter ((string) null,
+ selectConnection);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.IsNotNull (da.SelectCommand.CommandText, "#12");
+ Assert.AreEqual (string.Empty, da.SelectCommand.CommandText, "#13");
+ Assert.AreSame (selectConnection, da.SelectCommand.Connection, "#14");
+ Assert.IsNull (da.Site, "#15");
+ Assert.IsNotNull (da.TableMappings, "#16");
+ Assert.AreEqual (0, da.TableMappings.Count, "#17");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#18");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#19");
+ }
+
+ [Test] // OdbcDataAdapter (string, OdbcConnection)
+ public void Constructor3_SelectConnection_Null ()
+ {
+ string selectCommandText = "SELECT * FROM Authors";
+
+ OdbcDataAdapter da = new OdbcDataAdapter (selectCommandText,
+ (OdbcConnection) null);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.AreSame (selectCommandText, da.SelectCommand.CommandText, "#12");
+ Assert.IsNull (da.SelectCommand.Connection, "#13");
+ Assert.IsNull (da.Site, "#14");
+ Assert.IsNotNull (da.TableMappings, "#15");
+ Assert.AreEqual (0, da.TableMappings.Count, "#16");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#17");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#18");
+ }
+
+ [Test] // OdbcDataAdapter (string, string)]
+ public void Constructor4 ()
+ {
+ string selectCommandText = "SELECT * FROM Authors";
+ string selectConnectionString = "Provider=SQLOLEDB;Data Source=SQLSRV;";
+
+ OdbcDataAdapter da = new OdbcDataAdapter (selectCommandText,
+ selectConnectionString);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.AreSame (selectCommandText, da.SelectCommand.CommandText, "#12");
+ Assert.IsNotNull (da.SelectCommand.Connection, "#13");
+ Assert.AreEqual (selectConnectionString, da.SelectCommand.Connection.ConnectionString, "#14");
+ Assert.IsNull (da.Site, "#15");
+ Assert.IsNotNull (da.TableMappings, "#16");
+ Assert.AreEqual (0, da.TableMappings.Count, "#17");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#18");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#19");
+ }
+
+ [Test] // OdbcDataAdapter (string, string)]
+ public void Constructor4_SelectCommandText_Null ()
+ {
+ string selectConnectionString = "Provider=SQLOLEDB;Data Source=SQLSRV;";
+
+ OdbcDataAdapter da = new OdbcDataAdapter ((string) null,
+ selectConnectionString);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.IsNotNull (da.SelectCommand.CommandText, "#12");
+ Assert.AreEqual (string.Empty, da.SelectCommand.CommandText, "#13");
+ Assert.IsNotNull (da.SelectCommand.Connection, "#14");
+ Assert.AreEqual (selectConnectionString, da.SelectCommand.Connection.ConnectionString, "#15");
+ Assert.IsNull (da.Site, "#16");
+ Assert.IsNotNull (da.TableMappings, "#17");
+ Assert.AreEqual (0, da.TableMappings.Count, "#18");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#19");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#20");
+ }
+
+ [Test] // OdbcDataAdapter (string, string)]
+ public void Constructor4_SelectConnectionString_Null ()
+ {
+ string selectCommandText = "SELECT * FROM Authors";
+
+ OdbcDataAdapter da = new OdbcDataAdapter (selectCommandText,
+ (string) null);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.AreSame (selectCommandText, da.SelectCommand.CommandText, "#12");
+ Assert.IsNotNull (da.SelectCommand.Connection, "#14");
+ Assert.AreEqual (string.Empty, da.SelectCommand.Connection.ConnectionString, "#15");
+ Assert.IsNull (da.Site, "#16");
+ Assert.IsNotNull (da.TableMappings, "#17");
+ Assert.AreEqual (0, da.TableMappings.Count, "#18");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#19");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#20");
+ }
+
+ [Test]
+ public void DeleteCommand ()
+ {
+ OdbcDataAdapter da = new OdbcDataAdapter ();
+ OdbcCommand cmd1 = new OdbcCommand ();
+ OdbcCommand cmd2 = new OdbcCommand ();
+
+ da.DeleteCommand = cmd1;
+ Assert.AreSame (cmd1, da.DeleteCommand, "#1");
+ da.DeleteCommand = cmd2;
+ Assert.AreSame (cmd2, da.DeleteCommand, "#2");
+ da.DeleteCommand = null;
+ Assert.IsNull (da.DeleteCommand, "#3");
+ }
+
+ [Test]
+ public void DeleteCommand_IDbDataAdapter ()
+ {
+ IDbDataAdapter da = new OdbcDataAdapter ();
+ OdbcCommand cmd1 = new OdbcCommand ();
+ OdbcCommand cmd2 = new OdbcCommand ();
+
+ da.DeleteCommand = cmd1;
+ Assert.AreSame (cmd1, da.DeleteCommand, "#A1");
+ da.DeleteCommand = cmd2;
+ Assert.AreSame (cmd2, da.DeleteCommand, "#A2");
+ da.DeleteCommand = null;
+ Assert.IsNull (da.DeleteCommand, "#A3");
+
+ try {
+ da.DeleteCommand = new OleDbCommand ();
+ Assert.Fail ("#B1");
+ } catch (InvalidCastException ex) {
+ Assert.AreEqual (typeof (InvalidCastException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+ }
+
+ [Test]
+ public void Dispose ()
+ {
+ OdbcDataAdapter da = new OdbcDataAdapter ();
+ da.DeleteCommand = new OdbcCommand ();
+ da.InsertCommand = new OdbcCommand ();
+ da.SelectCommand = new OdbcCommand ();
+ da.UpdateCommand = new OdbcCommand ();
+ da.Dispose ();
+
+ Assert.IsNull (da.DeleteCommand, "#1");
+ Assert.IsNull (da.InsertCommand, "#2");
+ Assert.IsNull (da.SelectCommand, "#3");
+ Assert.IsNotNull (da.TableMappings, "#4");
+ Assert.AreEqual (0, da.TableMappings.Count, "#5");
+ Assert.IsNull (da.UpdateCommand, "#6");
+ }
+
+ [Test]
+ public void InsertCommand ()
+ {
+ OdbcDataAdapter da = new OdbcDataAdapter ();
+ OdbcCommand cmd1 = new OdbcCommand ();
+ OdbcCommand cmd2 = new OdbcCommand ();
+
+ da.InsertCommand = cmd1;
+ Assert.AreSame (cmd1, da.InsertCommand, "#1");
+ da.InsertCommand = cmd2;
+ Assert.AreSame (cmd2, da.InsertCommand, "#2");
+ da.InsertCommand = null;
+ Assert.IsNull (da.InsertCommand, "#3");
+ }
+
+ [Test]
+ public void InsertCommand_IDbDataAdapter ()
+ {
+ IDbDataAdapter da = new OdbcDataAdapter ();
+ OdbcCommand cmd1 = new OdbcCommand ();
+ OdbcCommand cmd2 = new OdbcCommand ();
+
+ da.InsertCommand = cmd1;
+ Assert.AreSame (cmd1, da.InsertCommand, "#A1");
+ da.InsertCommand = cmd2;
+ Assert.AreSame (cmd2, da.InsertCommand, "#A2");
+ da.InsertCommand = null;
+ Assert.IsNull (da.InsertCommand, "#A3");
+
+ try {
+ da.InsertCommand = new OleDbCommand ();
+ Assert.Fail ("#B1");
+ } catch (InvalidCastException ex) {
+ Assert.AreEqual (typeof (InvalidCastException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+ }
+
+ [Test]
+ public void SelectCommand ()
+ {
+ OdbcDataAdapter da = new OdbcDataAdapter ();
+ OdbcCommand cmd1 = new OdbcCommand ();
+ OdbcCommand cmd2 = new OdbcCommand ();
+
+ da.SelectCommand = cmd1;
+ Assert.AreSame (cmd1, da.SelectCommand, "#1");
+ da.SelectCommand = cmd2;
+ Assert.AreSame (cmd2, da.SelectCommand, "#2");
+ da.SelectCommand = null;
+ Assert.IsNull (da.SelectCommand, "#3");
+ }
+
+ [Test]
+ public void SelectCommand_IDbDataAdapter ()
+ {
+ IDbDataAdapter da = new OdbcDataAdapter ();
+ OdbcCommand cmd1 = new OdbcCommand ();
+ OdbcCommand cmd2 = new OdbcCommand ();
+
+ da.SelectCommand = cmd1;
+ Assert.AreSame (cmd1, da.SelectCommand, "#A1");
+ da.SelectCommand = cmd2;
+ Assert.AreSame (cmd2, da.SelectCommand, "#A2");
+ da.SelectCommand = null;
+ Assert.IsNull (da.SelectCommand, "#A3");
+
+ try {
+ da.SelectCommand = new OleDbCommand ();
+ Assert.Fail ("#B1");
+ } catch (InvalidCastException ex) {
+ Assert.AreEqual (typeof (InvalidCastException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+ }
+
+ [Test]
+ public void UpdateCommand ()
+ {
+ OdbcDataAdapter da = new OdbcDataAdapter ();
+ OdbcCommand cmd1 = new OdbcCommand ();
+ OdbcCommand cmd2 = new OdbcCommand ();
+
+ da.UpdateCommand = cmd1;
+ Assert.AreSame (cmd1, da.UpdateCommand, "#1");
+ da.UpdateCommand = cmd2;
+ Assert.AreSame (cmd2, da.UpdateCommand, "#2");
+ da.UpdateCommand = null;
+ Assert.IsNull (da.UpdateCommand, "#3");
+ }
+
+ [Test]
+ public void UpdateCommand_IDbDataAdapter ()
+ {
+ IDbDataAdapter da = new OdbcDataAdapter ();
+ OdbcCommand cmd1 = new OdbcCommand ();
+ OdbcCommand cmd2 = new OdbcCommand ();
+
+ da.UpdateCommand = cmd1;
+ Assert.AreSame (cmd1, da.UpdateCommand, "#A1");
+ da.UpdateCommand = cmd2;
+ Assert.AreSame (cmd2, da.UpdateCommand, "#A2");
+ da.UpdateCommand = null;
+ Assert.IsNull (da.UpdateCommand, "#A3");
+
+ try {
+ da.UpdateCommand = new OleDbCommand ();
+ Assert.Fail ("#B1");
+ } catch (InvalidCastException ex) {
+ Assert.AreEqual (typeof (InvalidCastException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+ }
+ }
+}
\r
\r
using System;\r
-using System.Text;
+using System.Text;\r
using System.Data;\r
using System.Data.Odbc;\r
\r
}\r
}\r
\r
-
+\r
\r
[Test]\r
public void NumericTest()\r
dbCommand.ExecuteNonQuery();\r
} \r
}\r
-
+\r
\r
/// <summary>\r
/// This test for the return type & value for GetValue\r
}\r
}\r
\r
-
+\r
}\r
}\r
+2007-10-21 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * OleDbDataAdapterTest.cs: Added tests for ctors, DeleteCommand,
+ InsertCommand, SelectCommand, UpdateCommand and Dispose.
+ * OleDbCommandTest.cs: Added tests for ctors and CommandText.
+ * OleDbConnectionTest.cs: Added tests for ctors and ConnectionString.
+ Added tests for BeginTransaction, GetSchema and ServerVersion with
+ connection that is closed.
+
2007-02-22 Raja R Harinath <rharinath@novell.com>
* OleDbParameterCollectionTest.cs: Fix compile error in 1.1 profile.
--- /dev/null
+//
+// OleDbCommandTest.cs - NUnit Test Cases for testing
+// System.Data.OleDb.OleDbCommand
+//
+// Author:
+// Gert Driesen (drieseng@users.sourceforge.net)
+//
+// Copyright (c) 2007 Gert Driesen
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Data;
+using System.Data.OleDb;
+
+using NUnit.Framework;
+
+namespace MonoTests.System.Data.OleDb
+{
+ [TestFixture]
+ public class OleDbCommandTest
+ {
+ const string COMMAND_TEXT = "SELECT * FROM Authors";
+
+ [Test] // OleDbCommand ()
+ public void Constructor1 ()
+ {
+ OleDbCommand cmd = new OleDbCommand ();
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#3");
+ Assert.IsNull (cmd.Connection, "#4");
+ Assert.IsNull (cmd.Container, "#5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#6");
+ Assert.IsNotNull (cmd.Parameters, "#7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#8");
+ Assert.IsNull (cmd.Site, "#9");
+ Assert.IsNull (cmd.Transaction, "#10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#11");
+ }
+
+ [Test] // OleDbCommand (string)
+ public void Constructor2 ()
+ {
+ OleDbCommand cmd = new OleDbCommand (COMMAND_TEXT);
+ Assert.AreEqual (COMMAND_TEXT, cmd.CommandText, "#A1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#A2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#A3");
+ Assert.IsNull (cmd.Connection, "#A4");
+ Assert.IsNull (cmd.Container, "#A5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#A6");
+ Assert.IsNotNull (cmd.Parameters, "#A7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#A8");
+ Assert.IsNull (cmd.Site, "#A9");
+ Assert.IsNull (cmd.Transaction, "#A10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#A11");
+
+ cmd = new OleDbCommand ((string) null);
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#B1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#B2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#B3");
+ Assert.IsNull (cmd.Connection, "#B4");
+ Assert.IsNull (cmd.Container, "#B5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#B6");
+ Assert.IsNotNull (cmd.Parameters, "#B7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#B8");
+ Assert.IsNull (cmd.Site, "#B9");
+ Assert.IsNull (cmd.Transaction, "#B10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#B11");
+ }
+
+ [Test] // OleDbCommand (string, OleDbConnection)
+ public void Constructor3 ()
+ {
+ OleDbConnection conn = new OleDbConnection ();
+ OleDbCommand cmd;
+
+ cmd = new OleDbCommand (COMMAND_TEXT, conn);
+ Assert.AreEqual (COMMAND_TEXT, cmd.CommandText, "#A1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#A2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#A3");
+ Assert.AreSame (conn, cmd.Connection, "#A4");
+ Assert.IsNull (cmd.Container, "#A5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#A6");
+ Assert.IsNotNull (cmd.Parameters, "#A7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#A8");
+ Assert.IsNull (cmd.Site, "#A9");
+ Assert.IsNull (cmd.Transaction, "#A10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#A11");
+
+ cmd = new OleDbCommand ((string) null, conn);
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#B1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#B2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#B3");
+ Assert.AreSame (conn, cmd.Connection, "#B4");
+ Assert.IsNull (cmd.Container, "#B5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#B6");
+ Assert.IsNotNull (cmd.Parameters, "#B7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#B8");
+ Assert.IsNull (cmd.Site, "#B9");
+ Assert.IsNull (cmd.Transaction, "#B10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#B11");
+
+ cmd = new OleDbCommand (COMMAND_TEXT, (OleDbConnection) null);
+ Assert.AreEqual (COMMAND_TEXT, cmd.CommandText, "#C1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#C2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#C3");
+ Assert.IsNull (cmd.Connection, "#C4");
+ Assert.IsNull (cmd.Container, "#C5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#C6");
+ Assert.IsNotNull (cmd.Parameters, "#C7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#C8");
+ Assert.IsNull (cmd.Site, "#C9");
+ Assert.IsNull (cmd.Transaction, "#C10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#C11");
+ }
+
+ [Test] // OleDbCommand (string, OleDbConnection, OleDbTransaction)
+ public void Constructor4 ()
+ {
+ OleDbConnection conn = new OleDbConnection ();
+ OleDbCommand cmd;
+
+ cmd = new OleDbCommand (COMMAND_TEXT, conn, (OleDbTransaction) null);
+ Assert.AreEqual (COMMAND_TEXT, cmd.CommandText, "#A1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#A2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#A3");
+ Assert.AreSame (conn, cmd.Connection, "#A4");
+ Assert.IsNull (cmd.Container, "#A5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#A6");
+ Assert.IsNotNull (cmd.Parameters, "#A7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#A8");
+ Assert.IsNull (cmd.Site, "#A9");
+ Assert.IsNull (cmd.Transaction, "#A10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#A11");
+
+ cmd = new OleDbCommand ((string) null, conn, (OleDbTransaction) null);
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#B1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#B2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#B3");
+ Assert.AreSame (conn, cmd.Connection, "#B4");
+ Assert.IsNull (cmd.Container, "#B5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#B6");
+ Assert.IsNotNull (cmd.Parameters, "#B7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#B8");
+ Assert.IsNull (cmd.Site, "#B9");
+ Assert.IsNull (cmd.Transaction, "#B10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#B11");
+
+ cmd = new OleDbCommand (COMMAND_TEXT, (OleDbConnection) null, (OleDbTransaction) null);
+ Assert.AreEqual (COMMAND_TEXT, cmd.CommandText, "#C1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#C2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#C3");
+ Assert.IsNull (cmd.Connection, "#C4");
+ Assert.IsNull (cmd.Container, "#C5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#C6");
+ Assert.IsNotNull (cmd.Parameters, "#C7");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#C8");
+ Assert.IsNull (cmd.Site, "#C9");
+ Assert.IsNull (cmd.Transaction, "#C10");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#C11");
+ }
+
+ [Test]
+ public void CommandText ()
+ {
+ OleDbCommand cmd = new OleDbCommand ();
+ cmd.CommandText = COMMAND_TEXT;
+ Assert.AreSame (COMMAND_TEXT, cmd.CommandText, "#1");
+ cmd.CommandText = null;
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#2");
+ cmd.CommandText = COMMAND_TEXT;
+ Assert.AreSame (COMMAND_TEXT, cmd.CommandText, "#3");
+ cmd.CommandText = string.Empty;
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#4");
+ }
+ }
+}
--- /dev/null
+//
+// OleDbConnectionTest.cs - NUnit Test Cases for testing the
+// OleDbConnectionTest class
+// Author:
+// Gert Driesen (drieseng@users.sourceforge.net)
+//
+// Copyright (c) 2007 Gert Driesen
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Data;
+using System.Data.OleDb;
+
+using NUnit.Framework;
+
+namespace MonoTests.System.Data.OleDb
+{
+ [TestFixture]
+ public class OleDbConnectionTest
+ {
+ const string CONNECTION_STRING = "Provider=sqloledb;Data Source=SQLSRV;Initial Catalog=Mono;";
+
+ [Test] // OleDbConnection ()
+ public void Constructor1 ()
+ {
+ OleDbConnection cn = new OleDbConnection ();
+
+ Assert.AreEqual (string.Empty, cn.ConnectionString, "#1");
+ Assert.AreEqual (15, cn.ConnectionTimeout, "#2");
+ Assert.IsNull (cn.Container, "#3");
+ Assert.AreEqual (string.Empty, cn.Database, "#4");
+ Assert.AreEqual (string.Empty, cn.DataSource, "#5");
+ Assert.AreEqual (string.Empty, cn.Provider, "#6");
+ Assert.IsNull (cn.Site, "#7");
+ Assert.AreEqual (ConnectionState.Closed, cn.State, "#8");
+ }
+
+ [Test] // OleDbConnection (string)
+ public void Constructor2 ()
+ {
+ OleDbConnection cn = new OleDbConnection (CONNECTION_STRING);
+ Assert.AreEqual (CONNECTION_STRING, cn.ConnectionString, "#A1");
+ Assert.AreEqual (15, cn.ConnectionTimeout, "#A2");
+ Assert.IsNull (cn.Container, "#A3");
+ //Assert.AreEqual ("Mono", cn.Database, "#A4");
+ //Assert.AreEqual ("SQLSRV", cn.DataSource, "#A5");
+ //Assert.AreEqual ("sqloledb", cn.Provider, "#A6");
+ Assert.IsNull (cn.Site, "#A7");
+ Assert.AreEqual (ConnectionState.Closed, cn.State, "#A8");
+
+ cn = new OleDbConnection ((string) null);
+ Assert.AreEqual (string.Empty, cn.ConnectionString, "#B1");
+ Assert.AreEqual (15, cn.ConnectionTimeout, "#B2");
+ Assert.IsNull (cn.Container, "#B3");
+ Assert.AreEqual (string.Empty, cn.Database, "#B4");
+ Assert.AreEqual (string.Empty, cn.DataSource, "#B5");
+ Assert.AreEqual (string.Empty, cn.Provider, "#B6");
+ Assert.IsNull (cn.Site, "#B7");
+ Assert.AreEqual (ConnectionState.Closed, cn.State, "#B8");
+ }
+
+ [Test]
+ public void BeginTransaction_Connection_Closed ()
+ {
+ OleDbConnection cn = new OleDbConnection ();
+
+ try {
+ cn.BeginTransaction ();
+ Assert.Fail ("#A1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2");
+ Assert.IsNull (ex.InnerException, "#A3");
+ Assert.IsNotNull (ex.Message, "#A4");
+ }
+
+ try {
+ cn.BeginTransaction ((IsolationLevel) 666);
+ Assert.Fail ("#B1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+
+ try {
+ cn.BeginTransaction (IsolationLevel.Serializable);
+ Assert.Fail ("#C1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#C2");
+ Assert.IsNull (ex.InnerException, "#C3");
+ Assert.IsNotNull (ex.Message, "#C4");
+ }
+ }
+
+ [Test]
+ public void ConnectionString ()
+ {
+ OleDbConnection cn = new OleDbConnection ();
+ cn.ConnectionString = CONNECTION_STRING;
+ Assert.AreEqual (CONNECTION_STRING, cn.ConnectionString, "#1");
+ cn.ConnectionString = null;
+ Assert.AreEqual (string.Empty, cn.ConnectionString, "#2");
+ cn.ConnectionString = CONNECTION_STRING;
+ Assert.AreEqual (CONNECTION_STRING, cn.ConnectionString, "#3");
+ cn.ConnectionString = string.Empty;
+ Assert.AreEqual (string.Empty, cn.ConnectionString, "#4");
+ }
+
+#if NET_2_0
+ [Test]
+ public void GetSchema_Connection_Closed ()
+ {
+ OleDbConnection cn = new OleDbConnection ();
+
+ try {
+ cn.GetSchema ();
+ Assert.Fail ("#A1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+
+ try {
+ cn.GetSchema ("Tables");
+ Assert.Fail ("#B1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+
+ try {
+ cn.GetSchema ((string) null);
+ Assert.Fail ("#C1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#C2");
+ Assert.IsNull (ex.InnerException, "#C3");
+ Assert.IsNotNull (ex.Message, "#C4");
+ }
+
+ try {
+ cn.GetSchema ("Tables", new string [] { "master" });
+ Assert.Fail ("#D1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#D2");
+ Assert.IsNull (ex.InnerException, "#D3");
+ Assert.IsNotNull (ex.Message, "#D4");
+ }
+
+ try {
+ cn.GetSchema ((string) null, new string [] { "master" });
+ Assert.Fail ("#E1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#E2");
+ Assert.IsNull (ex.InnerException, "#E3");
+ Assert.IsNotNull (ex.Message, "#E4");
+ }
+
+ try {
+ cn.GetSchema ("Tables", (string []) null);
+ Assert.Fail ("#F1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#F2");
+ Assert.IsNull (ex.InnerException, "#F3");
+ Assert.IsNotNull (ex.Message, "#F4");
+ }
+
+ try {
+ cn.GetSchema ((string) null, (string []) null);
+ Assert.Fail ("#G1");
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#G2");
+ Assert.IsNull (ex.InnerException, "#G3");
+ Assert.IsNotNull (ex.Message, "#G4");
+ }
+ }
+#endif
+
+ [Test]
+ public void ServerVersion_Connection_Closed ()
+ {
+ OleDbConnection cn = new OleDbConnection ();
+ try {
+ Assert.Fail ("#A1:" + cn.ServerVersion);
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2");
+ Assert.IsNull (ex.InnerException, "#A3");
+ Assert.IsNotNull (ex.Message, "#A4");
+ }
+
+ cn = new OleDbConnection (CONNECTION_STRING);
+ try {
+ Assert.Fail ("#B1:" + cn.ServerVersion);
+ } catch (InvalidOperationException ex) {
+ // Invalid operation. The connection is closed
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+ }
+ }
+}
--- /dev/null
+//
+// OleDbDataAdapterTest.cs - NUnit Test Cases for testing the
+// OleDbDataAdapter class
+// Author:
+// Gert Driesen (drieseng@users.sourceforge.net)
+//
+// Copyright (c) 2007 Gert Driesen
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Data;
+using System.Data.Odbc;
+using System.Data.OleDb;
+
+using NUnit.Framework;
+
+namespace MonoTests.System.Data.OleDb
+{
+ [TestFixture]
+ public class OleDbDataAdapterTest
+ {
+ [Test] // OleDbDataAdapter ()
+ public void Constructor1 ()
+ {
+ OleDbDataAdapter da = new OleDbDataAdapter ();
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNull (da.SelectCommand, "#11");
+ Assert.IsNull (da.Site, "#12");
+ Assert.IsNotNull (da.TableMappings, "#13");
+ Assert.AreEqual (0, da.TableMappings.Count, "#14");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#15");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#16");
+ }
+
+ [Test] // OleDbDataAdapter (OleDbCommand)
+ public void Constructor2 ()
+ {
+ OleDbCommand cmd = new OleDbCommand ();
+ OleDbDataAdapter da = new OleDbDataAdapter (cmd);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.AreSame (cmd, da.SelectCommand, "#12");
+ Assert.IsNull (da.Site, "#13");
+ Assert.IsNotNull (da.TableMappings, "#14");
+ Assert.AreEqual (0, da.TableMappings.Count, "#15");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#16");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#17");
+ }
+
+ [Test] // OleDbDataAdapter (OleDbCommand)
+ public void Constructor2_SelectCommand_Null ()
+ {
+ OleDbDataAdapter da = new OleDbDataAdapter ((OleDbCommand) null);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNull (da.SelectCommand, "#11");
+ Assert.IsNull (da.Site, "#12");
+ Assert.IsNotNull (da.TableMappings, "#13");
+ Assert.AreEqual (0, da.TableMappings.Count, "#14");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#15");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#16");
+ }
+
+ [Test] // OleDbDataAdapter (string, OleDbCommand)
+ public void Constructor3 ()
+ {
+ string selectCommandText = "SELECT * FROM Authors";
+ OleDbConnection selectConnection = new OleDbConnection ();
+
+ OleDbDataAdapter da = new OleDbDataAdapter (selectCommandText,
+ selectConnection);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.AreSame (selectCommandText, da.SelectCommand.CommandText, "#12");
+ Assert.AreSame (selectConnection, da.SelectCommand.Connection, "#13");
+ Assert.IsNull (da.Site, "#14");
+ Assert.IsNotNull (da.TableMappings, "#15");
+ Assert.AreEqual (0, da.TableMappings.Count, "#16");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#17");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#18");
+ }
+
+ [Test] // OleDbDataAdapter (string, OleDbConnection)
+ public void Constructor3_SelectCommandText_Null ()
+ {
+ OleDbConnection selectConnection = new OleDbConnection ();
+
+ OleDbDataAdapter da = new OleDbDataAdapter ((string) null,
+ selectConnection);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.IsNotNull (da.SelectCommand.CommandText, "#12");
+ Assert.AreEqual (string.Empty, da.SelectCommand.CommandText, "#13");
+ Assert.AreSame (selectConnection, da.SelectCommand.Connection, "#14");
+ Assert.IsNull (da.Site, "#15");
+ Assert.IsNotNull (da.TableMappings, "#16");
+ Assert.AreEqual (0, da.TableMappings.Count, "#17");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#18");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#19");
+ }
+
+ [Test] // OleDbDataAdapter (string, OleDbConnection)
+ public void Constructor3_SelectConnection_Null ()
+ {
+ string selectCommandText = "SELECT * FROM Authors";
+
+ OleDbDataAdapter da = new OleDbDataAdapter (selectCommandText,
+ (OleDbConnection) null);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.AreSame (selectCommandText, da.SelectCommand.CommandText, "#12");
+ Assert.IsNull (da.SelectCommand.Connection, "#13");
+ Assert.IsNull (da.Site, "#14");
+ Assert.IsNotNull (da.TableMappings, "#15");
+ Assert.AreEqual (0, da.TableMappings.Count, "#16");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#17");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#18");
+ }
+
+ [Test] // OleDbDataAdapter (string, string)]
+ public void Constructor4 ()
+ {
+ string selectCommandText = "SELECT * FROM Authors";
+ string selectConnectionString = "Provider=SQLOLEDB;Data Source=SQLSRV;";
+
+ OleDbDataAdapter da = new OleDbDataAdapter (selectCommandText,
+ selectConnectionString);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.AreSame (selectCommandText, da.SelectCommand.CommandText, "#12");
+ Assert.IsNotNull (da.SelectCommand.Connection, "#13");
+ Assert.AreEqual (selectConnectionString, da.SelectCommand.Connection.ConnectionString, "#14");
+ Assert.IsNull (da.Site, "#15");
+ Assert.IsNotNull (da.TableMappings, "#16");
+ Assert.AreEqual (0, da.TableMappings.Count, "#17");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#18");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#19");
+ }
+
+ [Test] // OleDbDataAdapter (string, string)]
+ public void Constructor4_SelectCommandText_Null ()
+ {
+ string selectConnectionString = "Provider=SQLOLEDB;Data Source=SQLSRV;";
+
+ OleDbDataAdapter da = new OleDbDataAdapter ((string) null,
+ selectConnectionString);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.IsNotNull (da.SelectCommand.CommandText, "#12");
+ Assert.AreEqual (string.Empty, da.SelectCommand.CommandText, "#13");
+ Assert.IsNotNull (da.SelectCommand.Connection, "#14");
+ Assert.AreEqual (selectConnectionString, da.SelectCommand.Connection.ConnectionString, "#15");
+ Assert.IsNull (da.Site, "#16");
+ Assert.IsNotNull (da.TableMappings, "#17");
+ Assert.AreEqual (0, da.TableMappings.Count, "#18");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#19");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#20");
+ }
+
+ [Test] // OleDbDataAdapter (string, string)]
+ public void Constructor4_SelectConnectionString_Null ()
+ {
+ string selectCommandText = "SELECT * FROM Authors";
+
+ OleDbDataAdapter da = new OleDbDataAdapter (selectCommandText,
+ (string) null);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.AreSame (selectCommandText, da.SelectCommand.CommandText, "#12");
+ Assert.IsNotNull (da.SelectCommand.Connection, "#14");
+ Assert.AreEqual (string.Empty, da.SelectCommand.Connection.ConnectionString, "#15");
+ Assert.IsNull (da.Site, "#16");
+ Assert.IsNotNull (da.TableMappings, "#17");
+ Assert.AreEqual (0, da.TableMappings.Count, "#18");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#19");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#20");
+ }
+
+ [Test]
+ public void DeleteCommand ()
+ {
+ OleDbDataAdapter da = new OleDbDataAdapter ();
+ OleDbCommand cmd1 = new OleDbCommand ();
+ OleDbCommand cmd2 = new OleDbCommand ();
+
+ da.DeleteCommand = cmd1;
+ Assert.AreSame (cmd1, da.DeleteCommand, "#1");
+ da.DeleteCommand = cmd2;
+ Assert.AreSame (cmd2, da.DeleteCommand, "#2");
+ da.DeleteCommand = null;
+ Assert.IsNull (da.DeleteCommand, "#3");
+ }
+
+ [Test]
+ public void DeleteCommand_IDbDataAdapter ()
+ {
+ IDbDataAdapter da = new OleDbDataAdapter ();
+ OleDbCommand cmd1 = new OleDbCommand ();
+ OleDbCommand cmd2 = new OleDbCommand ();
+
+ da.DeleteCommand = cmd1;
+ Assert.AreSame (cmd1, da.DeleteCommand, "#A1");
+ da.DeleteCommand = cmd2;
+ Assert.AreSame (cmd2, da.DeleteCommand, "#A2");
+ da.DeleteCommand = null;
+ Assert.IsNull (da.DeleteCommand, "#A3");
+
+ try {
+ da.DeleteCommand = new OdbcCommand ();
+ Assert.Fail ("#B1");
+ } catch (InvalidCastException ex) {
+ Assert.AreEqual (typeof (InvalidCastException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+ }
+
+ [Test]
+ public void Dispose ()
+ {
+ OleDbDataAdapter da = new OleDbDataAdapter ();
+ da.DeleteCommand = new OleDbCommand ();
+ da.InsertCommand = new OleDbCommand ();
+ da.SelectCommand = new OleDbCommand ();
+ da.UpdateCommand = new OleDbCommand ();
+ da.Dispose ();
+
+ Assert.IsNull (da.DeleteCommand, "#1");
+ Assert.IsNull (da.InsertCommand, "#2");
+ Assert.IsNull (da.SelectCommand, "#3");
+ Assert.IsNotNull (da.TableMappings, "#4");
+ Assert.AreEqual (0, da.TableMappings.Count, "#5");
+ Assert.IsNull (da.UpdateCommand, "#6");
+ }
+
+ [Test]
+ public void InsertCommand ()
+ {
+ OleDbDataAdapter da = new OleDbDataAdapter ();
+ OleDbCommand cmd1 = new OleDbCommand ();
+ OleDbCommand cmd2 = new OleDbCommand ();
+
+ da.InsertCommand = cmd1;
+ Assert.AreSame (cmd1, da.InsertCommand, "#1");
+ da.InsertCommand = cmd2;
+ Assert.AreSame (cmd2, da.InsertCommand, "#2");
+ da.InsertCommand = null;
+ Assert.IsNull (da.InsertCommand, "#3");
+ }
+
+ [Test]
+ public void InsertCommand_IDbDataAdapter ()
+ {
+ IDbDataAdapter da = new OleDbDataAdapter ();
+ OleDbCommand cmd1 = new OleDbCommand ();
+ OleDbCommand cmd2 = new OleDbCommand ();
+
+ da.InsertCommand = cmd1;
+ Assert.AreSame (cmd1, da.InsertCommand, "#A1");
+ da.InsertCommand = cmd2;
+ Assert.AreSame (cmd2, da.InsertCommand, "#A2");
+ da.InsertCommand = null;
+ Assert.IsNull (da.InsertCommand, "#A3");
+
+ try {
+ da.InsertCommand = new OdbcCommand ();
+ Assert.Fail ("#B1");
+ } catch (InvalidCastException ex) {
+ Assert.AreEqual (typeof (InvalidCastException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+ }
+
+ [Test]
+ public void SelectCommand ()
+ {
+ OleDbDataAdapter da = new OleDbDataAdapter ();
+ OleDbCommand cmd1 = new OleDbCommand ();
+ OleDbCommand cmd2 = new OleDbCommand ();
+
+ da.SelectCommand = cmd1;
+ Assert.AreSame (cmd1, da.SelectCommand, "#1");
+ da.SelectCommand = cmd2;
+ Assert.AreSame (cmd2, da.SelectCommand, "#2");
+ da.SelectCommand = null;
+ Assert.IsNull (da.SelectCommand, "#3");
+ }
+
+ [Test]
+ public void SelectCommand_IDbDataAdapter ()
+ {
+ IDbDataAdapter da = new OleDbDataAdapter ();
+ OleDbCommand cmd1 = new OleDbCommand ();
+ OleDbCommand cmd2 = new OleDbCommand ();
+
+ da.SelectCommand = cmd1;
+ Assert.AreSame (cmd1, da.SelectCommand, "#A1");
+ da.SelectCommand = cmd2;
+ Assert.AreSame (cmd2, da.SelectCommand, "#A2");
+ da.SelectCommand = null;
+ Assert.IsNull (da.SelectCommand, "#A3");
+
+ try {
+ da.SelectCommand = new OdbcCommand ();
+ Assert.Fail ("#B1");
+ } catch (InvalidCastException ex) {
+ Assert.AreEqual (typeof (InvalidCastException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+ }
+
+ [Test]
+ public void UpdateCommand ()
+ {
+ OleDbDataAdapter da = new OleDbDataAdapter ();
+ OleDbCommand cmd1 = new OleDbCommand ();
+ OleDbCommand cmd2 = new OleDbCommand ();
+
+ da.UpdateCommand = cmd1;
+ Assert.AreSame (cmd1, da.UpdateCommand, "#1");
+ da.UpdateCommand = cmd2;
+ Assert.AreSame (cmd2, da.UpdateCommand, "#2");
+ da.UpdateCommand = null;
+ Assert.IsNull (da.UpdateCommand, "#3");
+ }
+
+ [Test]
+ public void UpdateCommand_IDbDataAdapter ()
+ {
+ IDbDataAdapter da = new OleDbDataAdapter ();
+ OleDbCommand cmd1 = new OleDbCommand ();
+ OleDbCommand cmd2 = new OleDbCommand ();
+
+ da.UpdateCommand = cmd1;
+ Assert.AreSame (cmd1, da.UpdateCommand, "#A1");
+ da.UpdateCommand = cmd2;
+ Assert.AreSame (cmd2, da.UpdateCommand, "#A2");
+ da.UpdateCommand = null;
+ Assert.IsNull (da.UpdateCommand, "#A3");
+
+ try {
+ da.UpdateCommand = new OdbcCommand ();
+ Assert.Fail ("#B1");
+ } catch (InvalidCastException ex) {
+ Assert.AreEqual (typeof (InvalidCastException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+ }
+ }
+}
+2007-10-21 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * SqlCommandTest.cs: Added tests for ctors and CommantText.
+ * SqlConnectionTest.cs: Added tests for ctors, ConnectionString and
+ ServerVersion.
+ * SqlDataAdapterTest.cs: Added tests for ctors, DeleteCommand,
+ InsertCommand, SelectCommand, UpdateCommand, UpdateBatchSize and
+ Dispose.
+
+2007-10-18 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * SqlConnectionTest.cs: Added tests for BeginTransaction and GetSchema
+ when connection is closed.
+
2007-05-29 Gert Driesen <drieseng@users.sourceforge.net>
* SqlCommandTest.cs: Added test for bug #81710.
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
+using System.Data;
using System.Data.SqlClient;
using NUnit.Framework;
[TestFixture]
public class SqlCommandTest
{
+ const string COMMAND_TEXT = "SELECT * FROM Authors";
+
+ [Test] // SqlCommand ()
+ public void Constructor1 ()
+ {
+ SqlCommand cmd = new SqlCommand ();
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#3");
+ Assert.IsNull (cmd.Connection, "#4");
+ Assert.IsNull (cmd.Container, "#5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#6");
+#if NET_2_0
+ Assert.IsNull (cmd.Notification, "#7");
+ Assert.IsTrue (cmd.NotificationAutoEnlist, "#8");
+#endif
+ Assert.IsNotNull (cmd.Parameters, "#9");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#10");
+ Assert.IsNull (cmd.Site, "#11");
+ Assert.IsNull (cmd.Transaction, "#11");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#12");
+ }
+
+ [Test] // SqlCommand (string)
+ public void Constructor2 ()
+ {
+ SqlCommand cmd = new SqlCommand (COMMAND_TEXT);
+ Assert.AreEqual (COMMAND_TEXT, cmd.CommandText, "#A1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#A2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#A3");
+ Assert.IsNull (cmd.Connection, "#A4");
+ Assert.IsNull (cmd.Container, "#A5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#A6");
+#if NET_2_0
+ Assert.IsNull (cmd.Notification, "#A7");
+ Assert.IsTrue (cmd.NotificationAutoEnlist, "#A8");
+#endif
+ Assert.IsNotNull (cmd.Parameters, "#A9");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#A10");
+ Assert.IsNull (cmd.Site, "#A11");
+ Assert.IsNull (cmd.Transaction, "#A12");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#A13");
+
+ cmd = new SqlCommand ((string) null);
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#B1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#B2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#B3");
+ Assert.IsNull (cmd.Connection, "#B4");
+ Assert.IsNull (cmd.Container, "#B5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#B6");
+#if NET_2_0
+ Assert.IsNull (cmd.Notification, "#B7");
+ Assert.IsTrue (cmd.NotificationAutoEnlist, "#B8");
+#endif
+ Assert.IsNotNull (cmd.Parameters, "#B9");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#B10");
+ Assert.IsNull (cmd.Site, "#B11");
+ Assert.IsNull (cmd.Transaction, "#B12");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#B13");
+ }
+
+ [Test] // SqlCommand (string, SqlConnection)
+ public void Constructor3 ()
+ {
+ SqlConnection conn = new SqlConnection ();
+ SqlCommand cmd;
+
+ cmd = new SqlCommand (COMMAND_TEXT, conn);
+ Assert.AreEqual (COMMAND_TEXT, cmd.CommandText, "#A1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#A2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#A3");
+ Assert.AreSame (conn, cmd.Connection, "#A4");
+ Assert.IsNull (cmd.Container, "#A5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#A6");
+#if NET_2_0
+ Assert.IsNull (cmd.Notification, "#A7");
+ Assert.IsTrue (cmd.NotificationAutoEnlist, "#A8");
+#endif
+ Assert.IsNotNull (cmd.Parameters, "#A9");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#A10");
+ Assert.IsNull (cmd.Site, "#A11");
+ Assert.IsNull (cmd.Transaction, "#A12");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#A13");
+
+ cmd = new SqlCommand ((string) null, conn);
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#B1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#B2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#B3");
+ Assert.AreSame (conn, cmd.Connection, "#B4");
+ Assert.IsNull (cmd.Container, "#B5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#B6");
+#if NET_2_0
+ Assert.IsNull (cmd.Notification, "#B7");
+ Assert.IsTrue (cmd.NotificationAutoEnlist, "#B8");
+#endif
+ Assert.IsNotNull (cmd.Parameters, "#B9");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#B10");
+ Assert.IsNull (cmd.Site, "#B11");
+ Assert.IsNull (cmd.Transaction, "#B12");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#B13");
+
+ cmd = new SqlCommand (COMMAND_TEXT, (SqlConnection) null);
+ Assert.AreEqual (COMMAND_TEXT, cmd.CommandText, "#C1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#C2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#C3");
+ Assert.IsNull (cmd.Connection, "#C4");
+ Assert.IsNull (cmd.Container, "#C5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#C6");
+#if NET_2_0
+ Assert.IsNull (cmd.Notification, "#C7");
+ Assert.IsTrue (cmd.NotificationAutoEnlist, "#C8");
+#endif
+ Assert.IsNotNull (cmd.Parameters, "#C9");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#C10");
+ Assert.IsNull (cmd.Site, "#C11");
+ Assert.IsNull (cmd.Transaction, "#C12");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#C13");
+ }
+
+ [Test] // SqlCommand (string, SqlConnection, SqlTransaction)
+ public void Constructor4 ()
+ {
+ SqlConnection conn = new SqlConnection ();
+ SqlCommand cmd;
+
+ cmd = new SqlCommand (COMMAND_TEXT, conn, (SqlTransaction) null);
+ Assert.AreEqual (COMMAND_TEXT, cmd.CommandText, "#A1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#A2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#A3");
+ Assert.AreSame (conn, cmd.Connection, "#A4");
+ Assert.IsNull (cmd.Container, "#A5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#A6");
+#if NET_2_0
+ Assert.IsNull (cmd.Notification, "#A7");
+ Assert.IsTrue (cmd.NotificationAutoEnlist, "#A8");
+#endif
+ Assert.IsNotNull (cmd.Parameters, "#A9");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#A10");
+ Assert.IsNull (cmd.Site, "#A11");
+ Assert.IsNull (cmd.Transaction, "#A12");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#A13");
+
+ cmd = new SqlCommand ((string) null, conn, (SqlTransaction) null);
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#B1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#B2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#B3");
+ Assert.AreSame (conn, cmd.Connection, "#B4");
+ Assert.IsNull (cmd.Container, "#B5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#B6");
+#if NET_2_0
+ Assert.IsNull (cmd.Notification, "#B7");
+ Assert.IsTrue (cmd.NotificationAutoEnlist, "#B8");
+#endif
+ Assert.IsNotNull (cmd.Parameters, "#B9");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#B10");
+ Assert.IsNull (cmd.Site, "#B11");
+ Assert.IsNull (cmd.Transaction, "#B12");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#B13");
+
+ cmd = new SqlCommand (COMMAND_TEXT, (SqlConnection) null, (SqlTransaction) null);
+ Assert.AreEqual (COMMAND_TEXT, cmd.CommandText, "#C1");
+ Assert.AreEqual (30, cmd.CommandTimeout, "#C2");
+ Assert.AreEqual (CommandType.Text, cmd.CommandType, "#C3");
+ Assert.IsNull (cmd.Connection, "#C4");
+ Assert.IsNull (cmd.Container, "#C5");
+ Assert.IsTrue (cmd.DesignTimeVisible, "#C6");
+#if NET_2_0
+ Assert.IsNull (cmd.Notification, "#C7");
+ Assert.IsTrue (cmd.NotificationAutoEnlist, "#C8");
+#endif
+ Assert.IsNotNull (cmd.Parameters, "#C9");
+ Assert.AreEqual (0, cmd.Parameters.Count, "#C10");
+ Assert.IsNull (cmd.Site, "#C11");
+ Assert.IsNull (cmd.Transaction, "#C12");
+ Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource, "#C13");
+ }
+
[Test] // bug #81710
public void Dispose ()
{
command.Dispose ();
Assert.AreEqual (connectionString, connection.ConnectionString);
}
+
+ [Test]
+ public void CommandText ()
+ {
+ SqlCommand cmd = new SqlCommand ();
+ cmd.CommandText = COMMAND_TEXT;
+ Assert.AreSame (COMMAND_TEXT, cmd.CommandText, "#1");
+ cmd.CommandText = null;
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#2");
+ cmd.CommandText = COMMAND_TEXT;
+ Assert.AreSame (COMMAND_TEXT, cmd.CommandText, "#3");
+ cmd.CommandText = string.Empty;
+ Assert.AreEqual (string.Empty, cmd.CommandText, "#4");
+ }
}
}
[TestFixture]\r
public class SqlConnectionTest\r
{\r
+ [Test] // SqlConnection ()\r
+ public void Constructor1 ()\r
+ {\r
+ SqlConnection cn = new SqlConnection ();\r
+\r
+ Assert.AreEqual (string.Empty, cn.ConnectionString, "#1");\r
+ Assert.AreEqual (15, cn.ConnectionTimeout, "#2");\r
+ Assert.IsNull (cn.Container, "#3");\r
+ Assert.AreEqual (string.Empty, cn.Database, "#4");\r
+ Assert.AreEqual (string.Empty, cn.DataSource, "#5");\r
+#if NET_2_0\r
+ Assert.IsFalse (cn.FireInfoMessageEventOnUserErrors, "#6");\r
+ Assert.AreEqual (8000, cn.PacketSize, "#7");\r
+#else\r
+ Assert.AreEqual (8192, cn.PacketSize, "#7");\r
+#endif\r
+ Assert.IsNull (cn.Site, "#8");\r
+ Assert.AreEqual (ConnectionState.Closed, cn.State, "#9");\r
+#if NET_2_0\r
+ Assert.IsFalse (cn.StatisticsEnabled, "#10");\r
+#endif\r
+ Assert.AreEqual (Environment.MachineName, cn.WorkstationId, "#11");\r
+ }\r
+\r
+ [Test] // SqlConnection (string)\r
+ public void Constructor2 ()\r
+ {\r
+ string connectionString = "server=SQLSRV; database=Mono;";\r
+\r
+ SqlConnection cn = new SqlConnection (connectionString);\r
+ Assert.AreEqual (connectionString, cn.ConnectionString, "#A1");\r
+ Assert.AreEqual (15, cn.ConnectionTimeout, "#A2");\r
+ Assert.IsNull (cn.Container, "#A3");\r
+ Assert.AreEqual ("Mono", cn.Database, "#A4");\r
+ Assert.AreEqual ("SQLSRV", cn.DataSource, "#A5");\r
+#if NET_2_0\r
+ Assert.IsFalse (cn.FireInfoMessageEventOnUserErrors, "#A6");\r
+ Assert.AreEqual (8000, cn.PacketSize, "#A7");\r
+#else\r
+ Assert.AreEqual (8192, cn.PacketSize, "#A7");\r
+#endif\r
+ Assert.IsNull (cn.Site, "#A8");\r
+ Assert.AreEqual (ConnectionState.Closed, cn.State, "#A9");\r
+#if NET_2_0\r
+ Assert.IsFalse (cn.StatisticsEnabled, "#A10");\r
+#endif\r
+ Assert.AreEqual (Environment.MachineName, cn.WorkstationId, "#A11");\r
+\r
+ cn = new SqlConnection ((string) null);\r
+ Assert.AreEqual (string.Empty, cn.ConnectionString, "#B1");\r
+ Assert.AreEqual (15, cn.ConnectionTimeout, "#B2");\r
+ Assert.IsNull (cn.Container, "#B3");\r
+ Assert.AreEqual (string.Empty, cn.Database, "#B4");\r
+ Assert.AreEqual (string.Empty, cn.DataSource, "#B5");\r
+#if NET_2_0\r
+ Assert.IsFalse (cn.FireInfoMessageEventOnUserErrors, "#B6");\r
+ Assert.AreEqual (8000, cn.PacketSize, "#B7");\r
+#else\r
+ Assert.AreEqual (8192, cn.PacketSize, "#B7");\r
+#endif\r
+ Assert.IsNull (cn.Site, "#B8");\r
+ Assert.AreEqual (ConnectionState.Closed, cn.State, "#B9");\r
+#if NET_2_0\r
+ Assert.IsFalse (cn.StatisticsEnabled, "#B10");\r
+#endif\r
+ Assert.AreEqual (Environment.MachineName, cn.WorkstationId, "#B11");\r
+ }\r
+\r
[Test]\r
- public void DefaultConnectionValues()\r
+ public void BeginTransaction_Connection_Closed ()\r
{\r
SqlConnection cn = new SqlConnection ();\r
\r
- Assert.AreEqual (15, cn.ConnectionTimeout, \r
- "Default connection timeout should be 15 seconds");\r
- Assert.AreEqual ("", cn.Database, \r
- "Default database name should be empty string");\r
- Assert.AreEqual ("", cn.DataSource,\r
- "Default data source should be empty string");\r
- Assert.AreEqual (8192, cn.PacketSize,\r
- "Default packet size should be 8192 bytes");\r
- Assert.AreEqual (ConnectionState.Closed, cn.State,\r
- "Default connection state should be closed");\r
+ try {\r
+ cn.BeginTransaction ();\r
+ Assert.Fail ("#A1");\r
+ } catch (InvalidOperationException ex) {\r
+ // Invalid operation. The connection is closed\r
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2");\r
+ Assert.IsNull (ex.InnerException, "#A3");\r
+ Assert.IsNotNull (ex.Message, "#A4");\r
+ }\r
+\r
+ try {\r
+ cn.BeginTransaction ((IsolationLevel) 666);\r
+ Assert.Fail ("#B1");\r
+ } catch (InvalidOperationException ex) {\r
+ // Invalid operation. The connection is closed\r
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");\r
+ Assert.IsNull (ex.InnerException, "#B3");\r
+ Assert.IsNotNull (ex.Message, "#B4");\r
+ }\r
+\r
+ try {\r
+ cn.BeginTransaction (IsolationLevel.Serializable);\r
+ Assert.Fail ("#C1");\r
+ } catch (InvalidOperationException ex) {\r
+ // Invalid operation. The connection is closed\r
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#C2");\r
+ Assert.IsNull (ex.InnerException, "#C3");\r
+ Assert.IsNotNull (ex.Message, "#C4");\r
+ }\r
+\r
+ try {\r
+ cn.BeginTransaction ("trans");\r
+ Assert.Fail ("#D1");\r
+ } catch (InvalidOperationException ex) {\r
+ // Invalid operation. The connection is closed\r
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#D2");\r
+ Assert.IsNull (ex.InnerException, "#D3");\r
+ Assert.IsNotNull (ex.Message, "#D4");\r
+ }\r
+\r
+ try {\r
+ cn.BeginTransaction ((IsolationLevel) 666, "trans");\r
+ Assert.Fail ("#E1");\r
+ } catch (InvalidOperationException ex) {\r
+ // Invalid operation. The connection is closed\r
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#E2");\r
+ Assert.IsNull (ex.InnerException, "#E3");\r
+ Assert.IsNotNull (ex.Message, "#E4");\r
+ }\r
+\r
+ try {\r
+ cn.BeginTransaction (IsolationLevel.Serializable, "trans");\r
+ Assert.Fail ("#F1");\r
+ } catch (InvalidOperationException ex) {\r
+ // Invalid operation. The connection is closed\r
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#F2");\r
+ Assert.IsNull (ex.InnerException, "#F3");\r
+ Assert.IsNotNull (ex.Message, "#F4");\r
+ }\r
+ }\r
+\r
+ [Test]\r
+ public void ConnectionString ()\r
+ {\r
+ SqlConnection cn = new SqlConnection ();\r
+ cn.ConnectionString = "server=SQLSRV";\r
+ Assert.AreEqual ("server=SQLSRV", cn.ConnectionString, "#1");\r
+ cn.ConnectionString = null;\r
+ Assert.AreEqual (string.Empty, cn.ConnectionString, "#2");\r
+ cn.ConnectionString = "server=SQLSRV";\r
+ Assert.AreEqual ("server=SQLSRV", cn.ConnectionString, "#3");\r
+ cn.ConnectionString = string.Empty;\r
+ Assert.AreEqual (string.Empty, cn.ConnectionString, "#4");\r
}\r
\r
[Test]\r
Assert.AreEqual (25, cn.ConnectionTimeout);\r
}\r
\r
+#if NET_2_0\r
+ [Test]\r
+ public void GetSchema_Connection_Closed ()\r
+ {\r
+ SqlConnection cn = new SqlConnection ();\r
+\r
+ try {\r
+ cn.GetSchema ();\r
+ Assert.Fail ("#A1");\r
+ } catch (InvalidOperationException ex) {\r
+ // Invalid operation. The connection is closed\r
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2");\r
+ Assert.IsNull (ex.InnerException, "#B3");\r
+ Assert.IsNotNull (ex.Message, "#B4");\r
+ }\r
+\r
+ try {\r
+ cn.GetSchema ("Tables");\r
+ Assert.Fail ("#B1");\r
+ } catch (InvalidOperationException ex) {\r
+ // Invalid operation. The connection is closed\r
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");\r
+ Assert.IsNull (ex.InnerException, "#B3");\r
+ Assert.IsNotNull (ex.Message, "#B4");\r
+ }\r
+\r
+ try {\r
+ cn.GetSchema ((string) null);\r
+ Assert.Fail ("#C1");\r
+ } catch (InvalidOperationException ex) {\r
+ // Invalid operation. The connection is closed\r
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#C2");\r
+ Assert.IsNull (ex.InnerException, "#C3");\r
+ Assert.IsNotNull (ex.Message, "#C4");\r
+ }\r
+\r
+ try {\r
+ cn.GetSchema ("Tables", new string [] { "master" });\r
+ Assert.Fail ("#D1");\r
+ } catch (InvalidOperationException ex) {\r
+ // Invalid operation. The connection is closed\r
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#D2");\r
+ Assert.IsNull (ex.InnerException, "#D3");\r
+ Assert.IsNotNull (ex.Message, "#D4");\r
+ }\r
+\r
+ try {\r
+ cn.GetSchema ((string) null, new string [] { "master" });\r
+ Assert.Fail ("#E1");\r
+ } catch (InvalidOperationException ex) {\r
+ // Invalid operation. The connection is closed\r
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#E2");\r
+ Assert.IsNull (ex.InnerException, "#E3");\r
+ Assert.IsNotNull (ex.Message, "#E4");\r
+ }\r
+\r
+ try {\r
+ cn.GetSchema ("Tables", (string []) null);\r
+ Assert.Fail ("#F1");\r
+ } catch (InvalidOperationException ex) {\r
+ // Invalid operation. The connection is closed\r
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#F2");\r
+ Assert.IsNull (ex.InnerException, "#F3");\r
+ Assert.IsNotNull (ex.Message, "#F4");\r
+ }\r
+\r
+ try {\r
+ cn.GetSchema ((string) null, (string []) null);\r
+ Assert.Fail ("#G1");\r
+ } catch (InvalidOperationException ex) {\r
+ // Invalid operation. The connection is closed\r
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#G2");\r
+ Assert.IsNull (ex.InnerException, "#G3");\r
+ Assert.IsNotNull (ex.Message, "#G4");\r
+ }\r
+ }\r
+#endif\r
+\r
[Test]\r
public void NetworkLibrarySynonyms()\r
{\r
cn.ConnectionString = "initial file name=dunno";\r
*/\r
}\r
+\r
+ [Test]\r
+ public void ServerVersion_Connection_Closed ()\r
+ {\r
+ SqlConnection cn = new SqlConnection ();\r
+ try {\r
+ Assert.Fail ("#A1:" + cn.ServerVersion);\r
+ } catch (InvalidOperationException ex) {\r
+ // Invalid operation. The connection is closed\r
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2");\r
+ Assert.IsNull (ex.InnerException, "#A3");\r
+ Assert.IsNotNull (ex.Message, "#A4");\r
+ }\r
+\r
+ cn = new SqlConnection ("server=SQLSRV; database=Mono;");\r
+ try {\r
+ Assert.Fail ("#B1:" + cn.ServerVersion);\r
+ } catch (InvalidOperationException ex) {\r
+ // Invalid operation. The connection is closed\r
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");\r
+ Assert.IsNull (ex.InnerException, "#B3");\r
+ Assert.IsNotNull (ex.Message, "#B4");\r
+ }\r
+ }\r
}\r
}\r
--- /dev/null
+//
+// SqlDataAdapterTest.cs - NUnit Test Cases for testing the
+// SqlDataAdapter class
+// Author:
+// Gert Driesen (drieseng@users.sourceforge.net)
+//
+// Copyright (c) 2007 Gert Driesen
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Data;
+using System.Data.Odbc;
+using System.Data.SqlClient;
+
+using NUnit.Framework;
+
+namespace MonoTests.System.Data.SqlClient
+{
+ [TestFixture]
+ public class SqlDataAdapterTest
+ {
+ [Test] // SqlDataAdapter ()
+ public void Constructor1 ()
+ {
+ SqlDataAdapter da = new SqlDataAdapter ();
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNull (da.SelectCommand, "#11");
+ Assert.IsNull (da.Site, "#12");
+ Assert.IsNotNull (da.TableMappings, "#13");
+ Assert.AreEqual (0, da.TableMappings.Count, "#14");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#15");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#16");
+ }
+
+ [Test] // SqlDataAdapter (SqlCommand)
+ public void Constructor2 ()
+ {
+ SqlCommand cmd = new SqlCommand ();
+ SqlDataAdapter da = new SqlDataAdapter (cmd);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.AreSame (cmd, da.SelectCommand, "#12");
+ Assert.IsNull (da.Site, "#13");
+ Assert.IsNotNull (da.TableMappings, "#14");
+ Assert.AreEqual (0, da.TableMappings.Count, "#15");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#16");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#17");
+ }
+
+ [Test] // SqlDataAdapter (SqlCommand)
+ public void Constructor2_SelectCommand_Null ()
+ {
+ SqlDataAdapter da = new SqlDataAdapter ((SqlCommand) null);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNull (da.SelectCommand, "#11");
+ Assert.IsNull (da.Site, "#12");
+ Assert.IsNotNull (da.TableMappings, "#13");
+ Assert.AreEqual (0, da.TableMappings.Count, "#14");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#15");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#16");
+ }
+
+ [Test] // SqlDataAdapter (string, SqlConnection)
+ public void Constructor3 ()
+ {
+ string selectCommandText = "SELECT * FROM Authors";
+ SqlConnection selectConnection = new SqlConnection ();
+
+ SqlDataAdapter da = new SqlDataAdapter (selectCommandText,
+ selectConnection);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.AreSame (selectCommandText, da.SelectCommand.CommandText, "#12");
+ Assert.AreSame (selectConnection, da.SelectCommand.Connection, "#13");
+ Assert.IsNull (da.Site, "#14");
+ Assert.IsNotNull (da.TableMappings, "#15");
+ Assert.AreEqual (0, da.TableMappings.Count, "#16");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#17");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#18");
+ }
+
+ [Test] // SqlDataAdapter (string, SqlConnection)
+ public void Constructor3_SelectCommandText_Null ()
+ {
+ SqlConnection selectConnection = new SqlConnection ();
+
+ SqlDataAdapter da = new SqlDataAdapter ((string) null,
+ selectConnection);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.IsNotNull (da.SelectCommand.CommandText, "#12");
+ Assert.AreEqual (string.Empty, da.SelectCommand.CommandText, "#13");
+ Assert.AreSame (selectConnection, da.SelectCommand.Connection, "#14");
+ Assert.IsNull (da.Site, "#15");
+ Assert.IsNotNull (da.TableMappings, "#16");
+ Assert.AreEqual (0, da.TableMappings.Count, "#17");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#18");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#19");
+ }
+
+ [Test] // SqlDataAdapter (string, SqlConnection)
+ public void Constructor3_SelectConnection_Null ()
+ {
+ string selectCommandText = "SELECT * FROM Authors";
+
+ SqlDataAdapter da = new SqlDataAdapter (selectCommandText,
+ (SqlConnection) null);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.AreSame (selectCommandText, da.SelectCommand.CommandText, "#12");
+ Assert.IsNull (da.SelectCommand.Connection, "#13");
+ Assert.IsNull (da.Site, "#14");
+ Assert.IsNotNull (da.TableMappings, "#15");
+ Assert.AreEqual (0, da.TableMappings.Count, "#16");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#17");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#18");
+ }
+
+ [Test] // SqlDataAdapter (string, string)]
+ public void Constructor4 ()
+ {
+ string selectCommandText = "SELECT * FROM Authors";
+ string selectConnectionString = "server=SQLSRV;database=Mono";
+
+ SqlDataAdapter da = new SqlDataAdapter (selectCommandText,
+ selectConnectionString);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.AreSame (selectCommandText, da.SelectCommand.CommandText, "#12");
+ Assert.IsNotNull (da.SelectCommand.Connection, "#13");
+ Assert.AreEqual (selectConnectionString, da.SelectCommand.Connection.ConnectionString, "#14");
+ Assert.IsNull (da.Site, "#15");
+ Assert.IsNotNull (da.TableMappings, "#16");
+ Assert.AreEqual (0, da.TableMappings.Count, "#17");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#18");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#19");
+ }
+
+ [Test] // SqlDataAdapter (string, string)]
+ public void Constructor4_SelectCommandText_Null ()
+ {
+ string selectConnectionString = "server=SQLSRV;database=Mono";
+
+ SqlDataAdapter da = new SqlDataAdapter ((string) null,
+ selectConnectionString);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.IsNotNull (da.SelectCommand.CommandText, "#12");
+ Assert.AreEqual (string.Empty, da.SelectCommand.CommandText, "#13");
+ Assert.IsNotNull (da.SelectCommand.Connection, "#14");
+ Assert.AreEqual (selectConnectionString, da.SelectCommand.Connection.ConnectionString, "#15");
+ Assert.IsNull (da.Site, "#16");
+ Assert.IsNotNull (da.TableMappings, "#17");
+ Assert.AreEqual (0, da.TableMappings.Count, "#18");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#19");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#20");
+ }
+
+ [Test] // SqlDataAdapter (string, string)]
+ public void Constructor4_SelectConnectionString_Null ()
+ {
+ string selectCommandText = "SELECT * FROM Authors";
+
+ SqlDataAdapter da = new SqlDataAdapter (selectCommandText,
+ (string) null);
+ Assert.IsTrue (da.AcceptChangesDuringFill, "#1");
+#if NET_2_0
+ Assert.IsTrue (da.AcceptChangesDuringUpdate, "#2");
+#endif
+ Assert.IsNull (da.Container, "#3");
+ Assert.IsFalse (da.ContinueUpdateOnError, "#4");
+ Assert.IsNull (da.DeleteCommand, "#5");
+#if NET_2_0
+ Assert.AreEqual (LoadOption.OverwriteChanges, da.FillLoadOption, "#6");
+#endif
+ Assert.IsNull (da.InsertCommand, "#7");
+ Assert.AreEqual (MissingMappingAction.Passthrough, da.MissingMappingAction, "#8");
+ Assert.AreEqual (MissingSchemaAction.Add, da.MissingSchemaAction, "#9");
+#if NET_2_0
+ Assert.IsFalse (da.ReturnProviderSpecificTypes, "#10");
+#endif
+ Assert.IsNotNull (da.SelectCommand, "#11");
+ Assert.AreSame (selectCommandText, da.SelectCommand.CommandText, "#12");
+ Assert.IsNotNull (da.SelectCommand.Connection, "#14");
+ Assert.AreEqual (string.Empty, da.SelectCommand.Connection.ConnectionString, "#15");
+ Assert.IsNull (da.Site, "#16");
+ Assert.IsNotNull (da.TableMappings, "#17");
+ Assert.AreEqual (0, da.TableMappings.Count, "#18");
+#if NET_2_0
+ Assert.AreEqual (1, da.UpdateBatchSize, "#19");
+#endif
+ Assert.IsNull (da.UpdateCommand, "#20");
+ }
+
+ [Test]
+ public void DeleteCommand ()
+ {
+ SqlDataAdapter da = new SqlDataAdapter ();
+ SqlCommand cmd1 = new SqlCommand ();
+ SqlCommand cmd2 = new SqlCommand ();
+
+ da.DeleteCommand = cmd1;
+ Assert.AreSame (cmd1, da.DeleteCommand, "#1");
+ da.DeleteCommand = cmd2;
+ Assert.AreSame (cmd2, da.DeleteCommand, "#2");
+ da.DeleteCommand = null;
+ Assert.IsNull (da.DeleteCommand, "#3");
+ }
+
+ [Test]
+ public void DeleteCommand_IDbDataAdapter ()
+ {
+ IDbDataAdapter da = new SqlDataAdapter ();
+ SqlCommand cmd1 = new SqlCommand ();
+ SqlCommand cmd2 = new SqlCommand ();
+
+ da.DeleteCommand = cmd1;
+ Assert.AreSame (cmd1, da.DeleteCommand, "#A1");
+ da.DeleteCommand = cmd2;
+ Assert.AreSame (cmd2, da.DeleteCommand, "#A2");
+ da.DeleteCommand = null;
+ Assert.IsNull (da.DeleteCommand, "#A3");
+
+ try {
+ da.DeleteCommand = new OdbcCommand ();
+ Assert.Fail ("#B1");
+ } catch (InvalidCastException ex) {
+ Assert.AreEqual (typeof (InvalidCastException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+ }
+
+ [Test]
+ public void Dispose ()
+ {
+ SqlDataAdapter da = new SqlDataAdapter ();
+ da.DeleteCommand = new SqlCommand ();
+ da.InsertCommand = new SqlCommand ();
+ da.SelectCommand = new SqlCommand ();
+ da.UpdateCommand = new SqlCommand ();
+ da.Dispose ();
+
+ Assert.IsNull (da.DeleteCommand, "#1");
+ Assert.IsNull (da.InsertCommand, "#2");
+ Assert.IsNull (da.SelectCommand, "#3");
+ Assert.IsNotNull (da.TableMappings, "#4");
+ Assert.AreEqual (0, da.TableMappings.Count, "#5");
+ Assert.IsNull (da.UpdateCommand, "#6");
+ }
+
+ [Test]
+ public void InsertCommand ()
+ {
+ SqlDataAdapter da = new SqlDataAdapter ();
+ SqlCommand cmd1 = new SqlCommand ();
+ SqlCommand cmd2 = new SqlCommand ();
+
+ da.InsertCommand = cmd1;
+ Assert.AreSame (cmd1, da.InsertCommand, "#1");
+ da.InsertCommand = cmd2;
+ Assert.AreSame (cmd2, da.InsertCommand, "#2");
+ da.InsertCommand = null;
+ Assert.IsNull (da.InsertCommand, "#3");
+ }
+
+ [Test]
+ public void InsertCommand_IDbDataAdapter ()
+ {
+ IDbDataAdapter da = new SqlDataAdapter ();
+ SqlCommand cmd1 = new SqlCommand ();
+ SqlCommand cmd2 = new SqlCommand ();
+
+ da.InsertCommand = cmd1;
+ Assert.AreSame (cmd1, da.InsertCommand, "#A1");
+ da.InsertCommand = cmd2;
+ Assert.AreSame (cmd2, da.InsertCommand, "#A2");
+ da.InsertCommand = null;
+ Assert.IsNull (da.InsertCommand, "#A3");
+
+ try {
+ da.InsertCommand = new OdbcCommand ();
+ Assert.Fail ("#B1");
+ } catch (InvalidCastException ex) {
+ Assert.AreEqual (typeof (InvalidCastException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+ }
+
+ [Test]
+ public void SelectCommand ()
+ {
+ SqlDataAdapter da = new SqlDataAdapter ();
+ SqlCommand cmd1 = new SqlCommand ();
+ SqlCommand cmd2 = new SqlCommand ();
+
+ da.SelectCommand = cmd1;
+ Assert.AreSame (cmd1, da.SelectCommand, "#1");
+ da.SelectCommand = cmd2;
+ Assert.AreSame (cmd2, da.SelectCommand, "#2");
+ da.SelectCommand = null;
+ Assert.IsNull (da.SelectCommand, "#3");
+ }
+
+ [Test]
+ public void SelectCommand_IDbDataAdapter ()
+ {
+ IDbDataAdapter da = new SqlDataAdapter ();
+ SqlCommand cmd1 = new SqlCommand ();
+ SqlCommand cmd2 = new SqlCommand ();
+
+ da.SelectCommand = cmd1;
+ Assert.AreSame (cmd1, da.SelectCommand, "#A1");
+ da.SelectCommand = cmd2;
+ Assert.AreSame (cmd2, da.SelectCommand, "#A2");
+ da.SelectCommand = null;
+ Assert.IsNull (da.SelectCommand, "#A3");
+
+ try {
+ da.SelectCommand = new OdbcCommand ();
+ Assert.Fail ("#B1");
+ } catch (InvalidCastException ex) {
+ Assert.AreEqual (typeof (InvalidCastException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+ }
+
+#if NET_2_0
+ [Test]
+ public void UpdateBatchSize ()
+ {
+ SqlDataAdapter da = new SqlDataAdapter ();
+ da.UpdateBatchSize = 0;
+ Assert.AreEqual (0, da.UpdateBatchSize, "#1");
+ da.UpdateBatchSize = int.MaxValue;
+ Assert.AreEqual (int.MaxValue, da.UpdateBatchSize, "#2");
+ da.UpdateBatchSize = 1;
+ Assert.AreEqual (1, da.UpdateBatchSize, "#3");
+ }
+
+ [Test]
+ public void UpdateBatchSize_Negative ()
+ {
+ SqlDataAdapter da = new SqlDataAdapter ();
+ try {
+ da.UpdateBatchSize = -1;
+ Assert.Fail ("#1");
+ } catch (ArgumentOutOfRangeException ex) {
+ Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("UpdateBatchSize", ex.ParamName, "#6");
+ }
+ }
+#endif
+
+ [Test]
+ public void UpdateCommand ()
+ {
+ SqlDataAdapter da = new SqlDataAdapter ();
+ SqlCommand cmd1 = new SqlCommand ();
+ SqlCommand cmd2 = new SqlCommand ();
+
+ da.UpdateCommand = cmd1;
+ Assert.AreSame (cmd1, da.UpdateCommand, "#1");
+ da.UpdateCommand = cmd2;
+ Assert.AreSame (cmd2, da.UpdateCommand, "#2");
+ da.UpdateCommand = null;
+ Assert.IsNull (da.UpdateCommand, "#3");
+ }
+
+ [Test]
+ public void UpdateCommand_IDbDataAdapter ()
+ {
+ IDbDataAdapter da = new SqlDataAdapter ();
+ SqlCommand cmd1 = new SqlCommand ();
+ SqlCommand cmd2 = new SqlCommand ();
+
+ da.UpdateCommand = cmd1;
+ Assert.AreSame (cmd1, da.UpdateCommand, "#A1");
+ da.UpdateCommand = cmd2;
+ Assert.AreSame (cmd2, da.UpdateCommand, "#A2");
+ da.UpdateCommand = null;
+ Assert.IsNull (da.UpdateCommand, "#A3");
+
+ try {
+ da.UpdateCommand = new OdbcCommand ();
+ Assert.Fail ("#B1");
+ } catch (InvalidCastException ex) {
+ Assert.AreEqual (typeof (InvalidCastException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ }
+ }
+ }
+}
+2007-10-21 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * DataColumnTest.cs: No longer derive from deprecated Assertion class.
+ Code formatting. Added test for DateTimeMode.
+
2007-08-06 Nagappan A <anagappan@novell.com>
* DataTableTest.cs (Bug55978): In some cases this test case was
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
-using NUnit.Framework;
using System;
+using System.ComponentModel;
using System.Data;
+using NUnit.Framework;
+
namespace MonoTests.System.Data
{
[TestFixture]
- public class DataColumnTest : Assertion
+ public class DataColumnTest
{
private DataTable _tbl;
}
[Test]
- public void Ctor()
+ public void Ctor()
{
string colName = "ColName";
- DataColumn col = new DataColumn();
+ DataColumn col = new DataColumn ();
//These should all ctor without an exception
- col = new DataColumn(colName);
- col = new DataColumn(colName,typeof(int));
- col = new DataColumn(colName,typeof(int),null);
- col = new DataColumn(colName,typeof(int),null,MappingType.Attribute);
-
- //DataType Null
- try
- {
- col = new DataColumn(colName, null);
- Fail("DC7: Failed to throw ArgumentNullException.");
- }
- catch (ArgumentNullException){}
- catch (AssertionException exc) {throw exc;}
- catch (Exception exc)
- {
- Fail("DC8: DataColumnNull. Wrong exception type. Got:" + exc);
- }
+ col = new DataColumn (colName);
+ col = new DataColumn (colName, typeof(int));
+ col = new DataColumn (colName, typeof(int), null);
+ col = new DataColumn (colName, typeof(int), null, MappingType.Attribute);
+ }
+ [Test]
+ public void Constructor3_DataType_Null ()
+ {
+ try {
+ new DataColumn ("ColName", (Type) null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("dataType", ex.ParamName, "#6");
+ }
}
[Test]
_tbl.Rows.Add(_tbl.NewRow());
_tbl.Rows[0]["NullCheck"] = DBNull.Value;
try {
- col.AllowDBNull = false;
- Fail("DC8b: Failed to throw DataException.");
- }
- catch (DataException) {}
- catch (Exception exc) {
- Fail("DC8c: Wrong exception type. Got:" + exc);
+ col.AllowDBNull = false;
+ Assert.Fail ("DC8b: Failed to throw DataException.");
+ } catch (DataException) {
}
}
col.AllowDBNull = true;
col.AllowDBNull = false;
- AssertEquals (false, col.AllowDBNull);
+ Assert.IsFalse (col.AllowDBNull);
}
[Test]
public void AutoIncrement()
{
- DataColumn col = new DataColumn("Auto",typeof(string));
+ DataColumn col = new DataColumn("Auto",typeof (string));
col.AutoIncrement = true;
//Check for Correct Default Values
- AssertEquals("DC9: Seed default", (long)0, col.AutoIncrementSeed);
- AssertEquals("DC10: Step default", (long)1, col.AutoIncrementStep);
+ Assert.AreEqual (0L, col.AutoIncrementSeed, "#1");
+ Assert.AreEqual (1L, col.AutoIncrementStep, "#2");
//Check for auto type convert
- Assert("DC11: AutoInc type convert failed." ,col.DataType == typeof (int));
+ Assert.AreEqual (typeof (int), col.DataType, "#3");
}
[Test]
public void AutoIncrementExceptions()
{
DataColumn col = new DataColumn();
-
col.Expression = "SomeExpression";
//if computed column exception is thrown
- try
- {
+ try {
col.AutoIncrement = true;
- Fail("DC12: Failed to throw ArgumentException");
- }
- catch (ArgumentException){}
- catch (AssertionException exc) {throw exc;}
- catch (Exception exc)
- {
- Fail("DC13: ExprAutoInc. Wrong exception type. Got:" + exc);
+ Assert.Fail ("DC12: Failed to throw ArgumentException");
+ } catch (ArgumentException) {
}
-
-
}
[Test]
{
DataColumn col = new DataColumn("ColName");
//Caption not set at this point
- AssertEquals("DC14: Caption Should Equal Col Name", col.ColumnName, col.Caption);
+ Assert.AreEqual (col.ColumnName, col.Caption, "#1");
//Set caption
col.Caption = "MyCaption";
- AssertEquals("DC15: Caption should equal caption.", "MyCaption", col.Caption);
+ Assert.AreEqual ("MyCaption", col.Caption, "#2");
//Clear caption
col.Caption = null;
- AssertEquals("DC16: Caption Should Equal empty string after clear", String.Empty, col.Caption);
-
+ Assert.AreEqual (string.Empty, col.Caption, "#3");
+ }
+
+#if NET_2_0
+ [Test]
+ public void DateTimeMode_Valid ()
+ {
+ DataColumn col = new DataColumn ("birthdate", typeof (DateTime));
+ col.DateTimeMode = DataSetDateTime.Local;
+ Assert.AreEqual (DataSetDateTime.Local, col.DateTimeMode, "#1");
+ col.DateTimeMode = DataSetDateTime.Unspecified;
+ Assert.AreEqual (DataSetDateTime.Unspecified, col.DateTimeMode, "#2");
+ col.DateTimeMode = DataSetDateTime.Utc;
+ Assert.AreEqual (DataSetDateTime.Utc, col.DateTimeMode, "#3");
+ }
+
+ [Test]
+ public void DateTime_DataType_Invalid ()
+ {
+ DataColumn col = new DataColumn ("birthdate", typeof (int));
+ try {
+ col.DateTimeMode = DataSetDateTime.Local;
+ Assert.Fail ("#1");
+ } catch (InvalidOperationException ex) {
+ // The DateTimeMode can be set only on DataColumns
+ // of type DateTime
+ Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsTrue (ex.Message.IndexOf ("DateTimeMode") != -1, "#5");
+ Assert.IsTrue (ex.Message.IndexOf ("DateTime") != -1, "#6");
+ }
+ }
+
+ [Test]
+ public void DateTimeMode_Invalid ()
+ {
+ DataColumn col = new DataColumn ("birthdate", typeof (DateTime));
+ try {
+ col.DateTimeMode = (DataSetDateTime) 666;
+ Assert.Fail ("#1");
+ } catch (InvalidEnumArgumentException ex) {
+ // The DataSetDateTime enumeration value, 666, is invalid
+ Assert.AreEqual (typeof (InvalidEnumArgumentException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsTrue (ex.Message.IndexOf ("DataSetDateTime") != -1, "#5");
+ Assert.IsTrue (ex.Message.IndexOf ("666") != -1, "#6");
+ Assert.IsNull (ex.ParamName, "#7");
+ }
}
+#endif
[Test]
public void ForColumnNameException()
DataColumn col4 = new DataColumn();
col.ColumnName = "abc";
- AssertEquals( "abc", col.ColumnName);
+ Assert.AreEqual ("abc", col.ColumnName, "#1");
_tbl.Columns.Add(col);
//Duplicate name exception
- try
- {
+ try {
col2.ColumnName = "abc";
_tbl.Columns.Add(col2);
- AssertEquals( "abc", col2.ColumnName);
- Fail("DC17: Failed to throw duplicate name exception.");
+ Assert.AreEqual ("abc", col2.ColumnName, "#2");
+ Assert.Fail ("#3");
+ } catch (DuplicateNameException) {
}
- catch (DuplicateNameException){}
- catch (AssertionException exc) {throw exc;}
- catch (Exception exc)
- {
- Fail("DC18: Wrong exception type. " + exc.ToString());
- }
-
// Make sure case matters in duplicate checks
col3.ColumnName = "ABC";
_tbl.Columns.Add(col3);
//Set default Value if Autoincrement is true
tbl.Columns[0].AutoIncrement = true;
- try
- {
+ try {
tbl.Columns[0].DefaultValue = 2;
- Fail("DC19: Failed to throw ArgumentException.");
- }
- catch (ArgumentException){}
- catch (AssertionException exc) {throw exc;}
- catch (Exception exc)
- {
- Fail("DC20: Wrong exception type. " + exc.ToString());
+ Assert.Fail ("DC19: Failed to throw ArgumentException.");
+ } catch (ArgumentException) {
}
-
tbl.Columns[0].AutoIncrement = false;
//Set default value to an incompatible datatype
- try
- {
+ try {
tbl.Columns[0].DefaultValue = "hello";
- Fail("DC21: Failed to throw FormatException.");
- }
- catch (FormatException){}
- catch (AssertionException exc) {throw exc;}
- catch (Exception exc)
- {
- Fail("DC22: Wrong exception type. " + exc.ToString());
+ Assert.Fail ("DC21: Failed to throw FormatException.");
+ } catch (FormatException) {
}
//TODO: maybe add tests for setting default value for types that can implict
//cast
-
-
-
-
}
[Test]
- public void SetDataType()
+ public void SetDataType ()
{
//test for DataAlready exists and change the datatype
-
//supported datatype
-
//AutoInc column dataType supported
-
}
[Test]
- public void Defaults1()
+ public void Defaults1 ()
{
//Check for defaults - ColumnName not set at the beginning
- DataTable table = new DataTable();
+ DataTable table = new DataTable();
DataColumn column = new DataColumn();
-
- AssertEquals("DC1: ColumnName default Before Add", column.ColumnName, String.Empty);
- AssertEquals("DC2: DataType default Before Add", column.DataType.ToString(), typeof(string).ToString());
+
+ Assert.AreEqual (String.Empty, column.ColumnName, "#A1");
+ Assert.AreEqual (typeof (string), column.DataType, "#A2");
table.Columns.Add(column);
-
- AssertEquals("DC3: ColumnName default After Add", table.Columns[0].ColumnName, "Column1");
- AssertEquals("DC4: DataType default After Add", table.Columns[0].DataType.ToString(), typeof(string).ToString());
+
+ Assert.AreEqual ("Column1", table.Columns [0].ColumnName, "#B1");
+ Assert.AreEqual (typeof (string), table.Columns [0].DataType, "#B2");
DataRow row = table.NewRow();
table.Rows.Add(row);
DataRow dataRow = table.Rows[0];
- object v = null;
- try {
- v = dataRow.ItemArray[0];
- }
- catch(Exception e) {
- Fail("DC5: getting item from dataRow.ItemArray[0] threw Exception: " + e);
- }
-
- Type vType = dataRow.ItemArray[0].GetType();
- AssertEquals("DC6: Value from DataRow.Item", v, DBNull.Value);
+ object v = dataRow.ItemArray [0];
+ Assert.AreEqual (typeof (DBNull), v.GetType (), "#C1");
+ Assert.AreEqual (DBNull.Value, v, "#C2");
}
[Test]
- public void Defaults2()
+ public void Defaults2 ()
{
//Check for defaults - ColumnName set at the beginning
string blah = "Blah";
//Check for defaults - ColumnName not set at the beginning
- DataTable table = new DataTable();
+ DataTable table = new DataTable();
DataColumn column = new DataColumn(blah);
-
- AssertEquals("DC23: ColumnName default Before Add", column.ColumnName,blah);
- AssertEquals("DC24: DataType default Before Add", column.DataType.ToString(), typeof(string).ToString());
+
+ Assert.AreEqual (blah, column.ColumnName, "#A1");
+ Assert.AreEqual (typeof (string), column.DataType, "#A2");
table.Columns.Add(column);
- AssertEquals("DC25: ColumnName default After Add", table.Columns[0].ColumnName, blah);
- AssertEquals("DC26: DataType default After Add", table.Columns[0].DataType.ToString(), typeof(string).ToString());
+ Assert.AreEqual (blah, table.Columns[0].ColumnName, "#B1");
+ Assert.AreEqual (typeof (string), table.Columns[0].DataType, "#B2");
DataRow row = table.NewRow();
table.Rows.Add(row);
DataRow dataRow = table.Rows[0];
- object v = null;
- try {
- v = dataRow.ItemArray[0];
- }
- catch(Exception e) {
- Fail("DC27: getting item from dataRow.ItemArray[0] threw Exception: " + e);
- }
-
- Type vType = dataRow.ItemArray[0].GetType();
- AssertEquals("DC28: Value from DataRow.Item", v, DBNull.Value);
+ object v = dataRow.ItemArray[0];
+ Assert.AreEqual (typeof (DBNull), v.GetType (), "#C1");
+ Assert.AreEqual (DBNull.Value, v, "#C2");
}
[Test]
- [ExpectedException (typeof (OverflowException))]
- public void ExpressionSubstringlimits() {
- DataTable t = new DataTable();
- t.Columns.Add("aaa");
- t.Rows.Add(new object[]{"xxx"});
- DataColumn c = t.Columns.Add("bbb");
- c.Expression= "SUBSTRING(aaa, 6000000000000000, 2)";
+ public void ExpressionSubstringlimits () {
+ DataTable t = new DataTable ();
+ t.Columns.Add ("aaa");
+ t.Rows.Add (new object [] {"xxx"});
+ DataColumn c = t.Columns.Add ("bbb");
+ try {
+ c.Expression = "SUBSTRING(aaa, 6000000000000000, 2)";
+ Assert.Fail ("#1");
+ } catch (OverflowException) {
+ }
}
[Test]
- public void ExpressionFunctions ()
- {
- DataTable T = new DataTable ("test");
+ public void ExpressionFunctions ()
+ {
+ DataTable T = new DataTable ("test");
DataColumn C = new DataColumn ("name");
T.Columns.Add (C);
C = new DataColumn ("age");
C.DataType = typeof (int);
T.Columns.Add (C);
C = new DataColumn ("id");
- C.Expression = "substring (name, 1, 3) + len (name) + age";
+ C.Expression = "substring (name, 1, 3) + len (name) + age";
T.Columns.Add (C);
DataSet Set = new DataSet ("TestSet");
Row [0] = "h*an";
Row [1] = DBNull.Value;
T.Rows.Add (Row);
-
- AssertEquals ("DC29", "hum710", T.Rows [10] [2]);
- AssertEquals ("DC30", "hum64", T.Rows [4] [2]);
- C = T.Columns [2];
- C.Expression = "isnull (age, 'succ[[]]ess')";
- AssertEquals ("DC31", "succ[[]]ess", T.Rows [100] [2]);
-
- C.Expression = "iif (age = 24, 'hurrey', 'boo')";
- AssertEquals ("DC32", "boo", T.Rows [50] [2]);
- AssertEquals ("DC33", "hurrey", T.Rows [24] [2]);
-
- C.Expression = "convert (age, 'System.Boolean')";
- AssertEquals ("DC32", Boolean.TrueString, T.Rows [50] [2]);
- AssertEquals ("DC32", Boolean.FalseString, T.Rows [0] [2]);
-
- //
- // Exceptions
- //
-
- try {
- C.Expression = "iff (age = 24, 'hurrey', 'boo')";
-
- // The expression contains undefined function call iff().
- Fail ("DC34");
+
+ Assert.AreEqual ("hum710", T.Rows [10] [2], "#A1");
+ Assert.AreEqual ("hum64", T.Rows [4] [2], "#A2");
+ C = T.Columns [2];
+ C.Expression = "isnull (age, 'succ[[]]ess')";
+ Assert.AreEqual ("succ[[]]ess", T.Rows [100] [2], "#A3");
+
+ C.Expression = "iif (age = 24, 'hurrey', 'boo')";
+ Assert.AreEqual ("boo", T.Rows [50] [2], "#B1");
+ Assert.AreEqual ("hurrey", T.Rows [24] [2], "#B2");
+
+ C.Expression = "convert (age, 'System.Boolean')";
+ Assert.AreEqual (Boolean.TrueString, T.Rows [50] [2], "#C1");
+ Assert.AreEqual (Boolean.FalseString, T.Rows [0] [2], "#C2");
+
+ //
+ // Exceptions
+ //
+
+ try {
+ // The expression contains undefined function call iff().
+ C.Expression = "iff (age = 24, 'hurrey', 'boo')";
+ Assert.Fail ("#D");
} catch (EvaluateException) {
} catch (SyntaxErrorException) {
}
-
- //The following two cases fail on mono. MS.net evaluates the expression
- //immediatly upon assignment. We don't do this yet hence we don't throw
- //an exception at this point.
- try {
- C.Expression = "iif (nimi = 24, 'hurrey', 'boo')";
- Fail ("DC36");
- } catch (EvaluateException e) {
- AssertEquals ("DC37", typeof (EvaluateException), e.GetType ());
- AssertEquals ("DC38", "Cannot find column [nimi].", e.Message);
- }
-
- try {
- C.Expression = "iif (name = 24, 'hurrey', 'boo')";
- Fail ("DC39");
- } catch (Exception e) {
- AssertEquals ("DC40", typeof (EvaluateException), e.GetType ());
- //AssertEquals ("DC41", "Cannot perform '=' operation on System.String and System.Int32.", e.Message);
- }
-
-
- try {
- C.Expression = "convert (age, Boolean)";
- Fail ("DC42");
- } catch (Exception e) {
- AssertEquals ("DC43", typeof (EvaluateException), e.GetType ());
- AssertEquals ("DC44", "Invalid type name 'Boolean'.", e.Message);
- }
-
- }
+ //The following two cases fail on mono. MS.net evaluates the expression
+ //immediatly upon assignment. We don't do this yet hence we don't throw
+ //an exception at this point.
+ try {
+ C.Expression = "iif (nimi = 24, 'hurrey', 'boo')";
+ Assert.Fail ("#E1");
+ } catch (EvaluateException e) {
+ Assert.AreEqual (typeof (EvaluateException), e.GetType (), "#E2");
+ Assert.AreEqual ("Cannot find column [nimi].", e.Message, "#E3");
+ }
+
+ try {
+ C.Expression = "iif (name = 24, 'hurrey', 'boo')";
+ Assert.Fail ("#F1");
+ } catch (EvaluateException e) {
+ Assert.AreEqual (typeof (EvaluateException), e.GetType (), "#F2");
+ //AssertEquals ("DC41", "Cannot perform '=' operation on System.String and System.Int32.", e.Message);
+ }
+
+ try {
+ C.Expression = "convert (age, Boolean)";
+ Assert.Fail ("#G1");
+ } catch (EvaluateException e) {
+ Assert.AreEqual (typeof (EvaluateException), e.GetType (), "#G2");
+ Assert.AreEqual ("Invalid type name 'Boolean'.", e.Message, "#G3");
+ }
+ }
[Test]
- public void ExpressionAggregates ()
- {
- DataTable T = new DataTable ("test");
+ public void ExpressionAggregates ()
+ {
+ DataTable T = new DataTable ("test");
DataTable T2 = new DataTable ("test2");
-
+
DataColumn C = new DataColumn ("name");
T.Columns.Add (C);
C = new DataColumn ("age");
T.Columns.Add (C);
C = new DataColumn ("childname");
T.Columns.Add (C);
-
+
C = new DataColumn ("expression");
T.Columns.Add (C);
T.Rows.Add (Row);
C = new DataColumn ("name");
- T2.Columns.Add (C);
+ T2.Columns.Add (C);
C = new DataColumn ("age");
C.DataType = typeof (int);
T2.Columns.Add (C);
-
+
for (int i = 0; i < 100; i++) {
Row = T2.NewRow ();
Row [0] = "child" + i;
Row [1] = i - 2;
T2.Rows.Add (Row);
}
-
- DataRelation Rel = new DataRelation ("Rel", T.Columns [2], T2.Columns [0]);
- Set.Relations.Add (Rel);
-
- C = T.Columns [3];
- C.Expression = "Sum (Child.age)";
- AssertEquals ("DC45", "-2", T.Rows [0] [3]);
- AssertEquals ("DC46", "98", T.Rows [50] [3]);
-
+
+ DataRelation Rel = new DataRelation ("Rel", T.Columns [2], T2.Columns [0]);
+ Set.Relations.Add (Rel);
+
+ C = T.Columns [3];
+ C.Expression = "Sum (Child.age)";
+ Assert.AreEqual ("-2", T.Rows [0] [3], "#A1");
+ Assert.AreEqual ("98", T.Rows [50] [3], "#A2");
+
C.Expression = "Count (Child.age)";
- AssertEquals ("DC47", "2", T.Rows [0] [3]);
- AssertEquals ("DC48", "2", T.Rows [60] [3]);
+ Assert.AreEqual ("2", T.Rows [0] [3], "#B1");
+ Assert.AreEqual ("2", T.Rows [60] [3], "#B2");
C.Expression = "Avg (Child.age)";
- AssertEquals ("DC49", "-1", T.Rows [0] [3]);
- AssertEquals ("DC50", "59", T.Rows [60] [3]);
+ Assert.AreEqual ("-1", T.Rows [0] [3], "#C1");
+ Assert.AreEqual ("59", T.Rows [60] [3], "#C2");
C.Expression = "Min (Child.age)";
- AssertEquals ("DC51", "-2", T.Rows [0] [3]);
- AssertEquals ("DC52", "58", T.Rows [60] [3]);
+ Assert.AreEqual ("-2", T.Rows [0] [3], "#D1");
+ Assert.AreEqual ("58", T.Rows [60] [3], "#D2");
C.Expression = "Max (Child.age)";
- AssertEquals ("DC53", "0", T.Rows [0] [3]);
- AssertEquals ("DC54", "60", T.Rows [60] [3]);
+ Assert.AreEqual ("0", T.Rows [0] [3], "#E1");
+ Assert.AreEqual ("60", T.Rows [60] [3], "#E2");
C.Expression = "stdev (Child.age)";
- AssertEquals ("DC55", (1.4142135623731).ToString(), T.Rows [0] [3]);
- AssertEquals ("DC56", (1.4142135623731).ToString(), T.Rows [60] [3]);
+ Assert.AreEqual ((1.4142135623731).ToString (), T.Rows [0] [3], "#F1");
+ Assert.AreEqual ((1.4142135623731).ToString (), T.Rows [60] [3], "#F2");
C.Expression = "var (Child.age)";
- AssertEquals ("DC57", "2", T.Rows [0] [3]);
- AssertEquals ("DC58", "2", T.Rows [60] [3]);
- }
+ Assert.AreEqual ("2", T.Rows [0] [3], "#G1");
+ Assert.AreEqual ("2", T.Rows [60] [3], "#G2");
+ }
[Test]
public void ExpressionOperator ()
{
- DataTable T = new DataTable ("test");
+ DataTable T = new DataTable ("test");
DataColumn C = new DataColumn ("name");
T.Columns.Add (C);
C = new DataColumn ("age");
C.DataType = typeof (int);
T.Columns.Add (C);
C = new DataColumn ("id");
- C.Expression = "substring (name, 1, 3) + len (name) + age";
+ C.Expression = "substring (name, 1, 3) + len (name) + age";
T.Columns.Add (C);
DataSet Set = new DataSet ("TestSet");
Row [1] = DBNull.Value;
T.Rows.Add (Row);
- C = T.Columns [2];
- C.Expression = "age + 4";
- AssertEquals ("DC59", "68", T.Rows [64] [2]);
+ C = T.Columns [2];
+ C.Expression = "age + 4";
+ Assert.AreEqual ("68", T.Rows [64] [2], "#A");
C.Expression = "age - 4";
- AssertEquals ("DC60", "60", T.Rows [64] [2]);
+ Assert.AreEqual ("60", T.Rows [64] [2], "#B");
C.Expression = "age * 4";
- AssertEquals ("DC61", "256", T.Rows [64] [2]);
+ Assert.AreEqual ("256", T.Rows [64] [2], "#C");
C.Expression = "age / 4";
- AssertEquals ("DC62", "16", T.Rows [64] [2]);
+ Assert.AreEqual ("16", T.Rows [64] [2], "#D");
C.Expression = "age % 5";
- AssertEquals ("DC63", "4", T.Rows [64] [2]);
+ Assert.AreEqual ("4", T.Rows [64] [2], "#E");
C.Expression = "age in (5, 10, 15, 20, 25)";
- AssertEquals ("DC64", "False", T.Rows [64] [2]);
- AssertEquals ("DC65", "True", T.Rows [25] [2]);
+ Assert.AreEqual ("False", T.Rows [64] [2], "#F1");
+ Assert.AreEqual ("True", T.Rows [25] [2], "#F2");
C.Expression = "name like 'human1%'";
- AssertEquals ("DC66", "True", T.Rows [1] [2]);
- AssertEquals ("DC67", "False", T.Rows [25] [2]);
+ Assert.AreEqual ("True", T.Rows [1] [2], "#G1");
+ Assert.AreEqual ("False", T.Rows [25] [2], "#G2");
- C.Expression = "age < 4";
- AssertEquals ("DC68", "False", T.Rows [4] [2]);
- AssertEquals ("DC69", "True", T.Rows [3] [2]);
+ C.Expression = "age < 4";
+ Assert.AreEqual ("False", T.Rows [4] [2], "#H1");
+ Assert.AreEqual ("True", T.Rows [3] [2], "#H2");
- C.Expression = "age <= 4";
- AssertEquals ("DC70", "True", T.Rows [4] [2]);
- AssertEquals ("DC71", "False", T.Rows [5] [2]);
+ C.Expression = "age <= 4";
+ Assert.AreEqual ("True", T.Rows [4] [2], "#I1");
+ Assert.AreEqual ("False", T.Rows [5] [2], "#I2");
- C.Expression = "age > 4";
- AssertEquals ("DC72", "False", T.Rows [4] [2]);
- AssertEquals ("DC73", "True", T.Rows [5] [2]);
+ C.Expression = "age > 4";
+ Assert.AreEqual ("False", T.Rows [4] [2], "#J1");
+ Assert.AreEqual ("True", T.Rows [5] [2], "#J2");
- C.Expression = "age >= 4";
- AssertEquals ("DC74", "True", T.Rows [4] [2]);
- AssertEquals ("DC75", "False", T.Rows [1] [2]);
+ C.Expression = "age >= 4";
+ Assert.AreEqual ("True", T.Rows [4] [2], "#K1");
+ Assert.AreEqual ("False", T.Rows [1] [2], "#K2");
- C.Expression = "age = 4";
- AssertEquals ("DC76", "True", T.Rows [4] [2]);
- AssertEquals ("DC77", "False", T.Rows [1] [2]);
+ C.Expression = "age = 4";
+ Assert.AreEqual ("True", T.Rows [4] [2], "#L1");
+ Assert.AreEqual ("False", T.Rows [1] [2], "#L2");
- C.Expression = "age <> 4";
- AssertEquals ("DC76", "False", T.Rows [4] [2]);
- AssertEquals ("DC77", "True", T.Rows [1] [2]);
+ C.Expression = "age <> 4";
+ Assert.AreEqual ("False", T.Rows [4] [2], "#M1");
+ Assert.AreEqual ("True", T.Rows [1] [2], "#M2");
}
-
+
[Test]
- [ExpectedException (typeof (ArgumentException))]
public void SetMaxLengthException ()
{
// Setting MaxLength on SimpleContent -> exception
ds.Tables.Add("MyType");
ds.Tables["MyType"].Columns.Add(new DataColumn("Desc",
typeof (string), "", MappingType.SimpleContent));
- ds.Tables["MyType"].Columns["Desc"].MaxLength = 32;
+ try {
+ ds.Tables ["MyType"].Columns ["Desc"].MaxLength = 32;
+ Assert.Fail ("#1");
+ } catch (ArgumentException) {
+ }
}
[Test]
}
[Test]
- public void AdditionToConstraintCollectionTest()
- {
- DataTable myTable = new DataTable("myTable");
- DataColumn idCol = new DataColumn("id",Type.GetType("System.Int32")); //set the unique property and add them to the table
- idCol.Unique=true;
- myTable.Columns.Add(idCol);
- ConstraintCollection cc = myTable.Constraints;
- //cc just contains a single UniqueConstraint object.
- UniqueConstraint uc = cc[0] as UniqueConstraint;
- AssertEquals("#verifying whether the column associated with the UniqueConstraint is same:", uc.Columns[0].ColumnName , "id");
-
- }
-
- // Testcase for #77025
- [Test]
+ public void AdditionToConstraintCollectionTest()
+ {
+ DataTable myTable = new DataTable("myTable");
+ DataColumn idCol = new DataColumn("id", typeof (int));
+ idCol.Unique = true;
+ myTable.Columns.Add(idCol);
+ ConstraintCollection cc = myTable.Constraints;
+ //cc just contains a single UniqueConstraint object.
+ UniqueConstraint uc = cc[0] as UniqueConstraint;
+ Assert.AreEqual ("id", uc.Columns[0].ColumnName);
+ }
+
+ [Test] // bug #77025
public void CalcStatisticalFunction_SingleElement()
{
DataTable table = new DataTable ();
table.Columns.Add ("result_stdev", typeof (double), "stdev(test)");
// Check DBNull.Value is set as the result
- AssertEquals ("#1" , typeof (DBNull), (table.Rows[0]["result_var"]).GetType ());
- AssertEquals ("#2" , typeof (DBNull), (table.Rows[0]["result_stdev"]).GetType ());
+ Assert.AreEqual (typeof (DBNull), (table.Rows[0]["result_var"]).GetType (), "#1");
+ Assert.AreEqual (typeof (DBNull), (table.Rows [0] ["result_stdev"]).GetType (), "#2");
}
[Test]
// Adding the rows after all the expression columns are added
table.Rows.Add (new object[] {0});
- AssertEquals ("#1", 1, table.Rows[0]["result_count"]);
- AssertEquals ("#2", 0, table.Rows[0]["result_sum"]);
- AssertEquals ("#3", 0, table.Rows[0]["result_avg"]);
- AssertEquals ("#4", 0, table.Rows[0]["result_max"]);
- AssertEquals ("#5", 0, table.Rows[0]["result_min"]);
- AssertEquals ("#6", DBNull.Value, table.Rows[0]["result_var"]);
- AssertEquals ("#7", DBNull.Value, table.Rows[0]["result_stdev"]);
+ Assert.AreEqual (1, table.Rows [0] ["result_count"], "#A1");
+ Assert.AreEqual (0, table.Rows [0] ["result_sum"], "#A2");
+ Assert.AreEqual (0, table.Rows [0] ["result_avg"], "#A3");
+ Assert.AreEqual (0, table.Rows [0] ["result_max"], "#A4");
+ Assert.AreEqual (0, table.Rows [0] ["result_min"], "#A5");
+ Assert.AreEqual (DBNull.Value, table.Rows [0] ["result_var"], "#A6");
+ Assert.AreEqual (DBNull.Value, table.Rows [0] ["result_stdev"], "#A7");
table.Rows.Add (new object[] {1});
table.Rows.Add (new object[] {-2});
// Check if the aggregate columns are updated correctly
- AssertEquals ("#8", 3, table.Rows[0]["result_count"]);
- AssertEquals ("#9", -1, table.Rows[0]["result_sum"]);
- AssertEquals ("#10", 0, table.Rows[0]["result_avg"]);
- AssertEquals ("#11", 1, table.Rows[0]["result_max"]);
- AssertEquals ("#12", -2, table.Rows[0]["result_min"]);
- AssertEquals ("#13", (7.0/3), table.Rows[0]["result_var"]);
- AssertEquals ("#14", Math.Sqrt(7.0/3), table.Rows[0]["result_stdev"]);
+ Assert.AreEqual (3, table.Rows [0] ["result_count"], "#B1");
+ Assert.AreEqual (-1, table.Rows [0] ["result_sum"], "#B2");
+ Assert.AreEqual (0, table.Rows [0] ["result_avg"], "#B3");
+ Assert.AreEqual (1, table.Rows [0] ["result_max"], "#B4");
+ Assert.AreEqual (-2, table.Rows [0] ["result_min"], "#B5");
+ Assert.AreEqual ((7.0 / 3), table.Rows [0] ["result_var"], "#B6");
+ Assert.AreEqual (Math.Sqrt (7.0 / 3), table.Rows [0] ["result_stdev"], "#B7");
}
[Test]
table2.Rows.Add (new object[] {1,j});
// Check the values for the expression columns in parent table
- AssertEquals ("#1", 10, table.Rows[0]["result_count"]);
- AssertEquals ("#2", 0, table.Rows[1]["result_count"]);
+ Assert.AreEqual (10, table.Rows [0] ["result_count"], "#A1");
+ Assert.AreEqual (0, table.Rows [1] ["result_count"], "#A2");
- AssertEquals ("#3", 10, table.Rows[0]["result_sum"]);
- AssertEquals ("#4", DBNull.Value, table.Rows[1]["result_sum"]);
+ Assert.AreEqual (10, table.Rows [0] ["result_sum"], "#B1");
+ Assert.AreEqual (DBNull.Value, table.Rows [1] ["result_sum"], "#B2");
- AssertEquals ("#5", 1, table.Rows[0]["result_avg"]);
- AssertEquals ("#6", DBNull.Value, table.Rows[1]["result_avg"]);
+ Assert.AreEqual (1, table.Rows [0] ["result_avg"], "#C1");
+ Assert.AreEqual (DBNull.Value, table.Rows [1] ["result_avg"], "#C2");
- AssertEquals ("#7", 1, table.Rows[0]["result_max"]);
- AssertEquals ("#8", DBNull.Value, table.Rows[1]["result_max"]);
+ Assert.AreEqual (1, table.Rows [0] ["result_max"], "#D1");
+ Assert.AreEqual (DBNull.Value, table.Rows [1] ["result_max"], "#D2");
- AssertEquals ("#7", 1, table.Rows[0]["result_min"]);
- AssertEquals ("#8", DBNull.Value, table.Rows[1]["result_min"]);
+ Assert.AreEqual (1, table.Rows [0] ["result_min"], "#E1");
+ Assert.AreEqual (DBNull.Value, table.Rows [1] ["result_min"], "#E2");
- AssertEquals ("#9", 0, table.Rows[0]["result_var"]);
- AssertEquals ("#10", DBNull.Value, table.Rows[1]["result_var"]);
+ Assert.AreEqual (0, table.Rows [0] ["result_var"], "#F1");
+ Assert.AreEqual (DBNull.Value, table.Rows [1] ["result_var"], "#F2");
- AssertEquals ("#11", 0, table.Rows[0]["result_stdev"]);
- AssertEquals ("#12", DBNull.Value, table.Rows[1]["result_stdev"]);
+ Assert.AreEqual (0, table.Rows [0] ["result_stdev"], "#G1");
+ Assert.AreEqual (DBNull.Value, table.Rows [1] ["result_stdev"], "#G2");
}
[Test]
error = "Aggregation Functions cannot be called on Columns Returning Single Row (Parent Column)";
try {
table2.Columns.Add ("result", typeof (int), "count(parent.test)");
- Fail ("#1" + error);
- }catch (SyntaxErrorException) {
+ Assert.Fail ("#1" + error);
+ } catch (SyntaxErrorException) {
}
error = "Numerical or Functions cannot be called on Columns Returning Multiple Rows (Child Column)";
// Check arithematic operator
try {
table2.Columns.Add ("result", typeof (int), "10*(child.test)");
- Fail ("#2" + error);
- }catch (SyntaxErrorException) {
+ Assert.Fail ("#2" + error);
+ } catch (SyntaxErrorException) {
}
// Check rel operator
try {
table2.Columns.Add ("result", typeof (int), "(child.test) > 10");
- Fail ("#3" + error);
- }catch (SyntaxErrorException) {
+ Assert.Fail ("#3" + error);
+ } catch (SyntaxErrorException) {
}
// Check predicates
try {
table2.Columns.Add ("result", typeof (int), "(child.test) IN (1,2,3)");
- Fail ("#4" + error);
- }catch (SyntaxErrorException) {
+ Assert.Fail ("#4" + error);
+ } catch (SyntaxErrorException) {
}
try {
table2.Columns.Add ("result", typeof (int), "(child.test) LIKE 1");
- Fail ("#5" + error);
- }catch (SyntaxErrorException) {
+ Assert.Fail ("#5" + error);
+ } catch (SyntaxErrorException) {
}
try {
table2.Columns.Add ("result", typeof (int), "(child.test) IS null");
- Fail ("#6" + error);
- }catch (SyntaxErrorException) {
+ Assert.Fail ("#6" + error);
+ } catch (SyntaxErrorException) {
}
// Check Calc Functions
try {
table2.Columns.Add ("result", typeof (int), "isnull(child.test,10)");
- Fail ("#7" + error);
- }catch (SyntaxErrorException) {
+ Assert.Fail ("#7" + error);
+ } catch (SyntaxErrorException) {
}
}
table.Rows.Add (new object[] {});
// ms.net behavior.. seems to covert all numbers to double
- AssertEquals ("#1", 1, table.Rows[0][0]);
- AssertEquals ("#2", 1, table.Rows[0][1]);
+ Assert.AreEqual (1, table.Rows [0] [0], "#1");
+ Assert.AreEqual (1, table.Rows [0] [1], "#2");
}
[Test]
DataColumn col1 = new DataColumn ("col1", typeof (int));
DataColumn col2 = new DataColumn ("col2", typeof (int));
- AssertEquals ("#1" , -1, col1.Ordinal);
- AssertEquals ("#2" , null, col1.Table);
+ Assert.AreEqual (-1, col1.Ordinal, "#A1");
+ Assert.IsNull (col1.Table, "#A2");
table.Columns.Add (col1);
table.Columns.Add (col2);
- AssertEquals ("#3" , 0, col1.Ordinal);
- AssertEquals ("#4" , table, col1.Table);
+ Assert.AreEqual (0, col1.Ordinal, "#B1");
+ Assert.AreEqual (table, col1.Table, "#B2");
table.Columns.RemoveAt(0);
- AssertEquals ("#5" , -1, col1.Ordinal);
- AssertEquals ("#6" , null, col1.Table);
+ Assert.AreEqual (-1, col1.Ordinal, "#C1");
+ Assert.IsNull (col1.Table, "#C2");
table.Columns.Clear ();
- AssertEquals ("#7" , -1, col2.Ordinal);
- AssertEquals ("#8" , null, col2.Table);
+ Assert.AreEqual (-1, col2.Ordinal, "#D1");
+ Assert.IsNull (col2.Table, "#D2");
}
}
}
+2007-10-22 Andreia Gaita <avidigal@novell.com>
+
+ * SD2K5.csproj: Add 2k5 project
+
+2007-10-17 Sebastien Pouliot <sebastien@ximian.com>
+
+ * nunit-host-ignore-list: Change host name for DISTRO names.
+
2007-08-01 Sebastien Pouliot <sebastien@ximian.com>
* nunit-host-ignore-list: Update bots name changes.
--- /dev/null
+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
+ <PropertyGroup>\r
+ <ProjectType>Local</ProjectType>\r
+ <ProductVersion>8.0.50727</ProductVersion>\r
+ <SchemaVersion>2.0</SchemaVersion>\r
+ <ProjectGuid>{A6337986-B345-4C49-95F4-40D498C1927B}</ProjectGuid>\r
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
+ <ApplicationIcon>\r
+ </ApplicationIcon>\r
+ <AssemblyKeyContainerName>\r
+ </AssemblyKeyContainerName>\r
+ <AssemblyName>System.Drawing</AssemblyName>\r
+ <AssemblyOriginatorKeyFile>\r
+ </AssemblyOriginatorKeyFile>\r
+ <DefaultClientScript>JScript</DefaultClientScript>\r
+ <DefaultHTMLPageLayout>Grid</DefaultHTMLPageLayout>\r
+ <DefaultTargetSchema>IE50</DefaultTargetSchema>\r
+ <DelaySign>false</DelaySign>\r
+ <OutputType>Library</OutputType>\r
+ <RootNamespace>\r
+ </RootNamespace>\r
+ <RunPostBuildEvent>OnBuildSuccess</RunPostBuildEvent>\r
+ <StartupObject>\r
+ </StartupObject>\r
+ <FileUpgradeFlags>\r
+ </FileUpgradeFlags>\r
+ <UpgradeBackupLocation>\r
+ </UpgradeBackupLocation>\r
+ </PropertyGroup>\r
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
+ <OutputPath>bin\Debug_2.0\</OutputPath>\r
+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\r
+ <BaseAddress>285212672</BaseAddress>\r
+ <CheckForOverflowUnderflow>false</CheckForOverflowUnderflow>\r
+ <ConfigurationOverrideFile>\r
+ </ConfigurationOverrideFile>\r
+ <DefineConstants>NET_1_1 NET_2_0 VSTUDIO</DefineConstants>\r
+ <DocumentationFile>\r
+ </DocumentationFile>\r
+ <DebugSymbols>true</DebugSymbols>\r
+ <FileAlignment>4096</FileAlignment>\r
+ <NoStdLib>false</NoStdLib>\r
+ <NoWarn>\r
+ </NoWarn>\r
+ <Optimize>false</Optimize>\r
+ <RegisterForComInterop>false</RegisterForComInterop>\r
+ <RemoveIntegerChecks>false</RemoveIntegerChecks>\r
+ <TreatWarningsAsErrors>false</TreatWarningsAsErrors>\r
+ <WarningLevel>1</WarningLevel>\r
+ <DebugType>full</DebugType>\r
+ <ErrorReport>prompt</ErrorReport>\r
+ <UseVSHostingProcess>false</UseVSHostingProcess>\r
+ </PropertyGroup>\r
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
+ <OutputPath>bin\Release\</OutputPath>\r
+ <AllowUnsafeBlocks>false</AllowUnsafeBlocks>\r
+ <BaseAddress>285212672</BaseAddress>\r
+ <CheckForOverflowUnderflow>false</CheckForOverflowUnderflow>\r
+ <ConfigurationOverrideFile>\r
+ </ConfigurationOverrideFile>\r
+ <DefineConstants>\r
+ </DefineConstants>\r
+ <DocumentationFile>\r
+ </DocumentationFile>\r
+ <DebugSymbols>false</DebugSymbols>\r
+ <FileAlignment>4096</FileAlignment>\r
+ <NoStdLib>false</NoStdLib>\r
+ <NoWarn>\r
+ </NoWarn>\r
+ <Optimize>true</Optimize>\r
+ <RegisterForComInterop>false</RegisterForComInterop>\r
+ <RemoveIntegerChecks>false</RemoveIntegerChecks>\r
+ <TreatWarningsAsErrors>false</TreatWarningsAsErrors>\r
+ <WarningLevel>1</WarningLevel>\r
+ <DebugType>none</DebugType>\r
+ <ErrorReport>prompt</ErrorReport>\r
+ </PropertyGroup>\r
+ <ItemGroup>\r
+ <Compile Include="..\..\build\common\Consts.cs">\r
+ <Link>Consts.cs</Link>\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="..\..\build\common\Locale.cs">\r
+ <Link>Locale.cs</Link>\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="..\..\build\common\MonoTODOAttribute.cs">\r
+ <Link>MonoTODOAttribute.cs</Link>\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\CategoryNameCollection.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\IPropertyValueUIService.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\IToolboxItemProvider.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\IToolboxService.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\IToolboxUser.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\PaintValueEventArgs.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\PropertyValueItem.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\PropertyValueUIHandler.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\PropertyValueUIItemInvokeHandler.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\ToolboxComponentsCreatedEventArgs.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\ToolboxComponentsCreatedEventHandler.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\ToolboxComponentsCreatingEventArgs.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\ToolboxComponentsCreatingEventHandler.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\ToolboxItem.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\ToolboxItemCollection.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\ToolboxItemCreatorCallback.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\UITypeEditor.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Design\UITypeEditorEditStyle.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\AdjustableArrowCap.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\Blend.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\ColorBlend.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\CombineMode.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\CompostingMode.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\CompostingQuality.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\CoordinateSpace.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\CustomLineCap.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\DashCap.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\DashStyle.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\FillMode.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\FlushIntention.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\GraphicsContainer.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\GraphicsPath.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\GraphicsPathIterator.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\GraphicsState.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\HatchBrush.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\HatchStyle.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\InterpolationMode.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\LinearGradientBrush.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\LinearGradientMode.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\LineCap.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\LineJoin.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\Matrix.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\MatrixOrder.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\PathData.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\PathGradientBrush.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\PathPointType.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\PenAlignment.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\PenType.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\PixelOffsetMode.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\QualityMode.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\RegionData.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\SmoothingMode.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\WarpMode.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Drawing2D\WrapMode.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\BitmapData.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\ColorAdjustType.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\ColorChannelFlag.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\ColorMap.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\ColorMapType.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\ColorMatrix.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\ColorMatrixFlag.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\ColorMode.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\ColorPalette.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\EmfPlusRecordType.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\EmfType.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\Encoder.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\EncoderParameter.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\EncoderParameters.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\EncoderParameterValueType.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\EncoderValue.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\FrameDimension.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\ImageAttributes.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\ImageCodecFlags.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\ImageCodecInfo.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\ImageFlags.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\ImageFormat.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\ImageLockMode.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\Metafile.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\MetafileFrameUnit.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\MetafileHeader.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\MetafileType.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\MetaHeader.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\PaletteFlags.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\PixelFormat.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\PlayRecordCallback.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\PropertyItem.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Imaging\WmfPlaceableFileHeader.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\Duplex.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\InvalidPrinterException.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\Margins.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\MarginsConverter.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PageSettings.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PaperKind.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PaperSize.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PaperSource.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PaperSourceKind.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PreviewPageInfo.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PreviewPrintController.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrintAction.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrintController.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrintDocument.cs">\r
+ <SubType>Component</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrinterResolution.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrinterResolutionKind.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrinterSettings.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrinterUnit.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrinterUnitConvert.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrintEventArgs.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrintEventHandler.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrintingPermission.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrintingPermissionAttribute.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrintingPermissionLevel.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrintingServices.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrintingServicesUnix.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrintingServicesWin32.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrintPageEventArgs.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrintPageEventHandler.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\PrintRange.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\QueryPageSettingsEventArgs.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\QueryPageSettingsEventHandler.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Printing\StandardPrintController.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Text\FontCollection.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Text\GenericFontFamilies.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Text\HotkeyPrefix.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Text\InstalledFontCollection.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Text\PrivateFontCollection.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing.Text\TextRenderingHint.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\Bitmap.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\Brush.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\Brushes.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\BufferedGraphics.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\BufferedGraphicsContext.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\BufferedGraphicsManager.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\carbonFunctions.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\CharacterRange.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\Color.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\ColorConverter.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\ColorTranslator.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\ComIStreamMarshaler.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\ComIStreamWrapper.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\ContentAlignment.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\CopyPixelOperation.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\Font.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\FontConverter.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\FontFamily.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\FontStyle.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\gdipEnums.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\gdipFunctions.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\gdipStructs.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\Graphics.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\GraphicsUnit.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\Icon.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\IconConverter.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\IDeviceContext.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\Image.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\ImageAnimator.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\ImageConverter.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\ImageFormatConverter.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\KnownColor.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\KnownColors.cs" />\r
+ <Compile Include="System.Drawing\Pen.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\Pens.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\Point.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\PointConverter.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\PointF.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\Rectangle.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\RectangleConverter.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\RectangleF.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\Region.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\RotateFlipType.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\Size.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\SizeConverter.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\SizeF.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\SizeFConverter.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\SolidBrush.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\SRDescriptionAttribute.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\StringAligment.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\StringDigitSubstitute.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\StringFormat.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\StringFormatFlags.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\StringTrimming.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\StringUnit.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\SystemBrushes.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\SystemColors.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\SystemFonts.cs" />\r
+ <Compile Include="System.Drawing\SystemIcons.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\SystemPens.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\TextureBrush.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <Compile Include="System.Drawing\ToolboxBitmapAttribute.cs">\r
+ <SubType>Code</SubType>\r
+ </Compile>\r
+ <None Include="System.Drawing.Printing\ChangeLog" />\r
+ <None Include="System.Drawing\ChangeLog" />\r
+ </ItemGroup>\r
+ <ItemGroup>\r
+ <Reference Include="System" />\r
+ </ItemGroup>\r
+ <ItemGroup>\r
+ <EmbeddedResource Include="Assembly\Application.ico" />\r
+ <EmbeddedResource Include="Assembly\Asterisk.ico" />\r
+ <EmbeddedResource Include="Assembly\Error.ico" />\r
+ <EmbeddedResource Include="Assembly\Exclamation.ico" />\r
+ <EmbeddedResource Include="Assembly\Hand.ico" />\r
+ <EmbeddedResource Include="Assembly\Information.ico" />\r
+ <EmbeddedResource Include="Assembly\Mono.ico" />\r
+ <EmbeddedResource Include="Assembly\Question.ico" />\r
+ <EmbeddedResource Include="Assembly\Warning.ico" />\r
+ <EmbeddedResource Include="Assembly\WinLogo.ico" />\r
+ </ItemGroup>\r
+ <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
+ <PropertyGroup>\r
+ <PreBuildEvent>\r
+ </PreBuildEvent>\r
+ <PostBuildEvent>\r
+ </PostBuildEvent>\r
+ </PropertyGroup>\r
+</Project>
\ No newline at end of file
+2007-10-17 Geoff Norton <gnorton@novell.com>
+
+ * Graphics.cs: Only synchronize the display on Flush when we actually have
+ a CGContext
+
+2007-10-17 Geoff Norton <gnorton@novell.com>
+
+ * carbonFunctions.cs: Initial support for clipping children out of the
+ CGContext before drawing on it.
+
2007-10-09 Geoff Norton <gnorton@novell.com>
* carbonFunctions.cs: Correct the P/Invoke definition for CGContext*CTM.
Status status = GDIPlus.GdipFlush (nativeObject, intention);
GDIPlus.CheckStatus (status);
- if (GDIPlus.UseQuartzDrawable || GDIPlus.UseCocoaDrawable)
+ if ((GDIPlus.UseQuartzDrawable || GDIPlus.UseCocoaDrawable) && GDIPlus.Display != IntPtr.Zero)
Carbon.CGContextSynchronize (GDIPlus.Display);
}
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
+#define EnableClipping
+#undef EnableNCClipping
+#undef DebugClipping
+#undef DebugDrawing
+
+using System.Collections;
+using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
[SuppressUnmanagedCodeSecurity]
internal class Carbon {
+#if EnableClipping
+ internal static Type hwnd_type;
+ internal static FieldInfo hwnd_children_field;
+ internal static FieldInfo hwnd_client_rectangle_field;
+ internal static FieldInfo hwnd_x_field;
+ internal static FieldInfo hwnd_y_field;
+ internal static FieldInfo hwnd_width_field;
+ internal static FieldInfo hwnd_height_field;
+ internal static FieldInfo hwnd_whole_window_field;
+ internal static FieldInfo hwnd_client_window_field;
+ internal static MethodInfo get_hwnd;
+
+ static Carbon () {
+ foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies ()) {
+ if (String.Equals (asm.GetName ().Name, "System.Windows.Forms")) {
+ hwnd_type = asm.GetType ("System.Windows.Forms.Hwnd");
+ if (hwnd_type != null) {
+ get_hwnd = hwnd_type.GetMethod ("ObjectFromHandle");
+ hwnd_children_field = hwnd_type.GetField ("children", BindingFlags.NonPublic | BindingFlags.Instance);
+ hwnd_client_rectangle_field = hwnd_type.GetField ("client_rectangle", BindingFlags.NonPublic | BindingFlags.Instance);
+ hwnd_x_field = hwnd_type.GetField ("x", BindingFlags.NonPublic | BindingFlags.Instance);
+ hwnd_y_field = hwnd_type.GetField ("y", BindingFlags.NonPublic | BindingFlags.Instance);
+ hwnd_width_field = hwnd_type.GetField ("width", BindingFlags.NonPublic | BindingFlags.Instance);
+ hwnd_height_field = hwnd_type.GetField ("height", BindingFlags.NonPublic | BindingFlags.Instance);
+ hwnd_whole_window_field = hwnd_type.GetField ("whole_window", BindingFlags.NonPublic | BindingFlags.Instance);
+ hwnd_client_window_field = hwnd_type.GetField ("client", BindingFlags.NonPublic | BindingFlags.Instance);
+ }
+ }
+ }
+ }
+#endif
internal static CarbonContext GetCGContextForNSView (IntPtr hwnd) {
IntPtr cgContext = IntPtr.Zero;
objc_msgSend_stret (ref rect, hwnd, sel_registerName ("bounds"));
return new CarbonContext (cgContext, (int)rect.size.width, (int)rect.size.height);
}
+
internal static CarbonContext GetCGContextForView (IntPtr hwnd) {
IntPtr cgContext = IntPtr.Zero;
// Grab the window we're in
IntPtr port = Carbon.GetWindowPort (window);
// Create a CGContext ref
Carbon.CreateCGContextForPort (port, ref cgContext);
-
+
// Get the bounds of the window
QRect wBounds = new QRect ();
Carbon.GetWindowBounds (window, 32, ref wBounds);
// Convert the view local bounds to window coordinates
Carbon.HIViewConvertRect (ref vBounds, hwnd, IntPtr.Zero);
Carbon.CGContextTranslateCTM (cgContext, vBounds.origin.x, (wBounds.bottom-wBounds.top)-(vBounds.origin.y+vBounds.size.height));
- /* FIXME: Do we need this or is it inherintly clipped */
- HIRect rcClip = new HIRect ();
- rcClip.origin.x = 0;
- rcClip.origin.y = 0;
- rcClip.size.width = vBounds.size.width;
- rcClip.size.height = vBounds.size.height;
- Carbon.CGContextClipToRect (cgContext, rcClip);
+
+#if EnableClipping
+ if (get_hwnd != null) {
+ // Create the original rect path and clip to it
+ IntPtr clip_path = CGPathCreateMutable ();
+ HIRect rc_clip = new HIRect (0, 0, vBounds.size.width, vBounds.size.height);
+#if DebugClipping
+ Console.WriteLine ("--CLIP: {0}x{1}", vBounds.size.width, vBounds.size.height);
+#endif
+ CGPathAddRect (clip_path, IntPtr.Zero, rc_clip);
+ CGContextBeginPath (cgContext);
+ object hwnd_object = get_hwnd.Invoke (null, new object [] {hwnd});
+ IntPtr whole_window = (IntPtr) hwnd_whole_window_field.GetValue (hwnd_object);
+
+ if (hwnd == whole_window) {
+#if EnableNCClipping
+#if DebugClipping
+ Console.WriteLine ("\tNCCLIP:");
+#endif
+ HIRect clip_rect = new HIRect ();
+ Rectangle client_rect = (Rectangle) hwnd_client_rectangle_field.GetValue (hwnd_object);
+ clip_rect.origin.x = (int) client_rect.X;
+ clip_rect.origin.y = (int) client_rect.Y;
+ clip_rect.size.width = (int) client_rect.Width;
+ clip_rect.size.height = (int) client_rect.Height;
+#if DebugClipping
+ Console.WriteLine ("\txor: {0}x{1} @ {2}x{3}", clip_rect.size.width, clip_rect.size.height, clip_rect.origin.x, clip_rect.origin.y);
+#endif
+ CGPathAddRect (clip_path, IntPtr.Zero, clip_rect);
+ CGContextAddPath (cgContext, clip_path);
+ CGContextEOClip (cgContext);
+#if DebugClipping
+ Console.WriteLine ("\tEOClip client_window");
+#endif
+#endif
+ } else {
+ ArrayList hwnd_children = (ArrayList) hwnd_children_field.GetValue (hwnd_object);
+ int count = hwnd_children.Count;
+ if (count > 0) {
+#if DebugClipping
+ Console.WriteLine ("\tCLIP:");
+#endif
+ HIRect [] clip_rects = new HIRect [count];
+ for (int i = 0; i < count; i++) {
+ clip_rects [i] = new HIRect ();
+ clip_rects [i].origin.x = (int) hwnd_x_field.GetValue (hwnd_children [i]);
+ clip_rects [i].origin.y = vBounds.size.height - (int) hwnd_y_field.GetValue (hwnd_children [i]) - (int) hwnd_height_field.GetValue (hwnd_children [i]);
+ clip_rects [i].size.width = (int) hwnd_width_field.GetValue (hwnd_children [i]);
+ clip_rects [i].size.height = (int) hwnd_height_field.GetValue (hwnd_children [i]);
+#if DebugClipping
+ Console.WriteLine ("\txor: {0}x{1} @ {2}x{3}", clip_rects [i].size.width, clip_rects [i].size.height, clip_rects [i].origin.x, clip_rects [i].origin.y);
+#endif
+ }
+ CGPathAddRects (clip_path, IntPtr.Zero, clip_rects, count);
+ CGContextAddPath (cgContext, clip_path);
+ CGContextEOClip (cgContext);
+#if DebugClipping
+ Console.WriteLine ("\tEOClip");
+#endif
+ } else {
+#if DebugClipping
+ Console.WriteLine ("\tClip");
+#endif
+ CGContextAddPath (cgContext, clip_path);
+ CGContextClip (cgContext);
+ }
+ }
+#if DebugClipping
+ Console.WriteLine ("--ENDCLIP:");
+#endif
+ }
+#endif
+
+#if DebugDrawing
+ Console.WriteLine ("--DRAW:");
+ Console.WriteLine ("\t{0:X}: {1}x{2}", hwnd, (int)vBounds.size.width, (int)vBounds.size.height);
+#endif
return new CarbonContext (cgContext, (int)vBounds.size.width, (int)vBounds.size.height);
}
#region Cocoa Methods
#endregion
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- internal static extern int HIViewGetBounds (IntPtr vHnd, ref HIRect r);
- [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- internal static extern int HIViewConvertRect (ref HIRect r, IntPtr a, IntPtr b);
-
- [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- internal static extern IntPtr GetControlOwner (IntPtr aView);
-
- [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- internal static extern int GetWindowBounds (IntPtr wHnd, uint reg, ref QRect rect);
- [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- internal static extern IntPtr GetWindowPort (IntPtr hWnd);
- [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- internal static extern int CGContextClipToRect (IntPtr cgContext, HIRect clip);
- [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- internal static extern void CreateCGContextForPort (IntPtr port, ref IntPtr cgc);
- [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- internal static extern void CGContextTranslateCTM (IntPtr cgc, float tx, float ty);
- [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- internal static extern void CGContextScaleCTM (IntPtr cgc, float x, float y);
- [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- internal static extern void CGContextFlush (IntPtr cgc);
- [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
- internal static extern void CGContextSynchronize (IntPtr cgc);
+ internal static extern int HIViewGetBounds (IntPtr vHnd, ref HIRect r);
+ [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern int HIViewConvertRect (ref HIRect r, IntPtr a, IntPtr b);
+
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern IntPtr GetControlOwner (IntPtr aView);
+
+ [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern int GetWindowBounds (IntPtr wHnd, uint reg, ref QRect rect);
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern IntPtr GetWindowPort (IntPtr hWnd);
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern int CGContextClipToRect (IntPtr cgContext, HIRect clip);
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern int CGContextClipToRects (IntPtr cgContext, HIRect [] clip_rects, int count);
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern void CreateCGContextForPort (IntPtr port, ref IntPtr cgc);
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern void CGContextTranslateCTM (IntPtr cgc, float tx, float ty);
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern void CGContextScaleCTM (IntPtr cgc, float x, float y);
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern void CGContextFlush (IntPtr cgc);
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern void CGContextSynchronize (IntPtr cgc);
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern IntPtr CGPathCreateMutable ();
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern void CGPathAddRects (IntPtr path, IntPtr _void, HIRect [] rects, int count);
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern void CGPathAddRect (IntPtr path, IntPtr _void, HIRect rect);
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern void CGContextBeginPath (IntPtr cgc);
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern void CGContextAddPath (IntPtr cgc, IntPtr path);
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern void CGContextClip (IntPtr cgc);
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern void CGContextEOClip (IntPtr cgc);
+ [DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
+ internal static extern void CGContextEOFillPath (IntPtr cgc);
}
internal struct CGSize {
}
internal struct HIRect {
+ public HIRect (float x, float y, float width, float height) {
+ this.origin.x = x;
+ this.origin.y = y;
+ this.size.width = width;
+ this.size.height = height;
+ }
+
public CGPoint origin;
public CGSize size;
}
+2007-10-17 Sebastien Pouliot <sebastien@ximian.com>
+
+ * HostIgnoreList.cs: Now use the DISTRO variable to track tests to
+ ignore.
+
2007-01-07 Sebastien Pouliot <sebastien@ximian.com>
* HostIgnoreList.cs: New class to ignore some tests on specific hosts.
namespace MonoTests {
+ // now misnamed - we check for the DISTRO env variable
public class HostIgnoreList {
private const string IgnoreListName = "nunit-host-ignore-list";
static HostIgnoreList ()
{
+ string hostname = Environment.GetEnvironmentVariable ("DISTRO");
+ if (hostname == null)
+ return;
+
if (File.Exists (IgnoreListName)) {
- string hostname = Environment.MachineName;
using (StreamReader sr = new StreamReader (IgnoreListName)) {
string line = sr.ReadLine ();
while (line != null) {
return;
if (IgnoreList.Contains (testname)) {
- string msg = String.Format ("Test '{0}' was ignore because it's defined in the '{1}' ignore list.",
+ string msg = String.Format ("Test '{0}' was ignored because it's defined in the '{1}' ignore list.",
testname, IgnoreListName);
Assert.Ignore (msg);
}
# some older distro have (old) libraries which expose some drawing bugs
# but we do not want to ignore the test on all platforms because of this
# note: please avoid using this mechanism as much as possible
-monobuild2,MonoTests.System.Drawing.GraphicsTest.MeasureString_StringFontInt_LongString
-monobuild2,MonoTests.System.Drawing.GraphicsTest.MeasureString_Wrapping_Dots
-mono-linux-sparc,MonoTests.System.Drawing.GraphicsTest.MeasureString_StringFontInt_LongString
-mono-linux-sparc,MonoTests.System.Drawing.GraphicsTest.MeasureString_Wrapping_Dots
-despinasp,MonoTests.System.Drawing.GraphicsTest.MeasureString_StringFontInt_LongString
-despinasp,MonoTests.System.Drawing.GraphicsTest.MeasureString_Wrapping_Dots
-mono-arm,MonoTests.System.Drawing.GraphicsTest.MeasureString_StringFontInt_LongString
-mono-arm,MonoTests.System.Drawing.GraphicsTest.MeasureString_Wrapping_Dots
-hardhat.boston.ximian.com,MonoTests.System.Drawing.GraphicsTest.MeasureString_StringFontInt_LongString
-hardhat.boston.ximian.com,MonoTests.System.Drawing.GraphicsTest.MeasureString_Wrapping_Dots
-itanium,MonoTests.System.Drawing.GraphicsTest.MeasureString_StringFontInt_LongString
-itanium,MonoTests.System.Drawing.GraphicsTest.MeasureString_Wrapping_Dots
+sles-9-i586,MonoTests.System.Drawing.GraphicsTest.MeasureString_StringFontInt_LongString
+sles-9-i586,MonoTests.System.Drawing.GraphicsTest.MeasureString_Wrapping_Dots
+sles-9-x86_64,MonoTests.System.Drawing.GraphicsTest.MeasureString_StringFontInt_LongString
+sles-9-x86_64,MonoTests.System.Drawing.GraphicsTest.MeasureString_Wrapping_Dots
+sles-9-ia64,MonoTests.System.Drawing.GraphicsTest.MeasureString_StringFontInt_LongString
+sles-9-ia64,MonoTests.System.Drawing.GraphicsTest.MeasureString_Wrapping_Dots
+sles-9-s390,MonoTests.System.Drawing.GraphicsTest.MeasureString_StringFontInt_LongString
+sles-9-s390,MonoTests.System.Drawing.GraphicsTest.MeasureString_Wrapping_Dots
+sunos-8-sparc,MonoTests.System.Drawing.GraphicsTest.MeasureString_StringFontInt_LongString
+sunos-8-sparc,MonoTests.System.Drawing.GraphicsTest.MeasureString_Wrapping_Dots
+debian-4-arm,MonoTests.System.Drawing.GraphicsTest.MeasureString_StringFontInt_LongString
+debian-4-arm,MonoTests.System.Drawing.GraphicsTest.MeasureString_Wrapping_Dots
+
return c.ConvertFrom (obj);
}
+ /*
+ * Take care of the special case whereas in JSON an empty string ("") really means
+ * an empty value
+ * (see: https://bugzilla.novell.com/show_bug.cgi?id=328836)
+ */
+ if ( (type.IsGenericType) && (type.GetGenericTypeDefinition() == typeof(Nullable<>)) )
+ {
+ string s = obj as String;
+ if (String.IsNullOrEmpty(s))
+ return null;
+ }
+
return Convert.ChangeType (obj, type);
}
get {
if (IsDeploymentRetail)
return false;
-#if !TARGET_J2EE
+
CompilationSection compilation = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
if (!compilation.Debug && (ScriptMode == ScriptMode.Auto || ScriptMode == ScriptMode.Inherit))
return false;
-#endif
+
if (ScriptMode == ScriptMode.Release)
return false;
throw new InvalidOperationException ();
if (!EnablePartialRendering && value)
throw new InvalidOperationException ("The SupportsPartialRendering property cannot be set when EnablePartialRendering is false.");
+#if TARGET_J2EE
+ if (!ServerSoftwareSupportsPartialRendering && value)
+ throw new InvalidOperationException ("The server software does not supports partial rendering.");
+#endif
_supportsPartialRendering = value;
}
bool CheckSupportsPartialRendering () {
if (!EnablePartialRendering)
return false;
+#if TARGET_J2EE
+ if (!ServerSoftwareSupportsPartialRendering)
+ return false;
+#endif
// TODO: consider browser capabilities
return true;
}
+#if TARGET_J2EE
+ bool? _serverSoftwareSupportsPartialRendering;
+
+ bool ServerSoftwareSupportsPartialRendering {
+ get {
+ if (!_serverSoftwareSupportsPartialRendering.HasValue)
+ _serverSoftwareSupportsPartialRendering = CheckServerSoftwareSupportsPartialRendering ();
+ return _serverSoftwareSupportsPartialRendering.Value;
+ }
+ }
+
+ bool CheckServerSoftwareSupportsPartialRendering () {
+ string serverSoftware = Context.Request.ServerVariables ["SERVER_SOFTWARE"];
+ if (!String.IsNullOrEmpty (serverSoftware)) {
+
+ if (serverSoftware.IndexOf ("WebSphere", StringComparison.OrdinalIgnoreCase) >= 0)
+ return false;
+
+ if (serverSoftware.IndexOf ("Jetspeed", StringComparison.OrdinalIgnoreCase) >= 0)
+ return false;
+ }
+ return true;
+ }
+#endif
+
[EditorBrowsable (EditorBrowsableState.Never)]
[Browsable (false)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
sealed class HtmlTextParser : AlternativeHtmlTextWriter
{
+ bool _done;
+
public HtmlTextParser (HtmlTextWriter responseOutput)
: base (new TextParser (responseOutput), responseOutput) {
}
+
+ public override void WriteAttribute (string name, string value) {
+ if (!_done && String.Compare ("action", name, StringComparison.OrdinalIgnoreCase) == 0) {
+ _done = true;
+ ScriptManager.WriteCallbackOutput (ResponseOutput, formAction, null, value);
+ return;
+ }
+ base.WriteAttribute (name, value);
+ }
}
sealed class TextParser : TextWriter
+2007-10-17 Atsushi Enomoto <atsushi@ximian.com>
+
+ * WebServicesSection.cs : r87621 has changed WebConfigurationManager
+ to not read web.config, which caused couple of configuration
+ regressions. So enable ConfigurationManager again.
+
2007-10-04 Atsushi Enomoto <atsushi@ximian.com>
* WebServicesSection.cs : reverted r83640 which likely caused
}
public static WebServicesSection Current {
- get { return (WebServicesSection) WebConfigurationManager.GetSection ("system.web/webServices"); }
+ get { return (WebServicesSection) ConfigurationManager.GetSection ("system.web/webServices"); }
}
internal static bool IsSupported (WebServiceProtocols proto)
if (results.NativeCompilerReturnValue == 0) {
ret = results.CompiledAssembly;
- BuildManager.TopLevelAssemblies.Add (ret);
- if (defaultAssembly)
+ if (defaultAssembly) {
+ BuildManager.TopLevelAssemblies.Add (ret);
mainAssembly = ret;
+ }
} else {
if (HttpContext.Current.IsCustomErrorEnabled)
throw new ApplicationException ("An error occurred while compiling global resources.");
throw new CompilationException (null, results.Errors, null);
}
- HttpRuntime.WritePreservationFile (ret, canonicAssemblyName);
- HttpRuntime.EnableAssemblyMapping (true);
+
+ if (defaultAssembly) {
+ HttpRuntime.WritePreservationFile (ret, canonicAssemblyName);
+ HttpRuntime.EnableAssemblyMapping (true);
+ }
}
string BuildAssemblyPath (string cultureName, AssemblyBuilder abuilder)
// configuration section, though.
}
else {
- Type t = Type.GetType (comp.Type, true);
+ Type t = HttpApplication.LoadType (comp.Type, true);
provider = Activator.CreateInstance (t) as CodeDomProvider;
compilerOptions = comp.CompilerOptions;
Compiler compiler = config.Compilers.Get (language);
CompilerParameters p;
if (compiler != null) {
- Type type = Type.GetType (compiler.Type, true);
+ Type type = HttpApplication.LoadType (compiler.Type, true);
p = new CompilerParameters ();
p.CompilerOptions = compiler.CompilerOptions;
p.WarningLevel = compiler.WarningLevel;
#if NET_2_0
CompilationSection config = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
Compiler c = config.Compilers[language];
- Type t = Type.GetType (c.Type, true);
+ Type t = HttpApplication.LoadType (c.Type, true);
CodeDomProvider provider = Activator.CreateInstance (t) as CodeDomProvider;
#else
CompilationConfiguration config;
+2007-10-23 Marek Habersack <mhabersack@novell.com>
+
+ * AppResourcesAssemblyBuilder.cs: do not output preservation files
+ for satellite assemblies, just for the main assembly. Also, don't
+ add the satellite assemblies to the list of top-level assemblies.
+
+2007-10-17 Marek Habersack <mhabersack@novell.com>
+
+ * PageCompiler.cs: added code to set the AsyncMode and
+ AsyncTimeout Page properties.
+
+2007-10-15 Marek Habersack <mhabersack@novell.com>
+
+ * TemplateControlCompiler.cs, WebServiceCompiler.cs,
+ BuildProvider.cs, BaseCompiler.cs, CachingCompiler.cs: use
+ HttpApplication.LoadType instead of Type.GetType.
+
2007-10-10 Marek Habersack <mhabersack@novell.com>
* TemplateControlCompiler.cs: be careful when using type
if (pageParser.StyleSheetTheme != null)
method.Statements.Add (CreatePropertyAssign (ctrlVar, "StyleSheetTheme", pageParser.StyleSheetTheme));
+
+ if (pageParser.Async != false)
+ method.Statements.Add (CreatePropertyAssign (ctrlVar, "AsyncMode", pageParser.Async));
+
+ if (pageParser.AsyncTimeout != -1)
+ method.Statements.Add (CreatePropertyAssign (ctrlVar, "AsyncTimeout",
+ TimeSpan.FromSeconds (pageParser.AsyncTimeout)));
#endif
}
Type t;
try {
- t = System.Type.GetType (builderType, true);
+ t = HttpApplication.LoadType (builderType, true);
} catch (Exception e) {
throw new HttpException (
String.Format ("Failed to load expression builder type `{0}'", builderType), e);
Type t = null;
try {
- t = Type.GetType (typeName);
+ t = HttpApplication.LoadType (typeName);
} catch (Exception) {
// ignore
}
#if NET_2_0
CompilationSection config = (CompilationSection)WebConfigurationManager.GetSection ("system.web/compilation");
Compiler c = config.Compilers[lang];
- Type t = Type.GetType (c.Type, true);
+ Type t = HttpApplication.LoadType (c.Type, true);
provider = Activator.CreateInstance (t) as CodeDomProvider;
#else
CompilationConfiguration config;
+2007-10-15 Marek Habersack <mhabersack@novell.com>
+
+ * ModulesConfiguration.cs: load modules using
+ HttpApplication.LoadType to include the bin/ directory in search.
+
2007-08-30 Marek Habersack <mhabersack@novell.com>
* MachineKeyRegistryStorage.cs: added
Type item_type;
try {
- item_type = Type.GetType (type, true);
+ item_type = HttpApplication.LoadType (type, true);
} catch (Exception e){
throw new HttpException (
String.Format ("Failed to load module `{0}' from type `{1}'", name, type), e);
public HttpModuleCollection LoadModules (HttpApplication app)
{
HttpModuleCollection coll = new HttpModuleCollection ();
- foreach (ModuleItem item in Modules){
+ foreach (ModuleItem item in Modules) {
IHttpModule module = (IHttpModule) Activator.CreateInstance (item.Type, true);
module.Init (app);
coll.AddModule (item.Name, module);
+2007-10-17 Marek Habersack <mhabersack@novell.com>
+
+ * WebConfigurationHost.cs: if running outside hosted environment,
+ read only the assemblyname.config configuration file instead of
+ web.config. Fixes bug #332425
+
+2007-10-15 Marek Habersack <mhabersack@novell.com>
+
+ * ProvidersHelper.cs: use HttpApplication.LoadType instead of
+ Type.GetType.
+
+ * HttpModulesSection.cs: use HttpApplication.LoadType when loading
+ modules, to include both the bin/ directory and the top-level
+ assemblies in search. Fixes bug #333686.
+
2007-08-30 Marek Habersack <mhabersack@novell.com>
* MachineKeySection.cs: retrieve the keys from the registry before
internal HttpModuleCollection LoadModules (HttpApplication app)
{
HttpModuleCollection coll = new HttpModuleCollection ();
+ Type type;
+
foreach (HttpModuleAction item in Modules){
- Type type = Type.GetType (item.Type);
+ type = HttpApplication.LoadType (item.Type);
+
if (type == null) {
/* XXX should we throw here? */
continue;
{
public static ProviderBase InstantiateProvider (ProviderSettings providerSettings, Type providerType)
{
- Type settingsType = Type.GetType (providerSettings.Type);
+ Type settingsType = HttpApplication.LoadType (providerSettings.Type);
if (settingsType == null)
settingsType = HttpApplication.LoadTypeFromBin (providerSettings.Type);
using System.Security;
using System.Configuration;
using System.Configuration.Internal;
+using System.Web.Hosting;
using System.Web.Util;
using System.Reflection;
if (file != null)
return file.FullName;
#else
- string[] filenames = new string[] {"Web.Config", "Web.config", "web.config" };
+ AppDomain domain = AppDomain.CurrentDomain;
+ bool hosted = (domain.GetData (ApplicationHost.MonoHostedDataKey) as string) == "yes";
- foreach (string fn in filenames) {
- string file = Path.Combine (dir, fn);
- if (File.Exists (file))
- return file;
+ if (hosted) {
+ foreach (string fn in ApplicationHost.WebConfigFileNames) {
+ string file = Path.Combine (dir, fn);
+ if (File.Exists (file))
+ return file;
+ }
+ } else {
+ Assembly asm = Assembly.GetEntryAssembly () ?? Assembly.GetCallingAssembly ();
+ string name = Path.GetFileName (asm.Location);
+ string[] fileNames = new string[] {name + ".config", name + ".Config"};
+ string appDir = domain.BaseDirectory;
+ string file;
+
+ foreach (string fn in fileNames) {
+ file = Path.Combine (appDir, fn);
+ if (File.Exists (file))
+ return file;
+ }
}
-#endif
+#endif
return null;
}
#if TARGET_J2EE
// CAS - no InheritanceDemand here as the class is sealed
[AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
- public sealed class ApplicationHost {
- static string [] types = { "Web.config", "Web.Config", "web.config" };
+ public sealed class ApplicationHost {
+ internal static readonly string MonoHostedDataKey = ".:!MonoAspNetHostedApp!:.";
+ internal static string [] WebConfigFileNames = { "Web.config", "Web.Config", "web.config" };
private ApplicationHost ()
{
{
string r = null;
- foreach (string s in types){
+ foreach (string s in WebConfigFileNames){
r = Path.Combine (basedir, s);
if (File.Exists (r))
#if NET_2_0
appdomain.SetData ("DataDirectory", Path.Combine (physicalDir, "App_Data"));
#endif
+ appdomain.SetData (MonoHostedDataKey, "yes");
+
return appdomain.CreateInstanceAndUnwrap (hostType.Module.Assembly.FullName, hostType.FullName);
}
}
+2007-10-17 Marek Habersack <mhabersack@novell.com>
+
+ * ApplicationHost.cs: introduce an application domain data item to
+ allow checks for whether System.Web code runs inside a hosted
+ application or in a stand-alone one.
+ Made the array of web.config name variations an internal one, to
+ be used from within configuration code.
+
2007-08-24 Marek Habersack <mhabersack@novell.com>
* ApplicationHost.cs: use ; as the separator with PrivateBinPath.
+2007-10-15 Marek Habersack <mhabersack@novell.com>
+
+ * ProfileBase.cs: use HttpApplication.LoadType instead of
+ Type.GetType.
+
2007-08-14 Marek Habersack <mhabersack@novell.com>
* SqlProfileProvider.cs: remove unused variable.
static Type GetPropertyType (ProfileGroupSettings pgs, ProfilePropertySettings pps)
{
- Type type = Type.GetType (pps.Type);
+ Type type = HttpApplication.LoadType (pps.Type);
if (type != null)
return type;
sp.DefaultValue = ((DefaultSettingValueAttribute) attributes [i]).Value;
else if (attributes [i] is SettingsProviderAttribute) {
- Type providerType = Type.GetType (((SettingsProviderAttribute) attributes [i]).ProviderTypeName);
+ Type providerType = HttpApplication.LoadType (((SettingsProviderAttribute) attributes [i]).ProviderTypeName);
sp.Provider = (SettingsProvider) Activator.CreateInstance (providerType);
sp.Provider.Initialize (null, null);
}
+2007-10-17 Marek Habersack <mhabersack@novell.com>
+
+ * SessionInProcHandler.cs: in certain situations the 'item'
+ parameter passed to SetAndReleaseItemExclusive may be null. The
+ issue was reported in bug #333898, but the reporter cannot provide
+ a test case that triggers the issue. Added work around the problem
+ in the way that should have the least impact on the rest of the
+ code. If 'item' is null, then the new session item is created
+ without the items and staticItems collections - they will be
+ initialized to defaults when retrieving the session item. This is
+ not a correct fix, but since there is no test case this is the
+ best what can be done right now.
+
+2007-10-15 Juraj Skripsky <js@hotfeet.ch>
+
+ * SessionStateModule.cs (Init): Use HttpApplication.LoadType,
+ don't swallow TypeLoadException.
+
+2007-10-15 Marek Habersack <mhabersack@novell.com>
+
+ * SessionStateServerHandler.cs: adjust order of field
+ initialization.
+
2007-09-18 Marek Habersack <mhabersack@novell.com>
* SessionIDManager.cs: preserve the query part of the url when
item.rwlock.ReleaseWriterLock ();
}
}
-
+
+ /* In certain situations the 'item' parameter passed to SetAndReleaseItemExclusive
+ may be null. The issue was reported in bug #333898, but the reporter cannot
+ provide a test case that triggers the issue. Added work around the problem
+ in the way that should have the least impact on the rest of the code. If 'item'
+ is null, then the new session item is created without the items and staticItems
+ collections - they will be initialized to defaults when retrieving the session
+ item. This is not a correct fix, but since there is no test case this is the best
+ what can be done right now.
+ */
public override void SetAndReleaseItemExclusive (HttpContext context,
string id,
SessionStateStoreData item,
string CacheId = CachePrefix + id;
Cache cache = HttpRuntime.InternalCache;
InProcSessionItem inProcItem = cache [CacheId] as InProcSessionItem;
+ ISessionStateItemCollection itemItems = null;
+ int itemTimeout = 20;
+ HttpStaticObjectsCollection itemStaticItems = null;
+
+ if (item != null) {
+ itemItems = item.Items;
+ itemTimeout = item.Timeout;
+ itemStaticItems = item.StaticObjects;
+ }
if (newItem || inProcItem == null) {
inProcItem = new InProcSessionItem ();
- inProcItem.timeout = item.Timeout;
- inProcItem.expiresAt = DateTime.UtcNow.AddMinutes (item.Timeout);
+ inProcItem.timeout = itemTimeout;
+ inProcItem.expiresAt = DateTime.UtcNow.AddMinutes (itemTimeout);
if (lockId.GetType() == typeof(Int32))
inProcItem.lockId = (Int32)lockId;
} else {
try {
inProcItem.rwlock.AcquireWriterLock (lockAcquireTimeout);
inProcItem.locked = false;
- inProcItem.items = item.Items;
- inProcItem.staticItems = item.StaticObjects;
- InsertSessionItem (inProcItem, item.Timeout, CacheId);
+ inProcItem.items = itemItems;
+ inProcItem.staticItems = itemStaticItems;
+ InsertSessionItem (inProcItem, itemTimeout, CacheId);
} catch {
throw;
} finally {
handler = (SessionStateStoreProviderBase) ProvidersHelper.InstantiateProvider (settings, typeof (SessionStateStoreProviderBase));
- try {
- Type idManagerType;
- try {
- idManagerType = Type.GetType (config.SessionIDManagerType, true);
- }
- catch {
- idManagerType = typeof (SessionIDManager);
- }
- idManager = Activator.CreateInstance (idManagerType) as ISessionIDManager;
- idManager.Initialize ();
+ if (String.IsNullOrEmpty(config.SessionIDManagerType)) {
+ idManager = new SessionIDManager ();
+ } else {
+ Type idManagerType = HttpApplication.LoadType (config.SessionIDManagerType, true);
+ idManager = (ISessionIDManager)Activator.CreateInstance (idManagerType);
}
- catch (Exception ex) {
+
+ try {
+ idManager.Initialize ();
+ } catch (Exception ex) {
throw new HttpException ("Failed to initialize session ID manager.", ex);
}
#if TRACE
Console.WriteLine ("SessionStateServerHandler.Initialize");
#endif
+ this.config = (SessionStateSection) WebConfigurationManager.GetSection ("system.web/sessionState");
if (String.IsNullOrEmpty (name))
name = "Session Server handler";
RemotingConfiguration.Configure (null);
GetConData (out proto, out server, out port);
cons = String.Format ("{0}://{1}:{2}/StateServer", proto, server, port);
stateServer = Activator.GetObject (typeof (RemoteStateServer), cons) as RemoteStateServer;
- this.config = (SessionStateSection) WebConfigurationManager.GetSection ("system.web/sessionState");
+
base.Initialize (name, config);
}
protected virtual void RenderBulletText (ListItem item, int index, HtmlTextWriter writer)
{
+ string text = HttpUtility.HtmlEncode (item.Text);
+
switch (DisplayMode) {
case BulletedListDisplayMode.Text:
if (!item.Enabled) {
writer.RenderBeginTag (HtmlTextWriterTag.Span);
}
- writer.Write (item.Text);
+ writer.Write (text);
if (!item.Enabled)
writer.RenderEndTag ();
writer.AddAttribute (HtmlTextWriterAttribute.Disabled, "disabled", false);
writer.RenderBeginTag (HtmlTextWriterTag.A);
- writer.Write (item.Text);
+ writer.Write (text);
writer.RenderEndTag ();
break;
else
writer.AddAttribute (HtmlTextWriterAttribute.Disabled, "disabled", false);
writer.RenderBeginTag (HtmlTextWriterTag.A);
- writer.Write (item.Text);
+ writer.Write (text);
writer.RenderEndTag ();
break;
}
+2007-10-18 Marek Habersack <mhabersack@novell.com>
+
+ * Menu.js: a workaround for an IE bug. IE recalculates element's
+ offsetWidth when the element's _height_ is set - which in case of
+ elements with overflowing content results in a value that's just
+ slightly smaller than the client window width. In effect, a long
+ submenu will also be very wide, which isn't desirable. Fixes bug
+ #322809
+
+2007-10-15 Marek Habersack <mhabersack@novell.com>
+
+ * ObjectDataSourceView.cs: use HttpApplication.LoadType instead of
+ Type.GetType.
+
+ * BulletedList.cs: html encode the item text. Fixes bug #333550.
+
2007-10-01 Marek Habersack <mhabersack@novell.com>
* ListItem.cs: make HasAttributes available for the 1.1 profile as
if (subm.parentMenu == null && parentId != null)
subm.parentMenu = getSubMenu (menuId, parentId);
- if (subm.firstShown != true) {
+ if (subm.firstShown != true) {
var item = getMenuItem (menuId, itemId);
var offx = 0;
var offy = 0;
var submMargin = subm.offsetHeight - subm.clientHeight;
subm.initialOffsetHeight = subm.offsetHeight - subm.scrollButtonsHeight + submMargin;
subm.firstShown = true;
+
}
Menu_SetActive (menu, subm);
box.scrollTop = 0;
var bottom = subm.offsetTop + subm.initialOffsetHeight - parent.scrollTop;
var displayScroll;
+
+ /*
+ * This is a workaround for an IE bug. IE recalculates the box offsetWidth when
+ * the box _height_ is set below - which in case of boxes with overflowing content
+ * results in a value that's just slightly smaller than the client window width.
+ * In effect, a long submenu will also be very wide, which isn't desirable.
+ */
+ var newWidth = box.offsetWidth;
if (bottom > parent.clientHeight /* && parent.scrollHeight > parent.clientHeight*/) {
var overflow = bottom - parent.clientHeight;
box.style.overflow = "hidden";
box.style.height = bh + "px";
displayScroll = "block";
+
}
} else {
displayScroll = "none";
box.style.height = subm.initialContentHeight + "px";
}
- subm.style.width = box.offsetWidth + "px";
+ subm.style.width = newWidth + "px";
+
var btn = getMenuScrollBox (menuId, itemId, "u");
btn.style.display = displayScroll;
btn = getMenuScrollBox (menuId, itemId, "d");
tca = a as TypeConverterAttribute;
if (tca == null)
continue;
- converterType = Type.GetType (tca.ConverterTypeName, false);
+ converterType = HttpApplication.LoadType (tca.ConverterTypeName, false);
if (converterType == null)
continue;
converter = Activator.CreateInstance (converterType, new object[] {targetType}) as TypeConverter;
+2007-10-17 Marek Habersack <mhabersack@novell.com>
+
+ * TemplateParser.cs: removed code that ignored the Async and
+ AsyncTimeout attributes.
+
+ * PageParser.cs: handle the Async and AsyncTimeout attributes
+ here. Fixes bug #325450
+
+ * Control.cs: properly configure control visibility in
+ PreRenderRecursiveInternal. The check must be made by looking at
+ the Visible value, not at the flags directly. Fixes bug #325303
+
2007-10-03 Marek Habersack <mhabersack@novell.com>
* Page.cs: complete implementation of ValidationGroups. Fixes bug
internal void PreRenderRecursiveInternal ()
{
- if ((stateMask & VISIBLE) != 0) {
+ bool visible;
+
+#if NET_2_0
+ visible = Visible;
+#else
+ visible = (stateMask & VISIBLE) != 0;
+#endif
+
+ if (visible) {
+#if NET_2_0
+ SetMask (VISIBLE, true);
+#endif
EnsureChildControls ();
#if MONO_TRACE
TraceContext trace = (Context != null && Context.Trace.IsEnabled) ? Context.Trace : null;
trace.Write ("control", String.Format ("End PreRenderRecursive {0} {1}", _userId, type_name));
#endif
}
+#if NET_2_0
+ else
+ SetMask (VISIBLE, false);
+#endif
+
stateMask |= PRERENDERED;
}
Type baseType = typeof (Page);
#if NET_2_0
+ bool async;
+ int asyncTimeout = -1;
string masterPage;
Type masterType;
string title;
notBuffer = !GetBool (atts, "Buffer", true);
#if NET_2_0
+ async = GetBool (atts, "Async", false);
+ string asyncTimeoutVal = GetString (atts, "AsyncTimeout", null);
+ if (asyncTimeoutVal != null) {
+ try {
+ asyncTimeout = Int32.Parse (asyncTimeoutVal);
+ } catch (Exception) {
+ ThrowParseException ("AsyncTimeout must be an integer value");
+ }
+ }
+
masterPage = GetString (atts, "MasterPageFile", masterPage);
// Make sure the page exists
}
#if NET_2_0
+ internal bool Async {
+ get { return async; }
+ }
+
+ internal int AsyncTimeout {
+ get { return asyncTimeout; }
+ }
+
internal string Theme {
get { return theme; }
}
atts.Remove ("CodeBehind"); // ignored
#endif
atts.Remove ("AspCompat"); // ignored
-#if NET_2_0
- // these two are ignored for the moment
- atts.Remove ("Async");
- atts.Remove ("AsyncTimeOut");
-#endif
debug = GetBool (atts, "Debug", true);
compilerOptions = GetString (atts, "CompilerOptions", "");
+2007-10-18 Juraj Skripsky <js@hotfeet.ch>
+
+ * StaticSiteMapProvider.cs: Replace Hashtables by Dictionaries,
+ don't allocate them on-demand, there will never be many
+ Provider instances around.
+ AddNode(): Check for duplicate keys before adding any item to
+ hashtables.
+ RemoveNode(): Use fact that Hashtable.Remove() never throws,
+ remove item from keyToNode as well, make symmetric to AddNode().
+ MapUrl(): Use VirtualPathUtility, allow for full urls
+ (e.g. http://www.google.com).
+
+2007-10-17 Marek Habersack <mhabersack@novell.com>
+
+ * StaticFileHandler.cs: fixed an bug with Mono running under
+ Windows operating systems which caused XSP to return source of the
+ requested page if the file name used in the request ended in any
+ number of spaces or dots. The problem lies in the way the Win32
+ subsystem treats such file names - it ignores the trailing
+ characters and allows the calling application to open a file on
+ disk even when its name does not contain the trailing characters
+ used in the open request. Such file names may be supported by the
+ underlying filesystem (e.g. NTFS) but they are not supported by
+ the I/O Win32 subsystem. The security issue is reported in
+ CVE security report CVE-2007-5473. Fixes bug #332401
+
+2007-10-17 Igor Zelmanovich <igorz@mainsoft.com>
+
+ * HttpResponse.cs:
+ response status is sent after PreSendRequestHeaders invoked.
+ Redirect method set RedirectLocation property
+ fixes bug #334521
+
+2007-10-15 Marek Habersack <mhabersack@novell.com>
+
+ * HttpApplication.cs: do not return a non-existing bin directory
+ from BinDirectories. Patch from Atsushi Enomoto
+ <atsushi@ximian.com>, thanks! Fixes bug #332434.
+
2007-10-04 Marek Habersack <mhabersack@novell.com>
* HttpApplication.cs: call the Init method after loading the
string baseDir = setup.ApplicationBase;
string bindir;
- if (Environment.GetEnvironmentVariable ("MONO_IOMAP") != null || IsRunningOnWindows)
- yield return Path.Combine (baseDir, "bin");
- else {
+ if (Environment.GetEnvironmentVariable ("MONO_IOMAP") != null || IsRunningOnWindows) {
+ bindir = Path.Combine (baseDir, "bin");
+ if (Directory.Exists (bindir))
+ yield return bindir;
+ } else {
foreach (string dir in BinDirs) {
bindir = Path.Combine (baseDir, dir);
if (!Directory.Exists (bindir))
if (headers_sent)
return;
- if (WorkerRequest != null)
- WorkerRequest.SendStatus (status_code, StatusDescription);
-
if (cached_response != null)
cached_response.SetHeaders (headers);
if (app_instance != null)
app_instance.TriggerPreSendRequestHeaders ();
}
+
+ if (WorkerRequest != null)
+ WorkerRequest.SendStatus (status_code, StatusDescription);
+
if (WorkerRequest != null) {
foreach (BaseResponseHeader header in write_headers){
header.SendContent (WorkerRequest);
StatusCode = 302;
url = ApplyAppPathModifier (url);
- headers.Add (new UnknownResponseHeader ("Location", url));
+ redirect_location = url;
// Text for browsers that can't handle location header
Write ("<html><head><title>Object moved</title></head><body>\r\n");
using System;
using System.Globalization;
using System.IO;
+using System.Web.Util;
namespace System.Web
{
class StaticFileHandler : IHttpHandler
{
+ static bool runningWindows = RunningOnWindows ();
+
+ static bool RunningOnWindows ()
+ {
+ int pid = (int)Environment.OSVersion.Platform;
+ return (pid != 4 && pid != 128);
+ }
+
+ static bool ValidFileName (string fileName)
+ {
+ if (!runningWindows)
+ return true;
+
+ if (fileName == null || fileName.Length == 0)
+ return false;
+
+ return (!StrUtils.EndsWith (fileName, " ") && !StrUtils.EndsWith (fileName, "."));
+ }
+
public void ProcessRequest (HttpContext context)
{
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string fileName = request.PhysicalPath;
FileInfo fi = new FileInfo (fileName);
- if (!fi.Exists)
+ if (!fi.Exists || !ValidFileName (fileName))
throw new HttpException (404, "File '" + request.FilePath + "' not found.");
if ((fi.Attributes & FileAttributes.Directory) != 0) {
// Authors:
// Lluis Sanchez Gual (lluis@novell.com)
// Ben Maurer (bmaurer@users.sourceforge.net)
+// Juraj Skripsky (js@hotfeet.ch)
//
// (C) 2003 Ben Maurer
// (C) 2005 Novell, Inc (http://www.novell.com)
+// (C) 2007 HotFeet GmbH (http://www.hotfeet.ch)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
#if NET_2_0
-using System.Collections;
-using System.Collections.Specialized;
-using System.Text;
-using System.Configuration.Provider;
-using System.Web.Util;
-using System.Globalization;
+using System.Collections.Generic;
namespace System.Web
{
public abstract class StaticSiteMapProvider : SiteMapProvider
{
- Hashtable nodeToParent;
- Hashtable nodeToChildren;
- Hashtable urlToNode;
- Hashtable keyToNode;
-
+ Dictionary<string, SiteMapNode> keyToNode;
+ Dictionary<SiteMapNode, SiteMapNode> nodeToParent;
+ Dictionary<SiteMapNode, SiteMapNodeCollection> nodeToChildren;
+ Dictionary<string, SiteMapNode> urlToNode;
+
+ public StaticSiteMapProvider ()
+ {
+ keyToNode = new Dictionary<string, SiteMapNode> ();
+ nodeToParent = new Dictionary<SiteMapNode, SiteMapNode> ();
+ nodeToChildren = new Dictionary<SiteMapNode, SiteMapNodeCollection> ();
+ urlToNode = new Dictionary<string, SiteMapNode> (StringComparer.InvariantCultureIgnoreCase);
+ }
+
internal protected override void AddNode (SiteMapNode node, SiteMapNode parentNode)
{
if (node == null)
throw new ArgumentNullException ("node");
-
+
lock (this_lock) {
- string url = node.Url;
- if (url != null && url.Length > 0) {
- url = MapUrl (url);
+ if (FindSiteMapNodeFromKey (node.Key) != null)
+ throw new InvalidOperationException (string.Format ("A node with key '{0}' already exists.",node.Key));
+ if (!String.IsNullOrEmpty (node.Url)) {
+ string url = MapUrl (node.Url);
+
if (FindSiteMapNode (url) != null)
throw new InvalidOperationException (String.Format (
"Multiple nodes with the same URL '{0}' were found. " +
node.Url
));
- UrlToNode [url] = node;
+ urlToNode.Add (url, node);
}
-
- if (FindSiteMapNodeFromKey (node.Key) != null)
- throw new InvalidOperationException (string.Format ("A node with key {0} already exists.",node.Key));
- KeyToNode [node.Key] = node;
+ keyToNode.Add (node.Key, node);
if (node == RootNode)
return;
if (parentNode == null)
parentNode = RootNode;
- NodeToParent [node] = parentNode;
- if (NodeToChildren [parentNode] == null)
- NodeToChildren [parentNode] = new SiteMapNodeCollection ();
-
- ((SiteMapNodeCollection) NodeToChildren [parentNode]).Add (node);
- }
- }
-
- Hashtable NodeToParent {
- get {
- lock (this_lock) {
- if (nodeToParent == null)
- nodeToParent = new Hashtable ();
- }
- return nodeToParent;
- }
- }
-
- Hashtable NodeToChildren {
- get {
- lock (this_lock) {
- if (nodeToChildren == null)
- nodeToChildren = new Hashtable ();
- }
- return nodeToChildren;
- }
- }
-
- Hashtable UrlToNode {
- get {
- lock (this_lock) {
- if (urlToNode == null) {
- urlToNode = new Hashtable (StringComparer.InvariantCultureIgnoreCase);
- }
- }
- return urlToNode;
- }
- }
-
- Hashtable KeyToNode {
- get {
- lock (this_lock) {
- if (keyToNode == null)
- keyToNode = new Hashtable ();
- }
- return keyToNode;
+ nodeToParent.Add (node, parentNode);
+
+ SiteMapNodeCollection children;
+ if (!nodeToChildren.TryGetValue (parentNode, out children))
+ nodeToChildren.Add (parentNode, children = new SiteMapNodeCollection ());
+
+ children.Add (node);
}
}
protected virtual void Clear ()
{
lock (this_lock) {
- if (urlToNode != null)
- urlToNode.Clear ();
- if (nodeToChildren != null)
- nodeToChildren.Clear ();
- if (nodeToParent != null)
- nodeToParent.Clear ();
- if (keyToNode != null)
- keyToNode.Clear ();
+ urlToNode.Clear ();
+ nodeToChildren.Clear ();
+ nodeToParent.Clear ();
+ keyToNode.Clear ();
}
}
if (rawUrl == null)
throw new ArgumentNullException ("rawUrl");
- if (rawUrl.Length > 0) {
- this.BuildSiteMap();
- rawUrl = MapUrl (rawUrl);
- SiteMapNode node = (SiteMapNode) UrlToNode [rawUrl];
- if (node != null && IsAccessibleToUser (HttpContext.Current, node))
- return node;
- }
- return null;
+ if (rawUrl == String.Empty)
+ return null;
+
+ BuildSiteMap();
+ SiteMapNode node;
+ urlToNode.TryGetValue (MapUrl (rawUrl), out node);
+ return CheckAccessibility (node);
}
public override SiteMapNodeCollection GetChildNodes (SiteMapNode node)
if (node == null)
throw new ArgumentNullException ("node");
- this.BuildSiteMap();
- SiteMapNodeCollection col = (SiteMapNodeCollection) NodeToChildren [node];
- if (col == null) return SiteMapNodeCollection.EmptyCollection;
+ BuildSiteMap();
+ SiteMapNodeCollection col;
+ if (!nodeToChildren.TryGetValue (node, out col))
+ return SiteMapNodeCollection.EmptyCollection;
SiteMapNodeCollection ret = null;
for (int n=0; n<col.Count; n++) {
return SiteMapNodeCollection.ReadOnly (ret);
else
return SiteMapNodeCollection.EmptyCollection;
-
}
public override SiteMapNode GetParentNode (SiteMapNode node)
{
if (node == null)
throw new ArgumentNullException ("node");
- this.BuildSiteMap();
- SiteMapNode parent = (SiteMapNode) NodeToParent [node];
- return parent != null && IsAccessibleToUser (HttpContext.Current, parent) ? parent : null;
+
+ BuildSiteMap();
+ SiteMapNode parent;
+ nodeToParent.TryGetValue (node, out parent);
+ return CheckAccessibility (parent);
}
protected override void RemoveNode (SiteMapNode node)
throw new ArgumentNullException("node");
lock (this_lock) {
- SiteMapNode parent = (SiteMapNode) NodeToParent [node];
- if (NodeToParent.Contains (node))
- NodeToParent.Remove (node);
-
- if (node.Url != null && node.Url.Length > 0 && UrlToNode.Contains (node.Url))
- UrlToNode.Remove (node.Url);
-
- if (parent != null) {
- SiteMapNodeCollection siblings = (SiteMapNodeCollection) NodeToChildren [parent];
- if (siblings != null && siblings.Contains (node))
- siblings.Remove (node);
- }
+ keyToNode.Remove (node.Key);
+ if (!String.IsNullOrEmpty (node.Url))
+ urlToNode.Remove (MapUrl (node.Url));
+
+ if (node == RootNode)
+ return;
+
+ SiteMapNode parent = nodeToParent [node];
+ nodeToParent.Remove (node);
+ nodeToChildren [parent].Remove (node);
}
}
if (key == null)
throw new ArgumentNullException ("key");
- SiteMapNode ret = (SiteMapNode) KeyToNode [key];
- return ret != null && IsAccessibleToUser (HttpContext.Current, ret) ? ret : null;
+ SiteMapNode ret;
+ keyToNode.TryGetValue (key, out ret);
+ return CheckAccessibility (ret);
}
public abstract SiteMapNode BuildSiteMap ();
+
+ SiteMapNode CheckAccessibility (SiteMapNode node) {
+ return (node != null && IsAccessibleToUser (HttpContext.Current, node)) ? node : null;
+ }
string MapUrl (string url)
{
- if (HttpContext.Current == null)
- return url;
-
- if (UrlUtils.IsRelativeUrl (url))
- return UrlUtils.Combine (HttpRuntime.AppDomainAppVirtualPath, url);
+ if (VirtualPathUtility.IsAppRelative (url))
+ return VirtualPathUtility.ToAbsolute (url);
else
- return UrlUtils.ResolveVirtualPathFromAppAbsolute (url);
+ return url;
}
-
}
}
#endif
+2007-10-19 Atsushi Enomoto <atsushi@ximian.com>
+
+ * SubtreeXmlReader.cs : when a subtree reader is closed, the original
+ reader moves to the end of the subtree. Fixed bug #334752, patch by
+ Scott Peterson.
+
2007-08-09 Atsushi Enomoto <atsushi@ximian.com>
* SubtreeXmlReader.cs XmlFilterReader.cs : further dependent changes.
public override void Close ()
{
- // do nothing
+ while (Reader.Depth > startDepth && Read ())
+ ;
}
public override string GetAttribute (int i)
+2007-10-19 Atsushi Enomoto <atsushi@ximian.com>
+
+ * XmlReaderCommonTests.cs : added test for bug #334752.
+
2007-09-28 Atsushi Enomoto <atsushi@ximian.com>
* XmlWriterTests.cs : added WriteNodeXPathNavigatorAttribute().
AssertEquals (String.Empty, reader.ReadElementContentAsString ("sample", ""));\r
AssertEquals (XmlNodeType.EndElement, reader.NodeType);\r
}\r
+\r
+ [Test]\r
+ public void ReadSubtreeClose ()\r
+ {\r
+ // bug #334752\r
+ string xml = @"<root><item-list><item id='a'/><item id='b'/></item-list></root>";\r
+ RunTest (xml, new TestMethod (ReadSubtreeClose));\r
+ }\r
+\r
+ void ReadSubtreeClose (XmlReader reader)\r
+ {\r
+ reader.ReadToFollowing ("item-list");\r
+ XmlReader sub = reader.ReadSubtree ();\r
+ sub.ReadToDescendant ("item");\r
+ sub.Close ();\r
+ AssertEquals ("#1", XmlNodeType.EndElement, reader.NodeType);\r
+ AssertEquals ("#2", "item-list", reader.Name);\r
+ }\r
#endif\r
}\r
}\r
+2007-10-22 Jb Evain <jbevain@novell.com>
+
+ * net_2_1_System.dll.sources: remove System.Net.Mail.*
+
2007-09-29 Gert Driesen <drieseng@users.sourceforge.net>
* System_test.dll.sources: Added HttpListenerRequestTest.cs.
+2007-10-13 Miguel de Icaza <miguel@novell.com>
+
+ * SerialPortStream.cs: Send a break on the Unix case.
+
2007-08-12 Lukasz Byczynski <lukaszb@forcom.com.pl>
* SerialPortStream.cs: added timeout handling on write
throw new IOException ();
}
+ [DllImport ("MonoPosixHelper")]
+ static extern int breakprop (int fd);
+
public void SetBreakState (bool value)
{
- throw new NotImplementedException ();
+ if (value)
+ breakprop (fd);
}
}
#region Constructors
- [MonoTODO]
public AlternateView (string fileName) : base (fileName)
{
if (fileName == null)
throw new ArgumentNullException ();
}
- [MonoTODO]
public AlternateView (string fileName, ContentType contentType) : base (fileName, contentType)
{
if (fileName == null)
throw new ArgumentNullException ();
}
- [MonoTODO]
public AlternateView (string fileName, string mediaType) : base (fileName, mediaType)
{
if (fileName == null)
throw new ArgumentNullException ();
}
- [MonoTODO]
public AlternateView (Stream contentStream) : base (contentStream)
{
- if (contentStream == null)
- throw new ArgumentNullException ();
}
- [MonoTODO]
public AlternateView (Stream contentStream, string mediaType) : base (contentStream, mediaType)
{
- if (contentStream == null)
- throw new ArgumentNullException ();
}
- [MonoTODO]
public AlternateView (Stream contentStream, ContentType contentType) : base (contentStream, contentType)
{
- if (contentStream == null)
- throw new ArgumentNullException ();
}
#endregion // Constructors
#region Methods
- [MonoTODO]
public static AlternateView CreateAlternateViewFromString (string content)
{
if (content == null)
throw new ArgumentNullException ();
MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes (content));
- return new AlternateView (ms);
+ AlternateView av = new AlternateView (ms);
+ av.TransferEncoding = TransferEncoding.QuotedPrintable;
+ return av;
}
- [MonoTODO]
public static AlternateView CreateAlternateViewFromString (string content, ContentType contentType)
{
if (content == null)
throw new ArgumentNullException ();
MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes (content));
- return new AlternateView (ms, contentType);
+ AlternateView av = new AlternateView (ms, contentType);
+ av.TransferEncoding = TransferEncoding.QuotedPrintable;
+ return av;
}
- [MonoTODO]
public static AlternateView CreateAlternateViewFromString (string content, Encoding encoding, string mediaType)
{
if (content == null)
throw new ArgumentNullException ();
MemoryStream ms = new MemoryStream (encoding.GetBytes (content));
- return new AlternateView (ms, mediaType);
+ AlternateView av = new AlternateView (ms, mediaType);
+ av.TransferEncoding = TransferEncoding.QuotedPrintable;
+ return av;
}
- [MonoTODO]
protected override void Dispose (bool disposing)
{
+ if (disposing)
+ foreach (LinkedResource lr in linkedResources)
+ lr.Dispose ();
base.Dispose (disposing);
}
{
}
+ protected override void ClearItems ()
+ {
+ base.ClearItems ();
+ }
+
+ protected override void InsertItem (int index, AlternateView item)
+ {
+ base.InsertItem (index, item);
+ }
+
+ protected override void RemoveItem (int index)
+ {
+ base.RemoveItem (index);
+ }
+
+ protected override void SetItem (int index, AlternateView item)
+ {
+ base.SetItem (index, item);
+ }
+
#endregion // Methods
}
}
InitName (fileName);
}
- [MonoTODO]
public Attachment (Stream contentStream, ContentType contentType)
: base (contentStream, contentType) {
- //FIXME: What should we do with the name???
}
- [MonoTODO]
- public Attachment (Stream contentStream, string mediaType)
- : base (contentStream, mediaType) {
- //FIXME: What should we do with the name???
+ public Attachment (Stream contentStream, string name)
+ : base (contentStream) {
+ Name = name;
}
- [MonoTODO]
public Attachment (Stream contentStream, string name, string mediaType)
: base (contentStream, mediaType) {
- if (name == null) {
- throw new ArgumentNullException ("name");
- }
-
Name = name;
}
public string Name {
get { return ContentType.Name; }
- set {
- if (value == null)
- throw new ArgumentNullException ();
- if (value.Equals (""))
- throw new ArgumentException ();
- ContentType.Name = value;
- }
+ set { ContentType.Name = value; }
}
- [MonoTODO]
public Encoding NameEncoding {
get { return nameEncoding; }
set { nameEncoding = value; }
#region Methods
- [MonoTODO]
public static Attachment CreateAttachmentFromString (string content, ContentType contentType)
{
+ if (content == null)
+ throw new ArgumentNullException ("content");
MemoryStream ms = new MemoryStream ();
StreamWriter sw = new StreamWriter (ms);
sw.Write (content);
sw.Flush ();
ms.Position = 0;
- return new Attachment (ms, contentType);
+ Attachment a = new Attachment (ms, contentType);
+ a.TransferEncoding = TransferEncoding.QuotedPrintable;
+ return a;
}
- [MonoTODO]
public static Attachment CreateAttachmentFromString (string content, string name)
{
+ if (content == null)
+ throw new ArgumentNullException ("content");
MemoryStream ms = new MemoryStream ();
StreamWriter sw = new StreamWriter (ms);
sw.Write (content);
sw.Flush ();
ms.Position = 0;
- return new Attachment (ms, name);
+ Attachment a = new Attachment (ms, new ContentType ("text/plain"));
+ a.TransferEncoding = TransferEncoding.QuotedPrintable;
+ a.Name = name;
+ return a;
}
- [MonoTODO]
- public static Attachment CreateAttachmentFromString (string content, string name, Encoding encoding, string mediaType)
+ public static Attachment CreateAttachmentFromString (string content, string name, Encoding contentEncoding, string mediaType)
{
+ if (content == null)
+ throw new ArgumentNullException ("content");
MemoryStream ms = new MemoryStream ();
- StreamWriter sw = new StreamWriter (ms);
+ StreamWriter sw = new StreamWriter (ms, contentEncoding);
sw.Write (content);
sw.Flush ();
ms.Position = 0;
- return new Attachment (ms, name, mediaType);
+ Attachment a = new Attachment (ms, name, mediaType);
+ a.TransferEncoding = TransferEncoding.QuotedPrintable;
+ return a;
}
#endregion // Methods
string id;
ContentType contentType = new ContentType ();
Stream contentStream;
- TransferEncoding transferEncoding;
+ TransferEncoding transferEncoding = TransferEncoding.Base64;
#endregion // Fields
this.contentStream = contentStream;
contentType.MediaType = MediaTypeNames.Application.Octet;
contentType.CharSet = null;
- transferEncoding = TransferEncoding.Base64;
}
protected AttachmentBase (Stream contentStream, ContentType contentType)
throw new ArgumentNullException ();
this.contentStream = contentStream;
this.contentType = contentType;
- transferEncoding = TransferEncoding.Base64;
}
protected AttachmentBase (Stream contentStream, string mediaType)
throw new ArgumentNullException ();
this.contentStream = contentStream;
contentType.MediaType = mediaType;
- transferEncoding = TransferEncoding.Base64;
}
protected AttachmentBase (string fileName)
throw new ArgumentNullException ();
contentStream = File.OpenRead (fileName);
contentType = new ContentType (MimeTypes.GetMimeType (fileName));
- transferEncoding = TransferEncoding.Base64;
}
protected AttachmentBase (string fileName, ContentType contentType) {
throw new ArgumentNullException ();
contentStream = File.OpenRead (fileName);
this.contentType = contentType;
- transferEncoding = TransferEncoding.Base64;
}
protected AttachmentBase (string fileName, string mediaType)
throw new ArgumentNullException ();
contentStream = File.OpenRead (fileName);
contentType.MediaType = mediaType;
- transferEncoding = TransferEncoding.Base64;
}
#endregion // Constructors
//GC.SuppressFinalize (this);
}
- [MonoTODO]
protected virtual void Dispose (bool disposing)
{
+ if (disposing)
+ contentStream.Close ();
}
#endregion // Methods
{
}
- [MonoTODO]
public void Dispose ()
{
for (int i = 0; i < Count; i += 1)
this [i].Dispose ();
}
+
+ protected override void ClearItems ()
+ {
+ base.ClearItems ();
+ }
+
+ protected override void InsertItem (int index, Attachment item)
+ {
+ base.InsertItem (index, item);
+ }
+
+ protected override void RemoveItem (int index)
+ {
+ base.RemoveItem (index);
+ }
+
+ protected override void SetItem (int index, Attachment item)
+ {
+ base.SetItem (index, item);
+ }
}
}
+2007-10-23 Atsushi Enomoto <atsushi@ximian.com>
+
+ * SmtpClient.cs : small async refactory.
+
+2007-10-23 Atsushi Enomoto <atsushi@ximian.com>
+
+ * SmtpClient.cs : Implemented async operations.
+
+2007-10-23 Atsushi Enomoto <atsushi@ximian.com>
+
+ * Attachment.cs : reverted previous change. NameEncoding is not
+ guessed at set_Name().
+
+2007-10-22 Atsushi Enomoto <atsushi@ximian.com>
+
+ * SmtpClient.cs : lunatic cyclic build.
+
+2007-10-22 Atsushi Enomoto <atsushi@ximian.com>
+
+ * AttachmentBase.cs : implemented Dispose(bool).
+
+2007-10-22 Atsushi Enomoto <atsushi@ximian.com>
+
+ * AttachmentCollection.cs : remove TODO.
+ * Attachment.cs : guess NameEncoding when set_Name().
+ * MailMessage.cs : moved encoding guess impl to ContentType.
+ * SmtpClient.cs : moved RFC 2047 encoding impl to ContentType.
+ Support attachment Name encoding. Added some SSL changes (it's not
+ working yet).
+
+2007-10-22 Atsushi Enomoto <atsushi@ximian.com>
+
+ * SmtpClient.cs : attachment refactory. First, determine whether we
+ send multipart/mixed for attachments. Second, determine whether we
+ send multipart/alternative for AlternateViews.
+ Consider LinkedResources. Mark EnableSsl as TODO.
+
+2007-10-22 Atsushi Enomoto <atsushi@ximian.com>
+
+ * LinkedResource.cs : Now they are implemented and soon to be
+ supported. Fixed TransferEncoding (same as other AttachmentBase).
+
+2007-10-22 Atsushi Enomoto <atsushi@ximian.com>
+
+ * Attachment.cs : null name is allowed.
+
+2007-10-19 Atsushi Enomoto <atsushi@ximian.com>
+
+ * AlternateView.cs, AttachmentView.cs, AttachmentBase.cs :
+ reverted default back to TransferEncoding.Base64 again, and use
+ QuotedPrintable only when created from string.
+ No need to check null Stream at AlternateView.ctor(). See base.
+ * SmtpClient.cs : For multipart message, do not send body twice (it
+ still emits extraneous part, which should be fixed too).
+ Do not premise charset existence in every AttachmentBase.
+
+2007-10-17 Atsushi Enomoto <atsushi@ximian.com>
+
+ * AlternateView.cs : dispose linked resources. Remove MonoTODOs.
+ * Attachment.cs : check null content string.
+ The string argument in .ctor(Stream,string) is name, not mediaType.
+ Use contentEncoding argument in CreateAttachmentFromString().
+ * AttachmentBase.cs : TransferEncoding default is QuotedPrintable.
+
+2007-10-17 Atsushi Enomoto <atsushi@ximian.com>
+
+ * MailMessage.cs : removed MonoTODO. some comment.
+ * SmtpException.cs, SmtpFailedRecipientsException.cs,
+ SmtpFailedRecipientException.cs : implemented serialization.
+
+2007-10-16 Atsushi Enomoto <atsushi@ximian.com>
+
+ * SmtpClient.cs : use 3 StringBuilder.Replace() calls rather than
+ 3 string.Replace() calls.
+
+2007-10-16 Atsushi Enomoto <atsushi@ximian.com>
+
+ * SmtpClient.cs : do state check on other setters than set_Timeout().
+
+2007-10-16 Atsushi Enomoto <atsushi@ximian.com>
+
+ * MailMessage.cs : Some entire refactory on BodyEncoding and
+ IsBodyHtml. BodyEncoding and SubjectEncoding are guessed when
+ Body and Subject are set for each.
+ * SmtpClient.cs :
+ Subject header is encoded according to RFC 2047.
+ Body is encoded according to RFC 2821.
+ Output Date header.
+ ToQuotedPrintable() should take encoding into consideration.
+ For SevenBit/Unknown TransferEncoding, just decode with ASCII.
+ In set_UseDefaultCredentials(), raise NIE only when value is true.
+ In set_Timeout(), raise an error when Send() is in progress.
+
+2007-10-16 Atsushi Enomoto <atsushi@ximian.com>
+
+ * SmtpClient.cs : Replace every \r and \n with \r\n per RFC 2821
+ section 2.3.7, or you will receive SMTP error 451.
+
+2007-10-16 Atsushi Enomoto <atsushi@ximian.com>
+
+ * AlternateViewCollection.cs, LinkedResourceCollection.cs,
+ AttachmentCollection.cs : added missing 2.0 members.
+
2007-06-17 Gert Driesen <drieseng@users.sourceforge.net>
* MailAddress.cs: Throw ArgumentNullException if address is null.
#region Constructors
- [MonoTODO]
public LinkedResource (string fileName) : base (fileName)
{
if (fileName == null)
throw new ArgumentNullException ();
}
- [MonoTODO]
public LinkedResource (string fileName, ContentType contentType) : base (fileName, contentType)
{
if (fileName == null)
throw new ArgumentNullException ();
}
- [MonoTODO]
public LinkedResource (string fileName, string mediaType) : base (fileName, mediaType)
{
if (fileName == null)
throw new ArgumentNullException ();
}
- [MonoTODO]
public LinkedResource (Stream contentStream) : base (contentStream)
{
if (contentStream == null)
throw new ArgumentNullException ();
}
- [MonoTODO]
public LinkedResource (Stream contentStream, ContentType contentType) : base (contentStream, contentType)
{
if (contentStream == null)
throw new ArgumentNullException ();
}
- [MonoTODO]
public LinkedResource (Stream contentStream, string mediaType) : base (contentStream, mediaType)
{
if (contentStream == null)
#region Methods
- [MonoTODO]
public static LinkedResource CreateLinkedResourceFromString (string content)
{
if (content == null)
throw new ArgumentNullException ();
MemoryStream ms = new MemoryStream (Encoding.Default.GetBytes (content));
- return new LinkedResource (ms);
+ LinkedResource lr = new LinkedResource (ms);
+ lr.TransferEncoding = TransferEncoding.QuotedPrintable;
+ return lr;
}
- [MonoTODO]
public static LinkedResource CreateLinkedResourceFromString (string content, ContentType contentType)
{
if (content == null)
throw new ArgumentNullException ();
MemoryStream ms = new MemoryStream (Encoding.Default.GetBytes (content));
- return new LinkedResource (ms, contentType);
+ LinkedResource lr = new LinkedResource (ms, contentType);
+ lr.TransferEncoding = TransferEncoding.QuotedPrintable;
+ return lr;
}
- [MonoTODO]
public static LinkedResource CreateLinkedResourceFromString (string content, Encoding contentEncoding, string mediaType)
{
if (content == null)
throw new ArgumentNullException ();
MemoryStream ms = new MemoryStream (contentEncoding.GetBytes (content));
- return new LinkedResource (ms, mediaType);
+ LinkedResource lr = new LinkedResource (ms, mediaType);
+ lr.TransferEncoding = TransferEncoding.QuotedPrintable;
+ return lr;
}
#endregion // Methods
{
}
+ protected override void ClearItems ()
+ {
+ base.ClearItems ();
+ }
+
+ protected override void InsertItem (int index, LinkedResource item)
+ {
+ base.InsertItem (index, item);
+ }
+
+ protected override void RemoveItem (int index)
+ {
+ base.RemoveItem (index);
+ }
+
+ protected override void SetItem (int index, LinkedResource item)
+ {
+ base.SetItem (index, item);
+ }
+
#endregion // Methods
}
}
using System.Text;
namespace System.Net.Mail {
- [MonoTODO]
public class MailMessage : IDisposable
{
#region Fields
NameValueCollection headers;
MailAddressCollection to;
string subject;
- Encoding subjectEncoding;
- ContentType bodyContentType;
+ Encoding subjectEncoding, bodyEncoding;
+ bool isHtml;
#endregion // Fields
headers.Add ("MIME-Version", "1.0");
}
- // FIXME: should throw a FormatException if the addresses are wrong.
+ // FIXME: should it throw a FormatException if the addresses are wrong?
+ // (How is it possible to instantiate such a malformed MailAddress?)
public MailMessage (MailAddress from, MailAddress to) : this ()
{
if (from == null || to == null)
public string Body {
get { return body; }
- set { body = value; }
+ set {
+ // autodetect suitable body encoding (ASCII or UTF-8), if it is not initialized yet.
+ if (value != null && bodyEncoding == null)
+ bodyEncoding = GuessEncoding (value);
+ body = value;
+ }
}
internal ContentType BodyContentType {
get {
- if (bodyContentType == null)
- bodyContentType = new ContentType ("text/plain; charset=us-ascii");
- return bodyContentType;
+ ContentType ct = new ContentType (isHtml ? "text/html" : "text/plain");
+ ct.CharSet = (BodyEncoding ?? Encoding.ASCII).HeaderName;
+ return ct;
+ }
+ }
+
+ internal TransferEncoding ContentTransferEncoding {
+ get {
+ Encoding enc = BodyEncoding;
+ if (Encoding.ASCII.Equals (enc))
+ return TransferEncoding.SevenBit;
+ else if (Encoding.UTF8.CodePage == enc.CodePage ||
+ Encoding.Unicode.CodePage == enc.CodePage ||
+ Encoding.UTF32.CodePage == enc.CodePage)
+ return TransferEncoding.Base64;
+ else
+ return TransferEncoding.QuotedPrintable;
}
}
public Encoding BodyEncoding {
- get { return Encoding.GetEncoding (BodyContentType.CharSet); }
- set { BodyContentType.CharSet = value.WebName; }
+ get { return bodyEncoding; }
+ set { bodyEncoding = value; }
}
public MailAddressCollection CC {
}
public bool IsBodyHtml {
- get { return String.Compare (BodyContentType.MediaType, "text/html", true, CultureInfo.InvariantCulture) == 0; }
- set {
- if (value)
- BodyContentType.MediaType = "text/html";
- else
- BodyContentType.MediaType = "text/plain";
- }
+ get { return isHtml; }
+ set { isHtml = value; }
}
public MailPriority Priority {
public string Subject {
get { return subject; }
- set { subject = value; }
+ set {
+ if (value != null && subjectEncoding == null)
+ subjectEncoding = GuessEncoding (value);
+ subject = value;
+ }
}
public Encoding SubjectEncoding {
{
}
+ private Encoding GuessEncoding (string s)
+ {
+ return ContentType.GuessEncoding (s);
+ }
+
#endregion // Methods
}
}
#if NET_2_0
+#if SECURITY_DEP
+extern alias PrebuiltSystem;
+#endif
+
using System;
using System.Collections.Generic;
using System.ComponentModel;
+using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Mime;
using System.Reflection;
using System.Net.Configuration;
using System.Configuration;
+using System.Net.Security;
+using System.Security.Authentication;
+using System.Security.Cryptography.X509Certificates;
+
+#if SECURITY_DEP
+using X509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
+#endif
namespace System.Net.Mail {
public class SmtpClient
string pickupDirectoryLocation;
SmtpDeliveryMethod deliveryMethod;
bool enableSsl;
- //X509CertificateCollection clientCertificates;
+ X509CertificateCollection clientCertificates;
TcpClient client;
- NetworkStream stream;
+ Stream stream;
StreamWriter writer;
StreamReader reader;
int boundaryIndex;
MailAddress defaultFrom;
+ MailMessage messageInProcess;
+
+ BackgroundWorker worker;
+ object user_async_state;
+
// ESMTP state
enum AuthMechs {
None = 0,
Login = 0x10,
Plain = 0x20,
}
-
+
+ class CancellationException : Exception
+ {
+ }
+
AuthMechs authMechs = AuthMechs.None;
bool canStartTLS = false;
#region Properties
- [MonoTODO("Client certificates are not supported")]
+#if SECURITY_DEP
+ [MonoTODO("STARTTLS is not supported yet")]
public X509CertificateCollection ClientCertificates {
get {
- throw new NotImplementedException ("Client certificates are not supported");
- //return clientCertificates;
+ if (clientCertificates == null)
+ clientCertificates = new X509CertificateCollection ();
+ return clientCertificates;
}
}
+#endif
public ICredentialsByHost Credentials {
get { return credentials; }
- set { credentials = value; }
+ set {
+ CheckState ();
+ credentials = value;
+ }
}
public SmtpDeliveryMethod DeliveryMethod {
get { return deliveryMethod; }
- set { deliveryMethod = value; }
+ set {
+ CheckState ();
+ deliveryMethod = value;
+ }
}
+ [MonoTODO("STARTTLS is not supported yet")]
public bool EnableSsl {
// FIXME: So... is this supposed to enable SSL port functionality? or STARTTLS? Or both?
get { return enableSsl; }
- set { enableSsl = value; }
+ set {
+ CheckState ();
+ enableSsl = value;
+ }
}
public string Host {
get { return host; }
- // FIXME: Check to make sure an email is not being sent.
set {
if (value == null)
throw new ArgumentNullException ();
if (value.Length == 0)
throw new ArgumentException ();
+ CheckState ();
host = value;
}
}
public int Port {
get { return port; }
- // FIXME: Check to make sure an email is not being sent.
set {
if (value <= 0 || value > 65535)
throw new ArgumentOutOfRangeException ();
+ CheckState ();
port = value;
}
}
+ [MonoTODO]
public ServicePoint ServicePoint {
get { throw new NotImplementedException (); }
}
public int Timeout {
get { return timeout; }
- // FIXME: Check to make sure an email is not being sent.
set {
if (value < 0)
throw new ArgumentOutOfRangeException ();
+ CheckState ();
timeout = value;
}
}
public bool UseDefaultCredentials {
get { return useDefaultCredentials; }
- set { throw new NotImplementedException ("Default credentials are not supported"); }
+ [MonoNotSupported ("no DefaultCredential support in Mono")]
+ set {
+ if (value)
+ throw new NotImplementedException ("Default credentials are not supported");
+ CheckState ();
+ }
}
#endregion // Properties
#region Methods
+ private void CheckState ()
+ {
+ if (messageInProcess != null)
+ throw new InvalidOperationException ("Cannot set Timeout while Sending a message");
+ }
+
+ private string EncodeSubjectRFC2047 (MailMessage message)
+ {
+ return ContentType.EncodeSubjectRFC2047 (message.Subject, message.SubjectEncoding);
+ }
+
+ private string EncodeBody (MailMessage message)
+ {
+ string body = message.Body;
+ // RFC 2045 encoding
+ switch (message.ContentTransferEncoding) {
+ case TransferEncoding.SevenBit:
+ return body;
+ case TransferEncoding.Base64:
+ return Convert.ToBase64String (message.BodyEncoding.GetBytes (body));
+ default:
+ return ToQuotedPrintable (body, message.BodyEncoding);
+ }
+ }
+
private void EndSection (string section)
{
SendData (String.Format ("--{0}--", section));
protected void OnSendCompleted (AsyncCompletedEventArgs e)
{
- if (SendCompleted != null)
- SendCompleted (this, e);
+ try {
+ if (SendCompleted != null)
+ SendCompleted (this, e);
+ } finally {
+ worker = null;
+ user_async_state = null;
+ }
+ }
+
+ private void CheckCancellation ()
+ {
+ if (worker != null && worker.CancellationPending)
+ throw new CancellationException ();
}
private SmtpResponse Read () {
bool lastLine = false;
do {
+ CheckCancellation ();
+
int readLength = stream.Read (buffer, position, buffer.Length - position);
if (readLength > 0) {
int available = position + readLength - 1;
public void Send (MailMessage message)
{
+ if (message == null)
+ throw new ArgumentNullException ("message");
+
if (String.IsNullOrEmpty (Host))
throw new InvalidOperationException ("The SMTP host was not specified");
// Block while sending
mutex.WaitOne ();
+ try {
+ messageInProcess = message;
+ SendCore (message);
+ } catch (CancellationException) {
+ // This exception is introduced for convenient cancellation process.
+ } finally {
+ // Release the mutex to allow other threads access
+ mutex.ReleaseMutex ();
+ messageInProcess = null;
+ }
+Console.WriteLine ("Send() completed");
+ }
+ private void SendCore (MailMessage message)
+ {
SmtpResponse status;
+ CheckCancellation ();
+
client = new TcpClient (host, port);
stream = client.GetStream ();
+ // FIXME: this StreamWriter creation is bogus.
+ // It expects as if a Stream were able to switch to SSL
+ // mode (such behavior is only in Mainsoft Socket API).
writer = new StreamWriter (stream);
reader = new StreamReader (stream);
}
if (enableSsl) {
+#if old_comment
// FIXME: I get the feeling from the docs that EnableSsl is meant
// for using the SSL-port and not STARTTLS (or, if it includes
// STARTTLS... only use STARTTLS if the SSL-type in the certificate
// FIXME: even tho we have a canStartTLS flag... ignore it for now
// so that the STARTTLS command can throw the appropriate
// SmtpException if STARTTLS is unavailable
+#else
+ // SmtpClient implements STARTTLS support.
+#endif
InitiateSecureConnection ();
// FIXME: re-EHLO?
throw new SmtpException (status.StatusCode, status.Description);
// Send message headers
+ SendHeader (HeaderName.Date, DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo));
SendHeader (HeaderName.From, from.ToString ());
SendHeader (HeaderName.To, message.To.ToString ());
if (message.CC.Count > 0)
SendHeader (HeaderName.Cc, message.CC.ToString ());
- SendHeader (HeaderName.Subject, message.Subject);
+ SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
foreach (string s in message.Headers.AllKeys)
SendHeader (s, message.Headers [s]);
AddPriorityHeader (message);
- bool hasAlternateViews = (message.AlternateViews.Count > 0);
- bool hasAttachments = (message.Attachments.Count > 0);
-
- if (hasAttachments || hasAlternateViews) {
- SendMultipartBody (message);
- } else {
- SendSimpleBody (message);
- }
+ boundaryIndex = 0;
+ if (message.Attachments.Count > 0)
+ SendWithAttachments (message);
+ else
+ SendWithoutAttachments (message, null);
SendData (".");
reader.Close ();
stream.Close ();
client.Close ();
-
- // Release the mutex to allow other threads access
- mutex.ReleaseMutex ();
}
public void Send (string from, string to, string subject, string body)
private void SendData (string data)
{
- writer.Write (data);
+ CheckCancellation ();
+
// Certain SMTP servers will reject mail sent with unix line-endings; see http://cr.yp.to/docs/smtplf.html
+ StringBuilder sb = new StringBuilder (data);
+ sb.Replace ("\r\n", "\n");
+ sb.Replace ('\r', '\n');
+ sb.Replace ("\n", "\r\n");
+ writer.Write (sb.ToString ());
writer.Write ("\r\n");
writer.Flush ();
}
public void SendAsync (MailMessage message, object userToken)
{
- Send (message);
- OnSendCompleted (new AsyncCompletedEventArgs (null, false, userToken));
+ if (worker != null)
+ throw new InvalidOperationException ("Another SendAsync operation is in progress");
+
+ worker = new BackgroundWorker ();
+ worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
+ try {
+ user_async_state = ea.Argument;
+ Send (message);
+ } catch (Exception ex) {
+ ea.Result = ex;
+ }
+ };
+ worker.WorkerSupportsCancellation = true;
+ worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
+ // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
+ OnSendCompleted (new AsyncCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state));
+ };
+ worker.RunWorkerAsync (userToken);
}
public void SendAsync (string from, string to, string subject, string body, object userToken)
public void SendAsyncCancel ()
{
- throw new NotImplementedException ();
+ if (worker == null)
+ throw new InvalidOperationException ("SendAsync operation is not in progress");
+ worker.CancelAsync ();
}
private void AddPriorityHeader (MailMessage message) {
}
private void SendSimpleBody (MailMessage message) {
- SendHeader ("Content-Type", message.BodyContentType.ToString ());
+ SendHeader (HeaderName.ContentType, message.BodyContentType.ToString ());
+ if (message.ContentTransferEncoding != TransferEncoding.SevenBit)
+ SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (message.ContentTransferEncoding));
SendData (string.Empty);
- SendData (message.Body);
+ SendData (EncodeBody (message));
}
- private void SendMultipartBody (MailMessage message) {
- boundaryIndex = 0;
+ private void SendWithoutAttachments (MailMessage message, string boundary) {
+ if (message.AlternateViews.Count > 0)
+ SendBodyWithAlternateViews (message, boundary);
+ else
+ SendSimpleBody (message);
+ }
+
+
+ private void SendWithAttachments (MailMessage message) {
string boundary = GenerateBoundary ();
- // Figure out the message content type
- ContentType messageContentType = message.BodyContentType;
+ // first "multipart/mixed"
+ ContentType messageContentType = new ContentType ();
messageContentType.Boundary = boundary;
messageContentType.MediaType = "multipart/mixed";
+ messageContentType.CharSet = null;
- SendHeader ("Content-Type", messageContentType.ToString ());
- SendData (string.Empty);
+ SendHeader (HeaderName.ContentType, messageContentType.ToString ());
+ SendData (String.Empty);
- SendData (message.Body);
- SendData (string.Empty);
-
- message.AlternateViews.Add (AlternateView.CreateAlternateViewFromString (message.Body, new ContentType ("text/plain")));
+ // body section
+ Attachment body = null;
- if (message.AlternateViews.Count > 0) {
- SendAlternateViews (message, boundary);
+ if (message.AlternateViews.Count > 0)
+ SendWithoutAttachments (message, boundary);
+ else {
+ body = Attachment.CreateAttachmentFromString (message.Body, null, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
+ message.Attachments.Insert (0, body);
}
- if (message.Attachments.Count > 0) {
- SendAttachments (message, boundary);
+ try {
+ SendAttachments (message, body, boundary);
+ } finally {
+ if (body != null)
+ message.Attachments.Remove (body);
}
EndSection (boundary);
}
- private void SendAlternateViews (MailMessage message, string boundary) {
+ private void SendBodyWithAlternateViews (MailMessage message, string boundary) {
AlternateViewCollection alternateViews = message.AlternateViews;
string inner_boundary = GenerateBoundary ();
- ContentType messageContentType = message.BodyContentType;
+ ContentType messageContentType = new ContentType ();
messageContentType.Boundary = inner_boundary;
messageContentType.MediaType = "multipart/alternative";
StartSection (boundary, messageContentType);
- for (int i = 0; i < alternateViews.Count; i += 1) {
- ContentType contentType = new ContentType (alternateViews [i].ContentType.ToString ());
- StartSection (inner_boundary, contentType, alternateViews [i].TransferEncoding);
+ // body section
+ AlternateView body = AlternateView.CreateAlternateViewFromString (message.Body, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
+ alternateViews.Insert (0, body);
+try {
+ // alternate view sections
+ foreach (AlternateView av in alternateViews) {
+
+ string alt_boundary = null;
+ ContentType contentType;
+ if (av.LinkedResources.Count > 0) {
+ alt_boundary = GenerateBoundary ();
+ contentType = new ContentType ("multipart/related");
+ contentType.Boundary = alt_boundary;
+ contentType.Parameters ["type"] = "application/octet-stream";
+ StartSection (inner_boundary, contentType);
+ } else {
+ contentType = new ContentType (av.ContentType.ToString ());
+ StartSection (inner_boundary, contentType, av.TransferEncoding);
+ }
- switch (alternateViews [i].TransferEncoding) {
+ switch (av.TransferEncoding) {
case TransferEncoding.Base64:
- byte [] content = new byte [alternateViews [i].ContentStream.Length];
- alternateViews [i].ContentStream.Read (content, 0, content.Length);
+ byte [] content = new byte [av.ContentStream.Length];
+ av.ContentStream.Read (content, 0, content.Length);
#if TARGET_JVM
SendData (Convert.ToBase64String (content));
#else
#endif
break;
case TransferEncoding.QuotedPrintable:
- StreamReader sr = new StreamReader (alternateViews [i].ContentStream);
- SendData (ToQuotedPrintable (sr.ReadToEnd ()));
+ StreamReader sr = new StreamReader (av.ContentStream);
+ Encoding encoding = contentType.CharSet != null ? Encoding.GetEncoding (contentType.CharSet) : Encoding.ASCII;
+ SendData (ToQuotedPrintable (sr.ReadToEnd (), encoding));
break;
- //case TransferEncoding.SevenBit:
- //case TransferEncoding.Unknown:
- default:
- SendData ("TO BE IMPLEMENTED");
+ case TransferEncoding.SevenBit:
+ case TransferEncoding.Unknown:
+ content = new byte [av.ContentStream.Length];
+ SendData (Encoding.ASCII.GetString (content));
break;
}
- SendData (string.Empty);
+ if (av.LinkedResources.Count > 0) {
+ SendLinkedResources (message, av.LinkedResources, alt_boundary);
+ EndSection (alt_boundary);
+ }
+
+// SendData (string.Empty);
}
+} finally {
+ alternateViews.Remove (body);
+}
EndSection (inner_boundary);
}
- private void SendAttachments (MailMessage message, string boundary) {
- AttachmentCollection attachments = message.Attachments;
+ private void SendLinkedResources (MailMessage message, LinkedResourceCollection resources, string boundary)
+ {
+ foreach (LinkedResource lr in resources) {
+ ContentType contentType = new ContentType (lr.ContentType.ToString ());
+ StartSection (boundary, contentType, lr.TransferEncoding);
- for (int i = 0; i < attachments.Count; i += 1) {
- ContentType contentType = new ContentType (attachments [i].ContentType.ToString ());
- attachments [i].ContentDisposition.FileName = attachments [i].Name;
- StartSection (boundary, contentType, attachments [i].TransferEncoding, attachments [i].ContentDisposition);
+ switch (lr.TransferEncoding) {
+ case TransferEncoding.Base64:
+ byte [] content = new byte [lr.ContentStream.Length];
+ lr.ContentStream.Read (content, 0, content.Length);
+#if TARGET_JVM
+ SendData (Convert.ToBase64String (content));
+#else
+ SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
+#endif
+ break;
+ case TransferEncoding.QuotedPrintable:
+ StreamReader sr = new StreamReader (lr.ContentStream);
+ Encoding encoding = contentType.CharSet != null ? Encoding.GetEncoding (contentType.CharSet) : Encoding.ASCII;
+ SendData (ToQuotedPrintable (sr.ReadToEnd (), encoding));
+ break;
+ case TransferEncoding.SevenBit:
+ case TransferEncoding.Unknown:
+ content = new byte [lr.ContentStream.Length];
+ SendData (Encoding.ASCII.GetString (content));
+ break;
+ }
+ }
+ }
+
+ private void SendAttachments (MailMessage message, Attachment body, string boundary) {
+ foreach (Attachment att in message.Attachments) {
+ ContentType contentType = new ContentType (att.ContentType.ToString ());
+ if (att.Name != null) {
+ contentType.Name = att.Name;
+ if (att.NameEncoding != null)
+ contentType.CharSet = att.NameEncoding.HeaderName;
+ att.ContentDisposition.FileName = att.Name;
+ }
+ StartSection (boundary, contentType, att.TransferEncoding, att == body ? null : att.ContentDisposition);
- switch (attachments [i].TransferEncoding) {
+ switch (att.TransferEncoding) {
case TransferEncoding.Base64:
- byte[] content = new byte [attachments [i].ContentStream.Length];
- attachments [i].ContentStream.Read (content, 0, content.Length);
+ byte [] content = new byte [att.ContentStream.Length];
+ att.ContentStream.Read (content, 0, content.Length);
#if TARGET_JVM
SendData (Convert.ToBase64String (content));
#else
#endif
break;
case TransferEncoding.QuotedPrintable:
- StreamReader sr = new StreamReader (attachments [i].ContentStream);
- SendData (ToQuotedPrintable (sr.ReadToEnd ()));
+ StreamReader sr = new StreamReader (att.ContentStream);
+ Encoding encoding = contentType.CharSet != null ? Encoding.GetEncoding (contentType.CharSet) : Encoding.ASCII;
+ SendData (ToQuotedPrintable (sr.ReadToEnd (), encoding));
break;
- //case TransferEncoding.SevenBit:
- //case TransferEncoding.Unknown:
- default:
- SendData ("TO BE IMPLEMENTED");
+ case TransferEncoding.SevenBit:
+ case TransferEncoding.Unknown:
+ content = new byte [att.ContentStream.Length];
+ SendData (Encoding.ASCII.GetString (content));
break;
}
SendData (String.Format ("--{0}", section));
SendHeader ("content-type", sectionContentType.ToString ());
SendHeader ("content-transfer-encoding", GetTransferEncodingName (transferEncoding));
- SendHeader ("content-disposition", contentDisposition.ToString ());
+ if (contentDisposition != null)
+ SendHeader ("content-disposition", contentDisposition.ToString ());
SendData (string.Empty);
}
- private string ToQuotedPrintable (string input) {
- StringReader reader = new StringReader (input);
+ // use proper encoding to escape input
+ private string ToQuotedPrintable (string input, Encoding enc) {
+ byte [] bytes = enc.GetBytes (input);
StringWriter writer = new StringWriter ();
- int i;
-
- while ((i = reader.Read ()) > 0) {
+ foreach (byte i in bytes) {
if (i > 127) {
writer.Write ("=");
writer.Write (Convert.ToString (i, 16).ToUpper ());
return "unknown";
}
+#if SECURITY_DEP
+ RemoteCertificateValidationCallback callback = delegate (object sender,
+ X509Certificate certificate,
+ X509Chain chain,
+ SslPolicyErrors sslPolicyErrors) {
+ if (sslPolicyErrors != SslPolicyErrors.None)
+ throw new InvalidOperationException ("SSL authentication error: " + sslPolicyErrors);
+ return true;
+ };
+#endif
+
private void InitiateSecureConnection () {
SmtpResponse response = SendCommand ("STARTTLS");
throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
}
- ChangeToSSLSocket ();
- }
-
- private bool ChangeToSSLSocket () {
#if TARGET_JVM
- stream.ChangeToSSLSocket ();
+ ((NetworkStream) stream).ChangeToSSLSocket ();
+#elif SECURITY_DEP
+ SslStream sslStream = new SslStream (stream, false, callback, null);
+ CheckCancellation ();
+ sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
+ stream = sslStream;
- return true;
-#else
throw new NotImplementedException ();
+#else
+ throw new SystemException ("You are using an incomplete System.dll build");
#endif
}
}
}
- /*[MonoTODO]
- private sealed ContextAwareResult IGetContextAwareResult.GetContextAwareResult ()
- {
- throw new NotImplementedException ();
- }*/
-
#endregion // Methods
// The HeaderName struct is used to store constant string values representing mail headers.
public const string Priority = "Priority";
public const string Importance = "Importance";
public const string XPriority = "X-Priority";
+ public const string Date = "Date";
}
// This object encapsulates the status code and description of an SMTP response.
#region Constructors
public SmtpException ()
+ : this ("SMTP error occured")
{
}
public SmtpException (SmtpStatusCode statusCode)
+ : this ()
{
StatusCode = statusCode;
}
protected SmtpException (SerializationInfo info, StreamingContext context)
: base (info, context)
{
+ if (info == null)
+ throw new ArgumentNullException ("info");
+ StatusCode = (SmtpStatusCode) info.GetValue ("statusCode", typeof (SmtpStatusCode));
}
public SmtpException (SmtpStatusCode statusCode, string message)
#endregion // Properties
- [MonoTODO]
public override void GetObjectData (SerializationInfo info, StreamingContext context)
{
+ if (info == null)
+ throw new ArgumentNullException ("info");
+ info.AddValue ("statusCode", statusCode, typeof (SmtpStatusCode));
}
#if !TARGET_JVM //remove private implementation
- [MonoTODO]
void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
{
+ GetObjectData (info, context);
}
#endif
}
{
}
- [MonoTODO]
protected SmtpFailedRecipientException (SerializationInfo serializationInfo, StreamingContext streamingContext)
{
+ if (serializationInfo == null)
+ throw new ArgumentNullException ("serializationInfo");
+ failedRecipient = serializationInfo.GetString ("failedRecipient");
}
public SmtpFailedRecipientException (SmtpStatusCode statusCode, string failedRecipient) : base (statusCode)
#region Methods
- [MonoTODO]
public override void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
{
+ if (serializationInfo == null)
+ throw new ArgumentNullException ("serializationInfo");
+ serializationInfo.AddValue ("failedRecipient", failedRecipient);
}
#if !TARGET_JVM //remove private implementation
- [MonoTODO]
void ISerializable.GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
{
+ GetObjectData (serializationInfo, streamingContext);
}
#endif
this.innerExceptions = innerExceptions;
}
- [MonoTODO]
protected SmtpFailedRecipientsException (SerializationInfo info, StreamingContext context)
{
+ if (info == null)
+ throw new ArgumentNullException ("info");
+ innerExceptions = (SmtpFailedRecipientException []) info.GetValue ("innerExceptions", typeof (SmtpFailedRecipientException []));
}
#endregion
#region Methods
- [MonoTODO]
public override void GetObjectData (SerializationInfo info, StreamingContext context)
{
+ if (info == null)
+ throw new ArgumentNullException ("info");
+ info.AddValue ("innerExceptions", innerExceptions);
}
#if !TARGET_JVM //remove private implementation
- [MonoTODO]
void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
{
+ GetObjectData (info, context);
}
#endif
+2007-10-22 Atsushi Enomoto <atsushi@ximian.com>
+
+ * ContentType.cs : moved couple of encoding stuff to here.
+ Encode non-ASCII value in RFC 2047.
+
2007-09-28 Marek Habersack <mhabersack@novell.com>
* ContentDisposition.cs: if the file name contains spaces, enclose
public override string ToString ()
{
StringBuilder sb = new StringBuilder ();
+ Encoding enc = CharSet != null ? Encoding.GetEncoding (CharSet) : Encoding.UTF8;
sb.Append (MediaType);
if (Parameters != null && Parameters.Count > 0) {
foreach (DictionaryEntry pair in parameters)
sb.Append ("; ");
sb.Append (pair.Key);
sb.Append ("=");
- sb.Append (pair.Value);
+ sb.Append (EncodeSubjectRFC2047 (pair.Value as string, enc));
}
}
}
return sb.ToString ();
}
+ internal static Encoding GuessEncoding (string s)
+ {
+ for (int i = 0; i < s.Length; i++)
+ if (s [i] >= '\u0080')
+ return Encoding.UTF8;
+ return Encoding.ASCII;
+ }
+
+ internal static string EncodeSubjectRFC2047 (string s, Encoding enc)
+ {
+ if (s == null || Encoding.ASCII.Equals (enc))
+ return s;
+ for (int i = 0; i < s.Length; i++)
+ if (s [i] >= '\u0080') {
+ string b64 = Convert.ToBase64String (enc.GetBytes (s));
+ return String.Concat ("=?", enc.HeaderName, "?B?", b64, "?=");
+ }
+ return s;
+ }
+
#endregion // Methods
}
}
+2007-10-21 Robert Jordan <robertj@gmx.net>
+
+ * Socket.cs: Remove GetHashCode override from the NET_2_0
+ profile. Add LAMESPEC comment. Fixes bug #325113.
+
2007-09-22 Gert Driesen <drieseng@users.sourceforge.net>
* Socket.cs: Removed unused method.
throw new SocketException (error);
}
+#if ONLY_1_1
public override int GetHashCode ()
{
+ // LAMESPEC:
+ // The socket is not suitable to serve as a hash code,
+ // because it will change during its lifetime, but
+ // this is how MS.NET 1.1 implemented this method.
return (int) socket;
}
+#endif
protected virtual void Dispose (bool explicitDisposing)
{
+2007-10-15 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * FtpWebRequest.cs: Added support for DELETE.
+
+2007-10-15 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * WebRequest.cs: Changed serialization ctor to throw NIE on 1.0
+ profile. Cache default proxy, but still allow it to be explicitly set
+ to null. Removed commented code.
+
+2007-10-14 Gonzalo Paniagua Javier <gonzalo.mono@gmail.com>
+
+ * WebRequest.cs: DefaultWebProxy allows a null value. Fixes bug #323668.
+
2007-09-30 Gert Driesen <drieseng@users.sourceforge.net>
* HttpListenerRequest.cs: Do not store 'method' in upper case, but
case WebRequestMethods.Ftp.PrintWorkingDirectory:
case WebRequestMethods.Ftp.MakeDirectory:
case WebRequestMethods.Ftp.Rename:
+ case WebRequestMethods.Ftp.DeleteFile:
ProcessSimpleMethod ();
break;
default: // What to do here?
if (status.StatusCode != FtpStatusCode.FileActionOK)
throw CreateExceptionFromResponse (status);
break;
+ case WebRequestMethods.Ftp.DeleteFile:
+ if (status.StatusCode != FtpStatusCode.FileActionOK)
+ throw CreateExceptionFromResponse (status);
+ break;
}
ftpResponse.UpdateStatus (status);
\r
\r
#endregion\r
+#if NET_2_0\r
+ public DecompressionMethods AutomaticDecompression\r
+ {\r
+ get {\r
+ throw new NotSupportedException ();\r
+ }\r
+ set {\r
+ throw new NotSupportedException ();\r
+ }\r
+ }\r
+#endif\r
\r
}\r
}\r
public abstract class WebRequest : MarshalByRefObject, ISerializable
{
static HybridDictionary prefixes = new HybridDictionary ();
+#if NET_2_0
+ static bool isDefaultWebProxySet;
+ static IWebProxy defaultWebProxy;
+#endif
// Constructors
protected WebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
{
+#if ONLY_1_1
+ throw GetMustImplement ();
+#endif
}
static Exception GetMustImplement ()
}
#endif
- public virtual string ConnectionGroupName {
+ public virtual string ConnectionGroupName {
get { throw GetMustImplement (); }
set { throw GetMustImplement (); }
}
public static IWebProxy DefaultWebProxy {
get {
- lock (lockobj) {
- if (proxy == null)
- proxy = GetDefaultWebProxy ();
- return proxy;
+ if (!isDefaultWebProxySet) {
+ lock (lockobj) {
+ if (defaultWebProxy == null)
+ defaultWebProxy = GetDefaultWebProxy ();
+ }
}
+ return defaultWebProxy;
}
set {
- if (value == null)
- throw new ArgumentNullException ("WebRequest.DefaultWebProxy",
- "null IWebProxy not allowed.");
- proxy = value;
+ /* MS documentation states that a null value would cause an ArgumentNullException
+ * but that's not the way it behaves:
+ * https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304724
+ */
+ defaultWebProxy = value;
+ isDefaultWebProxySet = true;
}
}
p.BypassProxyOnLocal = (pe.BypassOnLocal == ProxyElement.BypassOnLocalValues.True);
#endif
return p;
- }
+ }
#endif
// Methods
public static bool RegisterPrefix (string prefix, IWebRequestCreate creator)
{
if (prefix == null)
- throw new ArgumentNullException("prefix");
+ throw new ArgumentNullException ("prefix");
if (creator == null)
- throw new ArgumentNullException("creator");
+ throw new ArgumentNullException ("creator");
lock (prefixes.SyncRoot) {
string lowerCasePrefix = prefix.ToLower (CultureInfo.InvariantCulture);
continue;
if (!prefix.StartsWith (key))
- continue;
+ continue;
longestPrefix = key.Length;
creator = (IWebRequestCreate) e.Value;
+2007-10-21 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * RegexTest.cs: Removed. Test was already moved to the appropriate
+ location.
+
2007-06-21 Juraj Skripsky <js@hotfeet.ch>
- * quicksearch.ch: Optimization. Add byte array as skip table for
- chars <= 255, falling back to the hashtable for chars > 255 and
- skip distances > 255.
+ * quicksearch.ch: Optimization. Add byte array as skip table for
+ chars <= 255, falling back to the hashtable for chars > 255 and
+ skip distances > 255.
2007-04-18 Raja R Harinath <rharinath@novell.com>
+++ /dev/null
-//
-// assembly: System_test
-// namespace: MonoTests.System.Text.RegularExpressions
-// file: RegexTest.cs
-//
-// Authors:
-// Juraj Skripsky (juraj@hotfeet.ch)
-//
-// (c) 2003 Juraj Skripsky
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Text.RegularExpressions;
-
-using NUnit.Framework;
-
-namespace MonoTests.System.Text.RegularExpressions {
-
- [TestFixture]
- public class RegexTest {
-
- [Test]
- public void Simple () {
- char[] c = { (char)32, (char)8212, (char)32 };
- string s = new String(c);
- Assertion.AssertEquals ("char", true, Regex.IsMatch(s, s));
- }
- }
-}
<Compile Include="System.Net\CookieException.cs" />\r
<Compile Include="System.Net\CredentialCache.cs" />\r
<Compile Include="System.Net\DefaultCertificatePolicy.cs" />\r
+ <Compile Include="System.Net\DecompressionMethods.cs" />\r
<Compile Include="System.Net\DigestClient.cs" />\r
<Compile Include="System.Net\Dns.cs">\r
<SubType>Code</SubType>\r
+2007-10-21 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * SwitchesTest.cs: Fixed compiler warning.
+
2007-09-22 Gert Driesen <drieseng@users.sourceforge.net>
* DiagnosticsConfigurationHandlerTest.cs: No longer derive from
// ensure that the .config file is read in
int n = base.SwitchSetting;
// remove warning about unused variable
- n = n;
+ n = 5;
return v;
}
}
Assert.IsTrue (av.ContentType.MediaType == "text/plain");
}
+ [Test]
+ public void ContentType2 ()
+ {
+ AlternateView av = new AlternateView (new MemoryStream ());
+ Assert.IsNotNull (av.ContentType, "#1");
+ Assert.AreEqual ("application/octet-stream", av.ContentType.MediaType, "#2");
+ }
+
[Test]
public void ContentStream ()
{
}
[Test]
- public void TransferEncoding ()
+ public void TransferEncodingTest ()
{
- //Assert.IsTrue (av.TransferEncoding = TransferEncoding.QuotedPrintable);
+ Assert.AreEqual (TransferEncoding.QuotedPrintable, av.TransferEncoding, "#1");
+
+ MemoryStream ms = new MemoryStream (new byte [] {1, 2, 3});
+ Assert.AreEqual (TransferEncoding.Base64, new AlternateView (ms).TransferEncoding, "#2");
+ Assert.AreEqual (TransferEncoding.Base64, new AlternateView (ms, "text/plain").TransferEncoding, "#3");
}
}
}
using System.IO;
using System.Text;
using System.Net.Mail;
+using System.Net.Mime;
namespace MonoTests.System.Net.Mail
{
[SetUp]
public void GetReady ()
{
- attach = Attachment.CreateAttachmentFromString ("test", "text/plain");
+ attach = Attachment.CreateAttachmentFromString ("test", "attachment-name");
}
[Test]
new Attachment (s, "application/octet-stream");
}
+ [Test]
+ public void ConstructorNullName ()
+ {
+ new Attachment (new MemoryStream (), null, "application/octet-stream");
+ }
+
+ [Test]
+ public void CreateAttachmentFromStringNullName ()
+ {
+ Attachment.CreateAttachmentFromString ("", null, Encoding.ASCII, "application/octet-stream");
+ }
+
[Test]
public void ContentDisposition ()
{
- Assert.IsNotNull (attach.ContentDisposition);
- Assert.IsTrue (attach.ContentDisposition.DispositionType == "attachment");
+ Assert.IsNotNull (attach.ContentDisposition, "#1");
+ Assert.AreEqual ("attachment", attach.ContentDisposition.DispositionType, "#2");
}
[Test]
public void ContentType ()
{
- Assert.IsNotNull (attach.ContentType);
- Assert.IsTrue (attach.ContentType.MediaType == "text/plain");
+ Assert.IsNotNull (attach.ContentType, "#1");
+ Assert.AreEqual ("text/plain", attach.ContentType.MediaType, "#2");
+ Attachment a2 = new Attachment (new MemoryStream (), "myname");
+ Assert.IsNotNull (a2.ContentType, "#1");
+ Assert.AreEqual ("application/octet-stream", a2.ContentType.MediaType, "#2");
}
[Test]
public void NameEncoding ()
{
- Assert.IsNull (attach.NameEncoding);
+ Assert.IsNull (attach.NameEncoding, "#1");
+ Attachment a = new Attachment (new MemoryStream (), "myname");
+ Assert.IsNull (a.NameEncoding, "#2");
+ a = new Attachment (new MemoryStream (), "myname\u3067");
+ Assert.IsNull (a.NameEncoding, "#3");
}
[Test]
}
- /*[Test]
+ [Test]
public void Name ()
{
- Assert.IsNotNull (attach.Name);
+ Assert.AreEqual ("attachment-name", attach.Name, "#1");
+ Attachment a2 = new Attachment (new MemoryStream (), new ContentType ("image/jpeg"));
+ Assert.AreEqual (null, a2.Name, "#2");
+ a2.Name = null; // nullable
}
[Test]
- public void TransferEncoding ()
+ public void TransferEncodingTest ()
{
- Assert.IsTrue (attach.TransferEncoding == MimeTransferEncoding.Base64);
- }*/
+ Assert.AreEqual (TransferEncoding.QuotedPrintable, attach.TransferEncoding);
+ }
}
}
#endif
+2007-10-23 Atsushi Enomoto <atsushi@ximian.com>
+
+ * AttachmentTest.cs : more NameEncoding tests.
+
+2007-10-22 Atsushi Enomoto <atsushi@ximian.com>
+
+ * AttachmentTest.cs : I have no time to fix it now. Disable it.
+
+2007-10-22 Atsushi Enomoto <atsushi@ximian.com>
+
+ * LinkedResourceTest.cs : removed NotWorking.
+
+2007-10-22 Atsushi Enomoto <atsushi@ximian.com>
+
+ * AttachmentTest.cs : test for null names.
+
+2007-10-22 Atsushi Enomoto <atsushi@ximian.com>
+
+ * LinkedResourceTest.cs : NotWorking, buildbot loudly claims for
+ unimplemented stuff.
+
+2007-10-19 Atsushi Enomoto <atsushi@ximian.com>
+
+ * AlternateViewTest.cs : default TransferEncoding value is more
+ complicated.
+
+2007-10-17 Atsushi Enomoto <atsushi@ximian.com>
+
+ * LinkedResourceTest.cs, AttachmentTest.cs, AlternateViewTest.cs:
+ added/enabled couple of attachment tests.
+
+2007-10-16 Atsushi Enomoto <atsushi@ximian.com>
+
+ * MailMessageTest.cs : added test for encoding guess.
+
2007-06-17 Gert Driesen <drieseng@users.sourceforge.net>
* MailAddressTest.cs: Added tests for ctors and specifying display
[TestFixture]
public class LinkedResourceTest
{
- //LinkedResource lr;
+ LinkedResource lr;
[SetUp]
public void GetReady ()
{
- //lr = LinkedResource.CreateLinkedResourceFromString ("test", new ContentType ("text/plain"));
+ lr = LinkedResource.CreateLinkedResourceFromString ("test", new ContentType ("text/plain"));
}
[Test]
}
[Test]
- public void TransferEncoding ()
+ public void TransferEncodingTest ()
{
- //Assert.IsTrue (lr.TransferEncoding = TransferEncoding.QuotedPrintable);
+ Assert.AreEqual (TransferEncoding.QuotedPrintable, lr.TransferEncoding);
}
}
}
Assert.AreEqual (msg.To[0].Address, "to@example.com", "#B2");
Assert.AreEqual (msg.To[1].Address, "you@nowhere.com", "#B3");
}
+
+ [Test]
+ public void BodyAndEncoding ()
+ {
+ MailMessage msg = new MailMessage ("from@example.com", "to@example.com");
+ Assert.AreEqual (null, msg.BodyEncoding, "#1");
+ msg.Body = "test";
+ Assert.AreEqual (Encoding.ASCII, msg.BodyEncoding, "#2");
+ msg.Body = "test\u3067\u3059";
+ Assert.AreEqual (Encoding.ASCII, msg.BodyEncoding, "#3");
+ msg.BodyEncoding = null;
+ msg.Body = "test\u3067\u3059";
+ Assert.AreEqual (Encoding.UTF8, msg.BodyEncoding, "#4");
+ }
+
+ [Test]
+ public void SubjectAndEncoding ()
+ {
+ MailMessage msg = new MailMessage ("from@example.com", "to@example.com");
+ Assert.AreEqual (null, msg.SubjectEncoding, "#1");
+ msg.Subject = "test";
+ Assert.AreEqual (Encoding.ASCII, msg.SubjectEncoding, "#2");
+ msg.Subject = "test\u3067\u3059";
+ Assert.AreEqual (Encoding.ASCII, msg.SubjectEncoding, "#3");
+ msg.SubjectEncoding = null;
+ msg.Subject = "test\u3067\u3059";
+ Assert.AreEqual (Encoding.UTF8, msg.SubjectEncoding, "#4");
+ }
}
}
#endif
+2007-10-21 Robert Jordan <robertj@gmx.net>
+
+ * SocketTest.cs: Enable GetHashCodeTest.
+
2007-08-15 Gert Driesen <drieseng@users.sourceforge.net>
* SocketTest.cs: Improved EndConnect test. Added test for bug #82446,
}
[Test]
-#if NET_2_0
- [Category ("NotWorking")] // bug #82446
-#endif
public void GetHashCodeTest ()
{
Socket server = new Socket (AddressFamily.InterNetwork,
+2007-10-21 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * WebProxyTest.cs: Remove unused fields.
+
+2007-10-15 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * WebRequestTest.cs: Fixed test for serialization ctor to match
+ 1.0 profile change. Added trivial tests to argument null checks.
+ Added test for DefaultWebProxy. Fixed line endings.
+
2007-09-30 Gert Driesen <drieseng@users.sourceforge.net>
* HttpListenerRequestTest.cs: Added test for HttpMethod.
[TestFixture]
public class WebProxyTest
{
- private Uri googleUri;
- private Uri yahooUri;
- private Uri apacheUri;
-
- [SetUp]
- public void GetReady ()
- {
- googleUri = new Uri ("http://www.google.com");
- yahooUri = new Uri ("http://www.yahoo.com");
- apacheUri = new Uri ("http://www.apache.org");
- }
-
[Test]
public void Constructors ()
{
[Test]\r
public void SerializationConstructor ()\r
{\r
+#if NET_2_0\r
NonAbstractWebRequest w = new NonAbstractWebRequest (null, new StreamingContext ());\r
Assert.IsNotNull (w);\r
+#else\r
+ try {\r
+ new NonAbstractWebRequest (null, new StreamingContext ());\r
+ Assert.Fail ("#1");\r
+ } catch (NotImplementedException) {\r
+ }\r
+#endif\r
}\r
\r
// properties (only test 'get'ter)\r
}\r
\r
[Test]\r
- public void All ()\r
- {\r
+ public void All ()\r
+ {\r
WebRequest req = WebRequest.Create ("http://www.contoso.com");\r
Assertion.Assert ("#1", req is HttpWebRequest);\r
req = WebRequest.Create ("https://www.contoso.com");\r
\r
try {\r
req = WebRequest.Create ("tcp://www.contoso.com");\r
- Assertion.Fail ("#11 should have failed with NotSupportedException"); \r
- } catch (NotSupportedException) { \r
- } \r
+ Assertion.Fail ("#11 should have failed with NotSupportedException");\r
+ } catch (NotSupportedException) {\r
+ }\r
}\r
- \r
+\r
+ [Test]\r
+ public void Create_RequestUriString_Null ()\r
+ {\r
+ try {\r
+ WebRequest.Create ((string) null);\r
+ Assert.Fail ("#1");\r
+ } catch (ArgumentNullException ex) {\r
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");\r
+ Assert.IsNull (ex.InnerException, "#3");\r
+ Assert.IsNotNull (ex.Message, "#4");\r
+ Assert.IsNotNull (ex.ParamName, "#5");\r
+ Assert.AreEqual ("requestUriString", ex.ParamName, "#6");\r
+ }\r
+ }\r
+\r
+ [Test]\r
+ public void CreateDefault_RequestUri_Null ()\r
+ {\r
+ try {\r
+ WebRequest.CreateDefault ((Uri) null);\r
+ Assert.Fail ("#1");\r
+ } catch (ArgumentNullException ex) {\r
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");\r
+ Assert.IsNull (ex.InnerException, "#3");\r
+ Assert.IsNotNull (ex.Message, "#4");\r
+ Assert.IsNotNull (ex.ParamName, "#5");\r
+ Assert.AreEqual ("requestUri", ex.ParamName, "#6");\r
+ }\r
+ }\r
+\r
+#if NET_2_0\r
+ [Test]\r
+ public void DefaultWebProxy ()\r
+ {\r
+ WebProxy proxy = new WebProxy ("proxy.intern.com", 83);\r
+\r
+ WebRequest.DefaultWebProxy = proxy;\r
+ Assert.IsNotNull (WebRequest.DefaultWebProxy, "#A1");\r
+ Assert.AreSame (proxy, WebRequest.DefaultWebProxy, "#A2");\r
+\r
+ HttpWebRequest req = (HttpWebRequest) WebRequest.CreateDefault (\r
+ new Uri ("http://www.mono-project.com"));\r
+ Assert.IsNotNull (req.Proxy, "#B1");\r
+ Assert.AreSame (proxy, req.Proxy, "#B2");\r
+\r
+ WebRequest.DefaultWebProxy = null;\r
+ Assert.IsNull (WebRequest.DefaultWebProxy, "#C1");\r
+ Assert.IsNotNull (req.Proxy, "#C2");\r
+ Assert.AreSame (proxy, req.Proxy, "#C3");\r
+\r
+ req = (HttpWebRequest) WebRequest.CreateDefault (\r
+ new Uri ("http://www.mono-project.com"));\r
+ Assert.IsNull (req.Proxy, "#D");\r
+ }\r
+#endif\r
+\r
+ [Test]\r
+ public void RegisterPrefix_Creator_Null ()\r
+ {\r
+ try {\r
+ WebRequest.RegisterPrefix ("http://www.mono-project.com", (IWebRequestCreate) null);\r
+ Assert.Fail ("#1");\r
+ } catch (ArgumentNullException ex) {\r
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");\r
+ Assert.IsNull (ex.InnerException, "#3");\r
+ Assert.IsNotNull (ex.Message, "#4");\r
+ Assert.IsNotNull (ex.ParamName, "#5");\r
+ Assert.AreEqual ("creator", ex.ParamName, "#6");\r
+ }\r
+ }\r
+\r
+ [Test]\r
+ public void RegisterPrefix_Prefix_Null ()\r
+ {\r
+ try {\r
+ WebRequest.RegisterPrefix ((string) null, new TestWebRequestCreator ());\r
+ Assert.Fail ("#1");\r
+ } catch (ArgumentNullException ex) {\r
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");\r
+ Assert.IsNull (ex.InnerException, "#3");\r
+ Assert.IsNotNull (ex.Message, "#4");\r
+ Assert.IsNotNull (ex.ParamName, "#5");\r
+ Assert.AreEqual ("prefix", ex.ParamName, "#6");\r
+ }\r
+ }\r
+\r
internal class TestWebRequestCreator : IWebRequestCreate\r
{\r
internal TestWebRequestCreator () { }\r
+2007-10-21 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * RegexBugs.cs: No longer derive from deprecated Assertion class.
+ Added test for bug #313642.
+ * MatchTest.cs: Code formatting.
+ * RegexTest.cs: Fixed compiler warnings. Code formatting. Spaces to
+ tabs.
+
2007-09-17 Gert Driesen <drieseng@users.sourceforge.net>
* RegexReplace.cs: Fixed compiler warning.
using System;
using System.Text.RegularExpressions;
-namespace MonoTests.System.Text.RegularExpressions {
-
+namespace MonoTests.System.Text.RegularExpressions
+{
[TestFixture]
- public class MatchTest {
-
+ public class MatchTest
+ {
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Synchronized_Null ()
// (c) Copyright 2003,2004 Novell, Inc. (http://www.novell.com)
//
-using NUnit.Framework;
using System;
using System.Text;
using System.Text.RegularExpressions;
+using NUnit.Framework;
+
namespace MonoTests.System.Text.RegularExpressions
{
[TestFixture]
- public class RegexBugs : Assertion
+ public class RegexBugsn
{
- [Test]
- public void SplitGroup () // bug51146
+ [Test] // bug #51146
+ public void SplitGroup ()
{
- string [] splitResult = new Regex ("-").Split ("a-bcd-e-fg");
+ string [] splitResult = new Regex ("-").Split ("a-bcd-e-fg");
string [] expected = new string [] {"a", "bcd", "e", "fg"};
int length = expected.Length;
- int i;
- AssertEquals ("#01", length, splitResult.Length);
- for (i = 0; i < length; i++)
- AssertEquals ("#02 " + i, expected [i], splitResult [i]);
+ Assert.AreEqual (length, splitResult.Length, "#1");
+ for (int i = 0; i < length; i++)
+ Assert.AreEqual (expected [i], splitResult [i], "#2:" + i);
splitResult = new Regex ("(-)").Split ("a-bcd-e-fg");
expected = new string [] {"a", "-", "bcd", "-", "e", "-", "fg"};
length = expected.Length;
- AssertEquals ("#03", length, splitResult.Length);
- for (i = 0; i < length; i++)
- AssertEquals ("#04 " + i, expected [i], splitResult [i]);
+ Assert.AreEqual (length, splitResult.Length, "#3");
+ for (int i = 0; i < length; i++)
+ Assert.AreEqual (expected [i], splitResult [i], "#4:" + i);
splitResult = new Regex ("(-)b(c)").Split ("a-bcd-e-fg");
expected = new string [] {"a", "-", "c", "d-e-fg" };
length = expected.Length;
- AssertEquals ("#04", length, splitResult.Length);
- for (i = 0; i < length; i++)
- AssertEquals ("#05 " + i, expected [i], splitResult [i]);
+ Assert.AreEqual (length, splitResult.Length, "#5");
+ for (int i = 0; i < length; i++)
+ Assert.AreEqual (expected [i], splitResult [i], "#6:" + i);
splitResult = new Regex ("-").Split ("a-bcd-e-fg-");
expected = new string [] {"a", "bcd", "e", "fg", ""};
length = expected.Length;
- AssertEquals ("#06", length, splitResult.Length);
- for (i = 0; i < length; i++)
- AssertEquals ("#07 " + i, expected [i], splitResult [i]);
+ Assert.AreEqual (length, splitResult.Length, "#7");
+ for (int i = 0; i < length; i++)
+ Assert.AreEqual (expected [i], splitResult [i], "#8:" + i);
}
- [Test]
- public void MathEmptyGroup () // bug 42529
+ [Test] // bug #42529
+ public void MathEmptyGroup ()
{
string str = "Match something from here.";
- AssertEquals ("MEG #01", false, Regex.IsMatch(str, @"(something|dog)$"));
- AssertEquals ("MEG #02", true, Regex.IsMatch(str, @"(|something|dog)$"));
- AssertEquals ("MEG #03", true, Regex.IsMatch(str, @"(something||dog)$"));
- AssertEquals ("MEG #04", true, Regex.IsMatch(str, @"(something|dog|)$"));
-
- AssertEquals ("MEG #05", true, Regex.IsMatch(str, @"(something|dog)*"));
- AssertEquals ("MEG #06", true, Regex.IsMatch(str, @"(|something|dog)*"));
- AssertEquals ("MEG #07", true, Regex.IsMatch(str, @"(something||dog)*"));
- AssertEquals ("MEG #08", true, Regex.IsMatch(str, @"(something|dog|)*"));
+ Assert.IsFalse (Regex.IsMatch(str, @"(something|dog)$"), "#1");
+ Assert.IsTrue (Regex.IsMatch (str, @"(|something|dog)$"), "#2");
+ Assert.IsTrue (Regex.IsMatch (str, @"(something||dog)$"), "#3");
+ Assert.IsTrue (Regex.IsMatch (str, @"(something|dog|)$"), "#4");
- AssertEquals ("MEG #09", true, Regex.IsMatch(str, @"(something|dog)*$"));
- AssertEquals ("MEG #10", true, Regex.IsMatch(str, @"(|something|dog)*$"));
- AssertEquals ("MEG #11", true, Regex.IsMatch(str, @"(something||dog)*$"));
- AssertEquals ("MEG #12", true, Regex.IsMatch(str, @"(something|dog|)*$"));
+ Assert.IsTrue (Regex.IsMatch (str, @"(something|dog)*"), "#5");
+ Assert.IsTrue (Regex.IsMatch (str, @"(|something|dog)*"), "#6");
+ Assert.IsTrue (Regex.IsMatch (str, @"(something||dog)*"), "#7");
+ Assert.IsTrue (Regex.IsMatch (str, @"(something|dog|)*"), "#8");
+ Assert.IsTrue (Regex.IsMatch (str, @"(something|dog)*$"), "#9");
+ Assert.IsTrue (Regex.IsMatch (str, @"(|something|dog)*$"), "#10");
+ Assert.IsTrue (Regex.IsMatch (str, @"(something||dog)*$"), "#11");
+ Assert.IsTrue (Regex.IsMatch (str, @"(something|dog|)*$"), "#12");
}
- [Test]
- public void Braces () // bug 52924
+ [Test] // bug #52924
+ public void Braces ()
{
- // Before the fix, the next line throws an exception
Regex regVar = new Regex(@"{\w+}");
Match m = regVar.Match ("{ }");
- AssertEquals ("BR #01", false, m.Success);
+ Assert.IsFalse (m.Success);
}
- [Test]
- public void WhiteSpaceGroupped () // bug 71077
+ [Test] // bug #71077
+ public void WhiteSpaceGroupped ()
{
string s = "\n";
string p = @"[\s\S]"; // =Category.Any
-
- AssertEquals ("WSG#1", true, Regex.IsMatch (s, p));
+ Assert.IsTrue (Regex.IsMatch (s, p));
}
- [Test]
- public void RangeIgnoreCase() // bug 45976
- {
- string str = "AAABBBBAAA" ;
- AssertEquals("RIC #01", true, Regex.IsMatch(str, @"[A-F]+", RegexOptions.IgnoreCase));
- AssertEquals("RIC #02", true, Regex.IsMatch(str, @"[a-f]+", RegexOptions.IgnoreCase));
- AssertEquals("RIC #03", true, Regex.IsMatch(str, @"[A-Fa-f]+", RegexOptions.IgnoreCase));
- AssertEquals("RIC #04", true, Regex.IsMatch(str, @"[AB]+", RegexOptions.IgnoreCase));
- AssertEquals("RIC #05", true, Regex.IsMatch(str, @"[A-B]+", RegexOptions.IgnoreCase));
-
- str = "AaaBBBaAa" ;
- AssertEquals("RIC #06", true, Regex.IsMatch(str, @"[A-F]+", RegexOptions.IgnoreCase));
- AssertEquals("RIC #07", true, Regex.IsMatch(str, @"[a-f]+", RegexOptions.IgnoreCase));
- AssertEquals("RIC #08", true, Regex.IsMatch(str, @"[A-Fa-f]+", RegexOptions.IgnoreCase));
- AssertEquals("RIC #09", true, Regex.IsMatch(str, @"[AB]+", RegexOptions.IgnoreCase));
- AssertEquals("RIC #10", true, Regex.IsMatch(str, @"[A-B]+", RegexOptions.IgnoreCase));
+ [Test] // bug #45976
+ public void RangeIgnoreCase()
+ {
+ string str = "AAABBBBAAA" ;
+ Assert.IsTrue (Regex.IsMatch(str, @"[A-F]+", RegexOptions.IgnoreCase), "#A1");
+ Assert.IsTrue (Regex.IsMatch (str, @"[a-f]+", RegexOptions.IgnoreCase), "#A2");
+ Assert.IsTrue (Regex.IsMatch (str, @"[A-Fa-f]+", RegexOptions.IgnoreCase), "#A3");
+ Assert.IsTrue (Regex.IsMatch (str, @"[AB]+", RegexOptions.IgnoreCase), "#A4");
+ Assert.IsTrue (Regex.IsMatch (str, @"[A-B]+", RegexOptions.IgnoreCase), "#A5");
+
+ str = "AaaBBBaAa" ;
+ Assert.IsTrue (Regex.IsMatch (str, @"[A-F]+", RegexOptions.IgnoreCase), "#B1");
+ Assert.IsTrue (Regex.IsMatch (str, @"[a-f]+", RegexOptions.IgnoreCase), "#B2");
+ Assert.IsTrue (Regex.IsMatch (str, @"[A-Fa-f]+", RegexOptions.IgnoreCase), "#B3");
+ Assert.IsTrue (Regex.IsMatch (str, @"[AB]+", RegexOptions.IgnoreCase), "#B4");
+ Assert.IsTrue (Regex.IsMatch (str, @"[A-B]+", RegexOptions.IgnoreCase), "#B5");
str = "Aaa[";
- AssertEquals("RIC #11", true, Regex.IsMatch(str, @"[A-a]+", RegexOptions.IgnoreCase));
-
+ Assert.IsTrue (Regex.IsMatch (str, @"[A-a]+", RegexOptions.IgnoreCase), "#C");
+
str = "Ae";
- Assert("RIC #12", Regex.IsMatch(str, @"[A-a]+", RegexOptions.IgnoreCase));
+ Assert.IsTrue (Regex.IsMatch (str, @"[A-a]+", RegexOptions.IgnoreCase), "#D");
+ }
- }
+ [Test] // bug #54797
+ public void Escape0 ()
+ {
+ Regex r = new Regex(@"^[\s\0]*$");
+ Assert.IsTrue (r.Match(" \0").Success);
+ }
[Test]
- public void Escape0 () // bug54797
- {
- Regex r = new Regex(@"^[\s\0]*$");
- AssertEquals ("E0-1", true, r.Match(" \0").Success);
- }
-
- [Test()]
- public void MultipleMatches()
- {
- Regex regex = new Regex (@"^(?'path'.*(\\|/)|(/|\\))(?'file'.*)$");
- Match match = regex.Match (@"d:\Temp\SomeDir\SomeDir\bla.xml");
-
- AssertEquals ("MM #01", 5, match.Groups.Count);
-
- AssertEquals ("MM #02", "1", regex.GroupNameFromNumber(1));
- AssertEquals ("MM #03", "2", regex.GroupNameFromNumber(2));
- AssertEquals ("MM #04", "path", regex.GroupNameFromNumber(3));
- AssertEquals ("MM #05", "file", regex.GroupNameFromNumber(4));
-
- AssertEquals ("MM #06", "\\", match.Groups[1].Value);
- AssertEquals ("MM #07", "", match.Groups[2].Value);
- AssertEquals ("MM #08", @"d:\Temp\SomeDir\SomeDir\", // fool emacs: "
- match.Groups[3].Value);
- AssertEquals ("MM #09", "bla.xml", match.Groups[4].Value);
- }
-
- [Test]
- public void SameNameGroups () // First problem in fixing bug #56000
+ public void MultipleMatches()
+ {
+ Regex regex = new Regex (@"^(?'path'.*(\\|/)|(/|\\))(?'file'.*)$");
+ Match match = regex.Match (@"d:\Temp\SomeDir\SomeDir\bla.xml");
+
+ Assert.AreEqual (5, match.Groups.Count, "#1");
+ Assert.AreEqual ("1", regex.GroupNameFromNumber (1), "#2");
+ Assert.AreEqual ("2", regex.GroupNameFromNumber (2), "#3");
+ Assert.AreEqual ("path", regex.GroupNameFromNumber (3), "#4");
+ Assert.AreEqual ("file", regex.GroupNameFromNumber (4), "#5");
+ Assert.AreEqual ("\\", match.Groups [1].Value, "#6");
+ Assert.AreEqual (string.Empty, match.Groups [2].Value, "#7");
+ Assert.AreEqual (@"d:\Temp\SomeDir\SomeDir\", match.Groups [3].Value, "#8");
+ Assert.AreEqual ("bla.xml", match.Groups [4].Value, "#9");
+ }
+
+ [Test] // bug #56000
+ public void SameNameGroups ()
{
string rex = "link\\s*rel\\s*=\\s*[\"']?alternate[\"']?\\s*";
rex += "type\\s*=\\s*[\"']?text/xml[\"']?\\s*href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|'(?<1>[^']*)'|(?<1>\\S+))";
- Regex rob = new Regex (rex, RegexOptions.IgnoreCase);
+ new Regex (rex, RegexOptions.IgnoreCase);
}
- [Test]
- public void UndefinedGroup () // bug 52890
+ [Test] // bug #52890
+ public void UndefinedGroup ()
{
Regex regex = new Regex( "[A-Za-z_0-9]" );
Match m = regex.Match( "123456789abc" );
Group g = m.Groups["not_defined"];
- AssertNotNull ("#0", g);
- AssertEquals ("#1", 0, g.Index);
- AssertEquals ("#2", 0, g.Length);
- AssertEquals ("#3", "", g.Value);
- Assert ("#4", !g.Success);
- AssertNotNull ("#5", g.Captures);
- AssertEquals ("#6", 0, g.Captures.Count);
+ Assert.IsNotNull (g, "#1");
+ Assert.AreEqual (0, g.Index, "#2");
+ Assert.AreEqual (0, g.Length, "#3");
+ Assert.AreEqual (string.Empty, g.Value, "#4");
+ Assert.IsFalse (g.Success, "#5");
+ Assert.IsNotNull (g.Captures, "#6");
+ Assert.AreEqual (0, g.Captures.Count, "#7");
}
[Test]
{
Regex re = new Regex ("[\\w\\W]{8,32}");
Match m = re.Match (new string ('1', 7));
- AssertEquals ("#01", false, m.Success);
+ Assert.IsFalse (m.Success);
}
[Test]
{
Regex re = new Regex ("[\\w\\W]{8,32}");
Match m = re.Match (new string ('1', 8));
- AssertEquals ("#01", true, m.Success);
+ Assert.IsTrue (m.Success);
}
[Test]
{
Regex re = new Regex ("[\\w\\W]{8,32}");
Match m = re.Match (new string ('1', 16));
- AssertEquals ("#01", true, m.Success);
+ Assert.IsTrue (m.Success);
}
[Test]
{
Regex re = new Regex ("[\\w\\W]{8,32}");
Match m = re.Match (new string ('1', 32));
- AssertEquals ("#01", true, m.Success);
+ Assert.IsTrue (m.Success);
}
[Test]
{
Regex re = new Regex ("[\\w\\W]{8,32}");
Match m = re.Match (new string ('1', 33));
- AssertEquals ("#01", true, m.Success);
+ Assert.IsTrue (m.Success);
}
[Test]
string text = "<?xml version=\"1.0\"?>";
Regex re = new Regex ("<\\s*(\\/?)\\s*([\\s\\S]*?)\\s*(\\/?)\\s*>");
text = re.Replace (text, "{blue:<$1}{maroon:$2}{blue:$3>}");
- AssertEquals ("#01", "{blue:<}{maroon:?xml version=\"1.0\"?}{blue:>}", text);
+ Assert.AreEqual ("{blue:<}{maroon:?xml version=\"1.0\"?}{blue:>}", text);
}
[Test]
string text = "Go, \bNo\bGo" ;
Regex re = new Regex(@"\b[\b]");
text = re.Replace(text, " ");
- AssertEquals("#01", "Go, \bNo Go", text);
+ Assert.AreEqual ("Go, \bNo Go", text);
}
[Test]
string text = "abcdeeee";
Regex re = new Regex("e+");
text = re.Replace(text, "e", -1, 4);
- AssertEquals("#01", "abcde", text);
+ Assert.AreEqual ("abcde", text);
}
- [Test]
- //[Ignore] You may want to ignore this if the bugs gets back
- public void SplitInfiniteLoop () // bug 57274
+ [Test] // bug #57274
+ public void SplitInfiniteLoop ()
{
string ss = "a b c d e";
string [] words = Regex.Split (ss, "[ \t\n\r]*");
- AssertEquals ("#01Length", 11, words.Length);
- AssertEquals ("#00", "", words [0]);
- AssertEquals ("#01", "a", words [1]);
- AssertEquals ("#02", "", words [2]);
- AssertEquals ("#03", "b", words [3]);
- AssertEquals ("#04", "", words [4]);
- AssertEquals ("#05", "c", words [5]);
- AssertEquals ("#06", "", words [6]);
- AssertEquals ("#07", "d", words [7]);
- AssertEquals ("#08", "", words [8]);
- AssertEquals ("#09", "e", words [9]);
- AssertEquals ("#10", "", words [10]);
-
+ Assert.AreEqual (11, words.Length, "#1");
+ Assert.AreEqual (string.Empty, words [0], "#2");
+ Assert.AreEqual ("a", words [1], "#3");
+ Assert.AreEqual (string.Empty, words [2], "#4");
+ Assert.AreEqual ("b", words [3], "#5");
+ Assert.AreEqual (string.Empty, words [4], "#6");
+ Assert.AreEqual ("c", words [5], "#7");
+ Assert.AreEqual (string.Empty, words [6], "#8");
+ Assert.AreEqual ("d", words [7], "#9");
+ Assert.AreEqual (string.Empty, words [8], "#10");
+ Assert.AreEqual ("e", words [9], "#11");
+ Assert.AreEqual (string.Empty, words [10], "#12");
}
- [Test]
- public void CaseAndSearch () // bug 69065
+ [Test] // bug #69065
+ public void CaseAndSearch ()
{
string test1 = @"\f!E ZWEITBAD :REGLER-PARAMETER 20.10.2004 SEITE 1";
string test2 = @" REGLER-PARAMETER ";
Regex x = new Regex ("REGLER-PARAMETER",RegexOptions.IgnoreCase|RegexOptions.Compiled);
Match m = x.Match (test1);
- AssertEquals ("#01", true, m.Success);
+ Assert.IsTrue (m.Success, "#1");
m = x.Match (test2);
- AssertEquals ("#02", true, m.Success);
+ Assert.IsTrue (m.Success, "#2");
m = x.Match (test3);
- AssertEquals ("#03", true, m.Success);
+ Assert.IsTrue (m.Success, "#3");
}
- [Test]
- public void QuantifiersParseError () // bug 69193
+ [Test] // bug #69193
+ public void QuantifiersParseError ()
{
- Regex x = new Regex ("{1,a}");
- x = new Regex ("{a,1}");
- x = new Regex ("{a}");
- x = new Regex ("{,a}");
+ new Regex ("{1,a}");
+ new Regex ("{a,1}");
+ new Regex ("{a}");
+ new Regex ("{,a}");
}
- [Test]
- public void NameLookupInEmptyMatch () // bug 74753
+ [Test] // bug #74753
+ public void NameLookupInEmptyMatch ()
{
Regex regTime = new Regex (
@"(?<hour>[0-9]{1,2})([\:](?<minute>[0-9]{1,2})){0,1}([\:](?<second>[0-9]{1,2})){0,1}\s*(?<ampm>(?i:(am|pm)){0,1})");
Match mTime = regTime.Match("");
- AssertEquals ("#01", "", mTime.Groups["hour"].Value);
- AssertEquals ("#02", "", mTime.Groups["minute"].Value);
- AssertEquals ("#03", "", mTime.Groups["second"].Value);
- AssertEquals ("#04", "", mTime.Groups["ampm"].Value);
+ Assert.AreEqual ("", mTime.Groups["hour"].Value, "#A1");
+ Assert.AreEqual ("", mTime.Groups ["minute"].Value, "#A2");
+ Assert.AreEqual ("", mTime.Groups ["second"].Value, "#A3");
+ Assert.AreEqual ("", mTime.Groups ["ampm"].Value, "#A4");
mTime = regTime.Match("12:00 pm");
- AssertEquals ("#05", "12", mTime.Groups["hour"].Value);
- AssertEquals ("#06", "00", mTime.Groups["minute"].Value);
- AssertEquals ("#07", "", mTime.Groups["second"].Value);
- AssertEquals ("#08", "pm", mTime.Groups["ampm"].Value);
+ Assert.AreEqual ("12", mTime.Groups ["hour"].Value, "#B1");
+ Assert.AreEqual ("00", mTime.Groups ["minute"].Value, "#B2");
+ Assert.AreEqual ("", mTime.Groups ["second"].Value, "#B3");
+ Assert.AreEqual ("pm", mTime.Groups ["ampm"].Value, "#B4");
}
- [Test]
+ [Test] // bug #77626
public void HangingHyphens ()
{
- // bug 77626
- Assert ("#01", Regex.IsMatch ("mT1[", @"m[0-9A-Za-z_-]+\["));
- Assert ("#02", Regex.IsMatch ("mT1[", @"m[-0-9A-Za-z_]+\["));
+ Assert.IsTrue (Regex.IsMatch ("mT1[", @"m[0-9A-Za-z_-]+\["), "#A1");
+ Assert.IsTrue (Regex.IsMatch ("mT1[", @"m[-0-9A-Za-z_]+\["), "#A2");
- Assert ("#03", Regex.IsMatch ("-a;", @"[--a]{3}"));
- Assert ("#04", Regex.IsMatch ("-&,", @"[&--]{3}"));
+ Assert.IsTrue (Regex.IsMatch ("-a;", @"[--a]{3}"), "#B1");
+ Assert.IsTrue (Regex.IsMatch ("-&,", @"[&--]{3}"), "#B2");
- Assert ("#05", Regex.IsMatch ("abcz-", @"[a-c-z]{5}"));
- Assert ("#05b", !Regex.IsMatch ("defghijklmnopqrstuvwxy", @"[a-c-z]"));
+ Assert.IsTrue (Regex.IsMatch ("abcz-", @"[a-c-z]{5}"), "#C1");
+ Assert.IsFalse (Regex.IsMatch ("defghijklmnopqrstuvwxy", @"[a-c-z]"), "#C2");
- Assert ("#06", Regex.IsMatch ("abcxyz-", @"[a-c-x-z]{7}"));
- Assert ("#06b", !Regex.IsMatch ("defghijklmnopqrstuvw", @"[a-c-x-z]"));
+ Assert.IsTrue (Regex.IsMatch ("abcxyz-", @"[a-c-x-z]{7}"), "#D1");
+ Assert.IsFalse (Regex.IsMatch ("defghijklmnopqrstuvw", @"[a-c-x-z]"), "#D2");
- Assert ("#07", Regex.IsMatch (" \tz-", @"[\s-z]{4}"));
- Assert ("#07b", !Regex.IsMatch ("abcdefghijklmnopqrstuvwxy", @"[\s-z]"));
+ Assert.IsTrue (Regex.IsMatch (" \tz-", @"[\s-z]{4}"), "#E1");
+ Assert.IsFalse (Regex.IsMatch ("abcdefghijklmnopqrstuvwxy", @"[\s-z]"), "#E2");
}
[Test, ExpectedException (typeof (ArgumentException))]
public void HangingHyphen1 ()
{
- bool b = Regex.IsMatch ("foobar", @"[a-\s]");
+ Regex.IsMatch ("foobar", @"[a-\s]");
+ }
+
+ [Test]
+ public void Bug313642 ()
+ {
+ Regex r = new Regex ("(?<a>c)");
+ Match m = r.Match ("a");
+ Assert.AreEqual (1, m.Groups.Count, "#1");
+ Assert.AreEqual (0, m.Groups [0].Captures.Count, "#2");
+ Assert.AreEqual (0, m.Groups [0].Index, "#3");
+ Assert.AreEqual (0, m.Groups [0].Length, "#4");
+ Assert.IsFalse (m.Groups [0].Success, "#5");
+ Assert.AreEqual (string.Empty, m.Groups [0].Value, "#6");
}
[Test]
public void Bug77487 ()
{
- Assert ("#01", Regex.IsMatch ("a a", "^(a[^a]*)*a$"));
- Assert ("#02", Regex.IsMatch ("a a", "^(a *)*a$"));
- Assert ("#03", Regex.IsMatch ("a a", "(a[^a]*)+a"));
- Assert ("#04", Regex.IsMatch ("a a", "(a *)+a"));
+ Assert.IsTrue (Regex.IsMatch ("a a", "^(a[^a]*)*a$"), "#1");
+ Assert.IsTrue (Regex.IsMatch ("a a", "^(a *)*a$"), "#2");
+ Assert.IsTrue (Regex.IsMatch ("a a", "(a[^a]*)+a"), "#3");
+ Assert.IsTrue (Regex.IsMatch ("a a", "(a *)+a"), "#4");
}
[Test]
public void Bug69269 ()
{
string s = "CREATE aa\faa; CREATE bb\nbb; CREATE cc\rcc; CREATE dd\tdd; CREATE ee\vee;";
- AssertEquals ("#01", 5, Regex.Matches(s, @"CREATE[\s\S]+?;").Count);
- AssertEquals ("#02", 5, Regex.Matches(s, @"CREATE[ \f\n\r\t\v\S]+?;").Count);
+ Assert.AreEqual (5, Regex.Matches(s, @"CREATE[\s\S]+?;").Count, "#1");
+ Assert.AreEqual (5, Regex.Matches (s, @"CREATE[ \f\n\r\t\v\S]+?;").Count, "#2");
}
[Test]
string s1 = "'asdf'";
string s2 = "'as,'df'";
- m = new Regex("'.*?'").Match(s1); Assert ("#01", m.Success); AssertEquals ("#01v", s1, m.Value);
- m = new Regex("'[^,].*?'").Match(s1); Assert ("#02", m.Success); AssertEquals ("#02v", s1, m.Value);
- m = new Regex("'.*?[^,]'").Match(s1); Assert ("#03", m.Success); AssertEquals ("#03v", s1, m.Value);
- m = new Regex("'.*?[^,]'").Match(s2); Assert ("#04", m.Success); AssertEquals ("#04v", s2, m.Value);
+ m = new Regex("'.*?'").Match(s1);
+ Assert.IsTrue (m.Success, "#A1");
+ Assert.AreEqual (s1, m.Value, "#A2");
+
+ m = new Regex("'[^,].*?'").Match(s1);
+ Assert.IsTrue (m.Success, "#B1");
+ Assert.AreEqual (s1, m.Value, "#B2");
+
+ m = new Regex("'.*?[^,]'").Match(s1);
+ Assert.IsTrue (m.Success, "#C1");
+ Assert.AreEqual (s1, m.Value, "#C2");
+
+ m = new Regex("'.*?[^,]'").Match(s2);
+ Assert.IsTrue (m.Success, "#D1");
+ Assert.AreEqual (s2, m.Value, "#D2");
}
[Test]
string pattern = @"\Ahead>\<html\>";
Regex r = new Regex (pattern);
Match m = r.Match (test);
- Assert ("#01", m.Success);
- AssertEquals ("#01i", 0, m.Index);
- AssertEquals ("#01l", 14, m.Length);
+ Assert.IsTrue (m.Success, "#A1");
+ Assert.AreEqual (0, m.Index, "#A2");
+ Assert.AreEqual (14, m.Length, "#A3");
m = m.NextMatch ();
- Assert ("#02", !m.Success);
+ Assert.IsFalse (m.Success, "#B");
}
[Test]
string str = "Foobar qux";
Regex re = new Regex (@"[a-z\s]*", RegexOptions.IgnoreCase);
Match m = re.Match (str);
- AssertEquals ("#01", str, m.Value);
- }
+ Assert.AreEqual (str, m.Value);
+ }
+
+ [Test] // bug #78278
+ public void No65535Limit ()
+ {
+ Kill65535_1 (65535);
+ Kill65535_1 (65536);
+ Kill65535_1 (131071);
+ Kill65535_1 (131072);
+
+ Kill65535_2 (65530);
+ Kill65535_2 (65531);
+ Kill65535_2 (131066);
+ Kill65535_2 (131067);
+ }
+
+ [Test]
+ public void GroupNumbers ()
+ {
+ GroupNumbers_1 ("a", 1);
+ GroupNumbers_1 ("(a)", 2);
+ GroupNumbers_1 ("(a)(b)", 3);
+ GroupNumbers_1 ("(a)|(b)", 3);
+ GroupNumbers_1 ("((a)(b))(c)", 5);
+ }
+
+ [Test]
+ public void Bug80554_0 ()
+ {
+ bug80554_trials [0].Execute ();
+ }
+
+ [Test]
+ public void Bug80554_1 ()
+ {
+ bug80554_trials [1].Execute ();
+ }
+
+ [Test]
+ public void Bug80554_2 ()
+ {
+ bug80554_trials [2].Execute ();
+ }
+
+ [Test]
+ public void Bug80554_3 ()
+ {
+ bug80554_trials [3].Execute ();
+ }
void Kill65535_1 (int length)
{
string teststring = sb.ToString ();
Regex regex = new Regex (@"xa*y");
Match m = regex.Match (teststring);
- Assert ("#01 " + length, m.Success);
- AssertEquals ("#02 " + length, m.Index, 0);
- AssertEquals ("#03 " + length, m.Length, teststring.Length);
+ Assert.IsTrue (m.Success, "#1:" + length);
+ Assert.AreEqual (0, m.Index, "#2:" + length);
+ Assert.AreEqual (teststring.Length, m.Length, "#3:" + length);
}
void Kill65535_2 (int length)
string teststring = sb.ToString ();
Regex regex = new Regex (@"x.*y");
Match m = regex.Match(teststring);
- Assert ("#01 " + length, m.Success);
- AssertEquals ("#02 " + length, m.Index, 0);
- AssertEquals ("#03 " + length, m.Length, teststring.Length);
+ Assert.IsTrue (m.Success, "#1:" + length);
+ Assert.AreEqual (0, m.Index, "#2:" + length);
+ Assert.AreEqual (teststring.Length, m.Length, "#3:" + length);
}
-
- [Test] // Based on bug #78278
- public void No65535Limit ()
- {
- Kill65535_1 (65535);
- Kill65535_1 (65536);
- Kill65535_1 (131071);
- Kill65535_1 (131072);
-
- Kill65535_2 (65530);
- Kill65535_2 (65531);
- Kill65535_2 (131066);
- Kill65535_2 (131067);
- }
-
void GroupNumbers_1 (string s, int n)
{
Regex r = new Regex (s);
int [] grps = r.GetGroupNumbers ();
- AssertEquals (r+" #01", n, grps.Length);
+ Assert.AreEqual (n, grps.Length, "#1:" + r);
int sum = 0;
for (int i = 0; i < grps.Length; ++i) {
sum += grps [i];
// group numbers are unique
for (int j = 0; j < i; ++j)
- Assert (r+" #02 ("+i+","+j+")", grps [i] != grps [j]);
+ Assert.IsTrue (grps [i] != grps [j], "#2:" + r + " (" + i + "," + j + ")");
}
// no gaps in group numbering
- AssertEquals (r+" #03", (n*(n-1))/2, sum);
- }
-
- [Test]
- public void GroupNumbers ()
- {
- GroupNumbers_1 ("a", 1);
- GroupNumbers_1 ("(a)", 2);
- GroupNumbers_1 ("(a)(b)", 3);
- GroupNumbers_1 ("(a)|(b)", 3);
- GroupNumbers_1 ("((a)(b))(c)", 5);
+ Assert.AreEqual ((n * (n - 1)) / 2, sum, "#3:" + r);
}
static string bug80554_s = @"(?(static)|(.*))(static)";
new RegexTrial (bug80554_s, RegexOptions.None, "statics", "Pass. Group[0]=(0,6) Group[1]= Group[2]=(0,6)"),
new RegexTrial (bug80554_s, RegexOptions.None, "dynamic", "Fail.")
};
-
- [Test] public void Bug80554_0 () { bug80554_trials [0].Execute (); }
- [Test] public void Bug80554_1 () { bug80554_trials [1].Execute (); }
- [Test] public void Bug80554_2 () { bug80554_trials [2].Execute (); }
- [Test] public void Bug80554_3 () { bug80554_trials [3].Execute (); }
-
}
}
using NUnit.Framework;
-namespace MonoTests.System.Text.RegularExpressions {
-
+namespace MonoTests.System.Text.RegularExpressions
+{
[TestFixture]
- public class RegexTest {
-
+ public class RegexTest
+ {
#if NET_2_0
private int cache_initial_value;
Regex.CacheSize = cache_initial_value;
}
#endif
+
[Test]
public void Simple ()
{
char[] c = { (char)32, (char)8212, (char)32 };
- string s = new String(c);
+ string s = new String(c);
Assert.IsTrue (Regex.IsMatch(s, s), "char");
}
Assert.AreEqual ("go-mono.com", m.Groups ["domain"].Value, "#m06");
}
- static string story =
+ static string story =
"Two little dragons lived in the forest\n" +
"They spent their days collecting honey suckle,\n" +
"And eating curds and whey\n" +
[Test]
public void Matches ()
{
- int i;
- MatchCollection mc;
- Regex r;
foreach (MatchCollectionTrial t in trials)
runTrial (t);
}
+2007-10-16 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * UriTest.cs: Removed extra tabs.
+ * UriTest3.cs: Added test for bug #325863. Improved test for absolute
+ URI.
+
2007-09-30 Gert Driesen <drieseng@users.sourceforge.net>
* UriTest3.cs: Added test for bug #328768 and #323542.
uri2 = new Uri ("http://www.contoso.com/index.htm?x=1");
Assert ("#2", uri1.GetHashCode () != uri2.GetHashCode ());
uri2 = new Uri ("http://www.contoso.com:80/index.htm");
- AssertEquals ("#3", uri1.GetHashCode (), uri2.GetHashCode ());
+ AssertEquals ("#3", uri1.GetHashCode (), uri2.GetHashCode ());
uri2 = new Uri ("http://www.contoso.com:8080/index.htm");
- Assert ("#4", uri1.GetHashCode () != uri2.GetHashCode ());
+ Assert ("#4", uri1.GetHashCode () != uri2.GetHashCode ());
}
#if NET_2_0
Assert ("#5b", !uri3.Equals(uri4));
}
- [ExpectedException(typeof(InvalidOperationException))]
[Test]
+ [ExpectedException(typeof(InvalidOperationException))]
public void GetLeftPart_Partial1 ()
{
Uri u = new Uri ("foo", UriKind.Relative);
}
#endif
-
-
// This test doesn't work on Linux, and arguably shouldn't work.
// new Uri("file:///tmp/foo/bar").AbsolutePath returns "/tmp/foo/bar"
// on Linux, as anyone sane would expect. It *doesn't* under .NET 1.1
public void Absolute_UriKind_Absolute ()
{
Uri uri = new Uri (absolute, UriKind.Absolute);
- Assert.AreEqual ("www.mono-project.com", uri.DnsSafeHost, "DnsSafeHost");
- Assert.IsTrue (uri.IsAbsoluteUri, "IsAbsoluteUri");
- Assert.AreEqual (absolute, uri.OriginalString, "OriginalString");
+ Assert.AreEqual ("www.mono-project.com", uri.DnsSafeHost, "#1");
+ Assert.IsTrue (uri.IsAbsoluteUri, "#2");
+ Assert.AreEqual (absolute, uri.OriginalString, "#3");
+ Assert.AreEqual (absolute, uri.ToString (), "#4");
+ Assert.IsFalse (uri.UserEscaped, "#5");
}
[Test]
Assert.AreEqual ("foo/bar", uri.ToString (), "#C3");
Assert.IsFalse (uri.UserEscaped, "#C4");
+ uri = new Uri ("/test.aspx", UriKind.Relative);
+ Assert.IsFalse (uri.IsAbsoluteUri, "#D1");
+ Assert.AreEqual ("/test.aspx", uri.OriginalString, "#D2");
+ Assert.AreEqual ("/test.aspx", uri.ToString (), "#D3");
+ Assert.IsFalse (uri.UserEscaped, "#D4");
}
[Test]
System.Net/IWebRequestCreate.cs
System.Net/ListenerAsyncResult.cs
System.Net/ListenerPrefix.cs
-System.Net.Mail/AlternateViewCollection.cs
-System.Net.Mail/AlternateView.cs
-System.Net.Mail/AttachmentBase.cs
-System.Net.Mail/AttachmentCollection.cs
-System.Net.Mail/Attachment.cs
-System.Net.Mail/DeliveryNotificationOptions.cs
-System.Net.Mail/LinkedResourceCollection.cs
-System.Net.Mail/LinkedResource.cs
-System.Net.Mail/MailAddressCollection.cs
-System.Net.Mail/MailAddress.cs
-System.Net.Mail/MailMessage.cs
-System.Net.Mail/MailPriority.cs
-System.Net.Mail/SendCompletedEventHandler.cs
-System.Net.Mail/SmtpAccess.cs
-System.Net.Mail/SmtpClient.cs
-System.Net.Mail/SmtpDeliveryMethod.cs
-System.Net.Mail/SmtpException.cs
-System.Net.Mail/SmtpFailedRecipientException.cs
-System.Net.Mail/SmtpFailedRecipientsException.cs
-System.Net.Mail/SmtpPermission.cs
-System.Net.Mail/SmtpPermissionAttribute.cs
-System.Net.Mail/SmtpStatusCode.cs
System.Net.Mime/ContentDisposition.cs
System.Net.Mime/ContentType.cs
System.Net.Mime/DispositionTypeNames.cs
+2007-10-13 kevin.fitzgerald@soarce.us
+
+ * UnixRegistryApi.cs: Escape the strings before passing them to
+ SecurityElement. This fixes bug #322839
+
2007-08-30 Marek Habersack <mhabersack@novell.com>
* UnixRegistryApi.cs: properly retrieve values of type
SecurityElement se = new SecurityElement ("values");
+ // With SecurityElement.Text = value, and SecurityElement.AddAttribute(key, value)
+ // the values must be escaped prior to being assigned.
foreach (DictionaryEntry de in values){
object val = de.Value;
SecurityElement value = new SecurityElement ("value");
- value.AddAttribute ("name", (string) de.Key);
+ value.AddAttribute ("name", SecurityElement.Escape ((string) de.Key));
if (val is string){
value.AddAttribute ("type", "string");
- value.Text = (string) val;
+ value.Text = SecurityElement.Escape ((string) val);
} else if (val is int){
value.AddAttribute ("type", "int");
value.Text = val.ToString ();
value.Text = Convert.ToBase64String ((byte[]) val);
} else if (val is ExpandString){
value.AddAttribute ("type", "expand");
- value.Text = val.ToString ();
+ value.Text = SecurityElement.Escape (val.ToString ());
} else if (val is string []){
value.AddAttribute ("type", "string-array");
foreach (string ss in (string[]) val){
SecurityElement str = new SecurityElement ("string");
- str.Text = ss;
+ str.Text = SecurityElement.Escape (ss);
value.AddChild (str);
}
}
+2007-10-15 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * ILGenerator.cs: Added missing null checks. Removed extra tabs.
+
2007-09-23 Gert Driesen <drieseng@users.sourceforge.net>
* AssemblyBuilder.cs: Added missing paramname to ArgumentExceptions.
code [code_len++] = s [3];
code [code_len++] = s [2];
code [code_len++] = s [1];
- code [code_len++] = s [0];
+ code [code_len++] = s [0];
}
}
public virtual void Emit (OpCode opcode, Label[] labels)
{
+ if (labels == null)
+ throw new ArgumentNullException ("labels");
+
/* opcode needs to be switch. */
int count = labels.Length;
make_room (6 + count * 4);
public virtual void Emit (OpCode opcode, LocalBuilder lbuilder)
{
+ if (lbuilder == null)
+ throw new ArgumentNullException ("local");
+
uint pos = lbuilder.position;
bool load_addr = false;
bool is_store = false;
public virtual void Emit (OpCode opcode, MethodInfo method)
{
if (method == null)
- throw new ArgumentNullException ("method");
+ throw new ArgumentNullException ("meth");
#if NET_2_0
// For compatibility with MS
code [code_len++] = s [3];
code [code_len++] = s [2];
code [code_len++] = s [1];
- code [code_len++] = s [0];
+ code [code_len++] = s [0];
}
}
public void EmitCall (OpCode opcode, MethodInfo methodinfo, Type[] optionalParamTypes)
{
if (methodinfo == null)
- throw new ArgumentNullException ("methodinfo can not be null");
+ throw new ArgumentNullException ("methodInfo");
short value = opcode.Value;
if (!(value == OpCodes.Call.Value || value == OpCodes.Callvirt.Value))
throw new NotSupportedException ("Only Call and CallVirt are allowed");
+2007-10-14 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * SecurityElement.cs: In ctors, do not assign to Tag property to
+ ensure exception message match that of MS. In Tag property, set name
+ of parameter in ArgumentNullException and do not filter out
+ namespace prefixes. Modified Text property to allow null values
+ after change to IsValidText that no longer considers null value as
+ valid. Avoid NRE in Escape.
+
2007-08-28 Mark Probst <mark.probst@gmail.com>
* SecurityManager.cs: Changed method argument of
public SecurityElement (string tag, string text)
{
- this.Tag = tag;
- this.Text = text;
+ if (tag == null)
+ throw new ArgumentNullException ("tag");
+ if (!IsValidTag (tag))
+ throw new ArgumentException (Locale.GetText ("Invalid XML string") + ": " + tag);
+ this.tag = tag;
+
+ Text = text;
}
// not a deep copy (childs are references)
return result;
}
- set {
+ set {
if (value == null || value.Count == 0) {
attributes.Clear ();
return;
}
set {
if (value == null)
- throw new ArgumentNullException ();
+ throw new ArgumentNullException ("Tag");
if (!IsValidTag (value))
throw new ArgumentException (Locale.GetText ("Invalid XML string") + ": " + value);
- int colon = value.IndexOf (':');
- tag = colon < 0 ? value : value.Substring (colon + 1);
+ tag = value;
}
}
}
set {
- if (!IsValidText (value))
- throw new ArgumentException (Locale.GetText ("Invalid XML string") + ": " + text);
+ if (value != null) {
+ if (!IsValidText (value))
+ throw new ArgumentException (
+ Locale.GetText ("Invalid XML string")
+ + ": " + value);
+ }
text = value;
}
}
public static string Escape (string str)
{
StringBuilder sb;
-
+
+ if (str == null)
+ return null;
+
if (str.IndexOfAny (invalid_chars) == -1)
return str;
}
#if NET_2_0
- public
+ public
#else
internal
#endif
SecurityParser sp = new SecurityParser ();
sp.LoadXml (xml);
return sp.ToXml ();
- }
- catch (Exception e) {
+ } catch (Exception e) {
string msg = Locale.GetText ("Invalid XML.");
throw new XmlSyntaxException (msg, e);
}
public static bool IsValidText (string value)
{
- if (value == null)
- return true;
- return value.IndexOfAny (invalid_text_chars) == -1;
+ return value != null && value.IndexOfAny (invalid_text_chars) == -1;
}
public SecurityElement SearchForChildByTag (string tag)
return elem;
}
return null;
- }
+ }
public string SearchForTextOfTag (string tag)
{
return result;
}
- return null;
+ return null;
}
public override string ToString ()
body_name = "utf-32BE";
encoding_name = "UTF-32 (Big-Endian)";
header_name = "utf-32BE";
- is_browser_save = false;
web_name = "utf-32BE";
} else {
body_name = "utf-32";
encoding_name = "UTF-32";
header_name = "utf-32";
- is_browser_save = true;
web_name = "utf-32";
}
is_browser_save = true;
is_browser_display = true;
is_mail_news_display = true;
+ is_mail_news_save = true;
windows_code_page = UnicodeEncoding.UNICODE_CODE_PAGE;
}
+
+Wed Oct 17 13:24:33 CEST 2007 Paolo Molaro <lupus@ximian.com>
+
+ * Timer.cs: better cleanup test for the expired array.
+
+Tue Oct 16 17:22:15 CEST 2007 Paolo Molaro <lupus@ximian.com>
+
+ * Timer.cs: remove expired timers from the the jobs list.
+
+Tue Oct 16 12:14:43 CEST 2007 Paolo Molaro <lupus@ximian.com>
+
+ * Timer.cs: rewrote to use threadpool threads to invoke the callbacks,
+ avoid Thread.Abort and Thread.Interrupt and use a single scheduler
+ thread, partially from the patch of Rafael Ferreira in bug #315999.
+ Fixes bug #315999, #332206.
+
+2007-10-15 Dick Porter <dick@ximian.com>
+
+ * Thread.cs: Initialise synch_cs to null now we aren't using it as
+ a monitor lock
+
2007-09-25 Dick Porter <dick@ximian.com>
* Thread.cs: Keep ManagedThreadId constant over the lifetime of a
private IntPtr suspend_event;
private IntPtr suspended_event;
private IntPtr resume_event;
- /* Don't lock on synch_lock in managed code, since it can result in deadlocks */
- private object synch_lock = new Object();
+ /* Don't lock on synch_cs in managed code, since it can result in deadlocks */
+ private object synch_cs = null;
private IntPtr serialized_culture_info;
private int serialized_culture_info_len;
private IntPtr serialized_ui_culture_info;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern IntPtr Thread_internal (MulticastDelegate start);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ private extern void Thread_init ();
+
private static int GetNewManagedId() {
return Interlocked.Increment(ref _managed_id_counter);
}
throw new ArgumentNullException("Null ThreadStart");
}
threadstart=start;
+
+ Thread_init ();
managed_id=GetNewManagedId();
}
//
using System.Runtime.InteropServices;
+using System.Collections;
namespace System.Threading
{
#endif
public sealed class Timer : MarshalByRefObject, IDisposable
{
- sealed class Runner : MarshalByRefObject
+#region Timer instance fields
+ TimerCallback callback;
+ object state;
+ long due_time_ms;
+ long period_ms;
+ long next_run; // in ticks
+ bool disposed;
+#endregion
+
+#region Timer static fields
+ static Thread scheduler;
+ static Hashtable jobs;
+ static AutoResetEvent change_event;
+#endregion
+
+ /* we use a static initializer to avoid race issues with the thread creation */
+ static Timer ()
{
- ManualResetEvent wait;
- AutoResetEvent start_event;
- TimerCallback callback;
- object state;
- int dueTime;
- int period;
- bool disposed;
- bool aborted;
-
- public Runner (TimerCallback callback, object state, AutoResetEvent start_event)
- {
- this.callback = callback;
- this.state = state;
- this.start_event = start_event;
- this.wait = new ManualResetEvent (false);
- }
-
- public int DueTime {
- get { return dueTime; }
- set { dueTime = value; }
- }
-
- public int Period {
- get { return period; }
- set { period = value == 0 ? Timeout.Infinite : value; }
- }
-
- bool WaitForDueTime ()
- {
- if (dueTime > 0) {
- bool signaled;
- do {
- wait.Reset ();
- signaled = wait.WaitOne (dueTime, false);
- } while (signaled == true && !disposed && !aborted);
-
- if (!signaled)
- callback (state);
-
- if (disposed)
- return false;
- }
- else
- callback (state);
-
- return true;
- }
-
- public void Abort ()
- {
- lock (this) {
- aborted = true;
- wait.Set ();
- }
- }
-
- public void Dispose ()
- {
- lock (this) {
- disposed = true;
- Abort ();
- }
- }
-
- public void Start ()
- {
- while (!disposed && start_event.WaitOne ()) {
- if (disposed)
- return;
-
- aborted = false;
-
- if (dueTime == Timeout.Infinite)
- continue;
-
- if (!WaitForDueTime ())
- return;
-
- if (aborted || (period == Timeout.Infinite))
- continue;
-
- bool signaled = false;
- while (true) {
- if (disposed)
- return;
+ change_event = new AutoResetEvent (false);
+ jobs = new Hashtable ();
+ scheduler = new Thread (SchedulerThread);
+ scheduler.IsBackground = true;
+ scheduler.Start ();
+ }
- if (aborted)
- break;
+ static long Ticks ()
+ {
+ /* use a monotonic time value later */
+ return DateTime.UtcNow.Ticks;
+ }
- try {
- wait.Reset ();
- } catch (ObjectDisposedException) {
- // FIXME: There is some race condition
- // here when the thread is being
- // aborted on exit.
- return;
+ static private void SchedulerThread ()
+ {
+ Thread.CurrentThread.Name = "Timer-Scheduler";
+ while (true) {
+ long min_wait = long.MaxValue;
+ lock (jobs) {
+ ArrayList expired = null;
+ long ticks = Ticks ();
+ foreach (DictionaryEntry entry in jobs) {
+ Timer t1 = entry.Value as Timer;
+ if (t1.next_run <= ticks) {
+ ThreadPool.QueueUserWorkItem (new WaitCallback (t1.callback), t1.state);
+ if (t1.period_ms == -1) {
+ t1.next_run = long.MaxValue;
+ if (expired == null)
+ expired = new ArrayList ();
+ expired.Add (t1);
+ } else {
+ t1.next_run = ticks + TimeSpan.TicksPerMillisecond * t1.period_ms;
+ }
}
-
- signaled = wait.WaitOne (period, false);
-
- if (aborted || disposed)
- break;
-
- if (!signaled) {
- callback (state);
- } else if (!WaitForDueTime ()) {
- return;
+ if (t1.next_run != long.MaxValue) {
+ min_wait = Math.Min (min_wait, t1.next_run - ticks);
+ }
+ }
+ if (expired != null) {
+ int count = expired.Count;
+ for (int i = 0; i < count; ++i) {
+ jobs.Remove (expired [i]);
}
+ expired.Clear ();
+ if (count > 50)
+ expired = null;
}
}
+ if (min_wait != long.MaxValue) {
+ change_event.WaitOne ((int)(min_wait / TimeSpan.TicksPerMillisecond), true);
+ } else {
+ change_event.WaitOne (Timeout.Infinite, true);
+ }
}
}
- Runner runner;
- AutoResetEvent start_event;
- WeakReference weak_t;
-
public Timer (TimerCallback callback, object state, int dueTime, int period)
{
if (dueTime < -1)
if (period < -1)
throw new ArgumentOutOfRangeException ("period");
- Init (callback, state, (int) dueTime, (int) period);
+ Init (callback, state, dueTime, period);
}
public Timer (TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)
- : this (callback, state, Convert.ToInt32(dueTime.TotalMilliseconds), Convert.ToInt32(period.TotalMilliseconds))
+ : this (callback, state, (long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds)
{
}
}
#endif
- void Init (TimerCallback callback, object state, int dueTime, int period)
+ void Init (TimerCallback callback, object state, long dueTime, long period)
{
- start_event = new AutoResetEvent (false);
- runner = new Runner (callback, state, start_event);
- Change (dueTime, period);
- Thread t = new Thread (new ThreadStart (runner.Start));
+ this.callback = callback;
+ this.state = state;
- weak_t = new WeakReference (t);
-
- t.IsBackground = true;
- t.Start ();
+ Change (dueTime, period);
}
public bool Change (int dueTime, int period)
{
- if (dueTime < -1)
- throw new ArgumentOutOfRangeException ("dueTime");
-
- if (period < -1)
- throw new ArgumentOutOfRangeException ("period");
-
- if (runner == null)
- return false;
-
- start_event.Reset ();
- runner.Abort ();
- runner.DueTime = dueTime;
- runner.Period = period;
- start_event.Set ();
- return true;
+ return Change ((long)dueTime, (long)period);
}
public bool Change (long dueTime, long period)
if(period > 4294967294)
throw new NotSupportedException ("Period too large");
- return Change ((int) dueTime, (int) period);
+ if (dueTime < -1)
+ throw new ArgumentOutOfRangeException ("dueTime");
+
+ if (period < -1)
+ throw new ArgumentOutOfRangeException ("period");
+
+ if (disposed)
+ return false;
+
+ due_time_ms = dueTime;
+ period_ms = period;
+ if (dueTime == 0) {
+ next_run = Ticks ();
+ } else if (dueTime == Timeout.Infinite) {
+ next_run = long.MaxValue;
+ } else {
+ next_run = dueTime * TimeSpan.TicksPerMillisecond + Ticks ();
+ }
+ lock (jobs) {
+ if (next_run != long.MaxValue) {
+ Timer t = jobs [this] as Timer;
+ if (t == null)
+ jobs [this] = this;
+ change_event.Set ();
+ } else {
+ jobs.Remove (this);
+ }
+ }
+ return true;
}
public bool Change (TimeSpan dueTime, TimeSpan period)
{
- return Change (Convert.ToInt32(dueTime.TotalMilliseconds), Convert.ToInt32(period.TotalMilliseconds));
+ return Change ((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds);
}
[CLSCompliant(false)]
if (period > Int32.MaxValue)
throw new NotSupportedException ("Period too large");
- return Change ((int) dueTime, (int) period);
+ return Change ((long) dueTime, (long) period);
}
public void Dispose ()
{
- Thread t = (Thread)weak_t.Target;
-
- if (t != null && t.IsAlive) {
- if (t != Thread.CurrentThread)
- t.Abort ();
- }
-
- if (runner != null) {
- runner.Dispose ();
- runner = null;
+ disposed = true;
+ lock (jobs) {
+ jobs.Remove (this);
}
- GC.SuppressFinalize (this);
}
public bool Dispose (WaitHandle notifyObject)
return true;
}
- ~Timer ()
- {
- Thread t = (Thread)weak_t.Target;
-
- if (t != null && t.IsAlive)
- t.Abort ();
-
- if (runner != null)
- runner.Abort ();
- }
}
}
using System.Configuration.Assemblies;
#if NET_2_0
+using System.Collections.Generic;
using System.Runtime.ConstrainedExecution;
#endif
return ab;
}
+#if NET_2_0
+ // NET 3.5 method
+ public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
+ Evidence evidence,
+ PermissionSet requiredPermissions,
+ PermissionSet optionalPermissions,
+ PermissionSet refusedPermissions, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
+ {
+ AssemblyBuilder ab = DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, isSynchronized);
+ if (assemblyAttributes != null)
+ foreach (CustomAttributeBuilder cb in assemblyAttributes) {
+ ab.SetCustomAttribute (cb);
+ }
+ return ab;
+ }
+
+ // NET 3.5 method
+ public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes) {
+ return DefineDynamicAssembly (name, access, null, null, null, null, null, false, assemblyAttributes);
+ }
+#endif
+
internal AssemblyBuilder DefineInternalDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
{
return new AssemblyBuilder (name, null, access, true);
{
if (rawAssembly == null)
throw new ArgumentNullException ("rawAssembly");
-
+
Assembly assembly = LoadAssemblyRaw (rawAssembly, rawSymbolStore, securityEvidence, refonly);
assembly.FromByteArray = true;
return assembly;
+2007-10-19 Zoltan Varga <vargaz@gmail.com>
+
+ * AppDomain.cs: Add NET 3.5 DefineDynamicAssembly () overloads.
+
+2007-10-13 Zoltan Varga <vargaz@gmail.com>
+
+ * Delegate.cs (CreateDelegate): Allow binding instance methods to
+ delegates with an extra argument, a NET 2.0 feature. Fixes #333647.
Fri Oct 12 08:11:50 CEST 2007 Paolo Molaro <lupus@ximian.com>
[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal extern void SetMulticastInvoke ();
+ private static bool arg_type_match (Type delArgType, Type argType) {
+ bool match = delArgType == argType;
+
+#if NET_2_0
+ // Delegate contravariance
+ if (!match) {
+ if (!delArgType.IsValueType && (delArgType != typeof (ValueType)) && (argType.IsAssignableFrom (delArgType)))
+ match = true;
+ }
+#endif
+ return match;
+ }
+
#if NET_2_0
public
#else
if (!type.IsSubclassOf (typeof (MulticastDelegate)))
throw new ArgumentException ("type is not a subclass of Multicastdelegate");
+#if !NET_2_0
if (!method.IsStatic)
if (throwOnBindFailure)
throw new ArgumentException ("The method should be static.", "method");
else
return null;
+#endif
MethodInfo invoke = type.GetMethod ("Invoke");
ParameterInfo[] delargs = invoke.GetParameters ();
ParameterInfo[] args = method.GetParameters ();
- if (args.Length != delargs.Length)
- if (throwOnBindFailure)
- throw new ArgumentException ("method argument length mismatch");
- else
- return null;
-
- int length = delargs.Length;
- for (int i = 0; i < length; i++) {
- bool match = delargs [i].ParameterType == args [i].ParameterType;
-
-#if NET_2_0
- // Delegate contravariance
- if (!match) {
- Type argType = delargs [i].ParameterType;
-
- if (!argType.IsValueType && (argType != typeof (ValueType)) && (args [i].ParameterType.IsAssignableFrom (argType)))
- match = true;
- }
-#endif
-
- if (!match)
+ bool argLengthMatch;
+ if (!method.IsStatic)
+ //
+ // Net 2.0 feature. The first argument of the delegate is passed
+ // as the 'this' argument to the method.
+ //
+ argLengthMatch = (args.Length + 1 == delargs.Length);
+ else
+ argLengthMatch = (args.Length == delargs.Length);
+ if (!argLengthMatch)
if (throwOnBindFailure)
- throw new ArgumentException ("method arguments are incompatible");
+ throw new ArgumentException ("method argument length mismatch");
else
return null;
+
+ bool argsMatch;
+ if (!method.IsStatic) {
+ // The first argument should match this
+ argsMatch = arg_type_match (delargs [0].ParameterType, method.DeclaringType);
+ for (int i = 0; i < args.Length; i++)
+ argsMatch &= arg_type_match (delargs [i + 1].ParameterType, args [i].ParameterType);
+ } else {
+ argsMatch = true;
+ for (int i = 0; i < args.Length; i++)
+ argsMatch &= arg_type_match (delargs [i].ParameterType, args [i].ParameterType);
}
+ if (!argsMatch)
+ if (throwOnBindFailure)
+ throw new ArgumentException ("method arguments are incompatible");
+ else
+ return null;
+
Delegate d = CreateDelegate_internal (type, null, method);
d.original_method_info = method;
return d;
+2007-10-14 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * RegistryKeyTest.cs: Added test for bug #322839.
+
2007-08-30 Gert Driesen <drieseng@users.sourceforge.net>
* RegistryKeyTest.cs: Improve SetValue tests to ensure values are
}
}
+ [Test] // bug #322839
+ [Category ("NotWorking")]
+ public void SetValue_EntityReferences ()
+ {
+ string subKeyName = Guid.NewGuid ().ToString ();
+
+ try {
+ using (RegistryKey createdKey = Registry.CurrentUser.CreateSubKey (subKeyName)) {
+ // we created a new subkey, so value should not exist
+ Assert.IsNull (createdKey.GetValue ("FirstName&\"<LastName>\""), "#A1");
+ // create value
+ createdKey.SetValue ("FirstName&\"<LastName>\"", "<'Miguel' & \"de Icaza\">!");
+ // get value
+ object name = createdKey.GetValue ("FirstName&\"<LastName>\"");
+ // value should exist
+ Assert.IsNotNull (name, "#A2");
+ // type of value should be string
+ Assert.AreEqual (typeof (string), name.GetType (), "#A3");
+ // ensure value matches
+ Assert.AreEqual ("<'Miguel' & \"de Icaza\">!", name, "#A4");
+
+ // we created a new subkey, so value should not exist
+ Assert.IsNull (createdKey.GetValue ("Info"), "#B1");
+ // create value
+ createdKey.SetValue ("Info", new string [] { "Mono&<Novell>!", "<CLR&BCL>" });
+ // get value
+ object info = createdKey.GetValue ("Info");
+ // value should exist
+ Assert.IsNotNull (info, "#B2");
+ // type of value should be string
+ Assert.AreEqual (typeof (string []), info.GetType (), "#B3");
+ // ensure value matches
+ Assert.AreEqual (new string [] { "Mono&<Novell>!", "<CLR&BCL>" }, info, "#B4");
+ }
+
+ using (RegistryKey openedKey = Registry.CurrentUser.OpenSubKey (subKeyName)) {
+ object name = openedKey.GetValue ("FirstName&\"<LastName>\"");
+ Assert.IsNotNull (name, "#C1");
+ Assert.AreEqual (typeof (string), name.GetType (), "#C2");
+ Assert.AreEqual ("<'Miguel' & \"de Icaza\">!", name, "#C3");
+
+ object info = openedKey.GetValue ("Info");
+ Assert.IsNotNull (info, "#D1");
+ Assert.AreEqual (typeof (string []), info.GetType (), "#D2");
+ Assert.AreEqual (new string [] { "Mono&<Novell>!", "<CLR&BCL>" }, info, "#D3");
+ }
+ } finally {
+ // clean-up
+ Registry.CurrentUser.DeleteSubKeyTree (subKeyName);
+ }
+ }
+
[Test]
public void SetValue_Name_Null ()
{
[Test]
[ExpectedException (typeof (ArgumentNullException))]
- public void SetValue_Null ()
+ public void SetValue_Value_Null ()
{
string subKeyName = Guid.NewGuid ().ToString ();
// create value
createdKey.SetValue ("Path", "/usr/lib/whatever");
// get value
- object value = createdKey.GetValue ("Path");
+ object path = createdKey.GetValue ("Path");
// value should exist
- Assert.IsNotNull (value, "#A2");
+ Assert.IsNotNull (path, "#A2");
// type of value should be string
- Assert.AreEqual (typeof (string), value.GetType (), "#A3");
+ Assert.AreEqual (typeof (string), path.GetType (), "#A3");
// ensure value matches
- Assert.AreEqual ("/usr/lib/whatever", value, "#A4");
+ Assert.AreEqual ("/usr/lib/whatever", path, "#A4");
}
using (RegistryKey openedKey = Registry.CurrentUser.OpenSubKey (subKeyName)) {
- object value = openedKey.GetValue ("Path");
- Assert.IsNotNull (value, "#B1");
- Assert.AreEqual (typeof (string), value.GetType (), "#B2");
- Assert.AreEqual ("/usr/lib/whatever", value, "#B3");
+ object path = openedKey.GetValue ("Path");
+ Assert.IsNotNull (path, "#B1");
+ Assert.AreEqual (typeof (string), path.GetType (), "#B2");
+ Assert.AreEqual ("/usr/lib/whatever", path, "#B3");
}
} finally {
// clean-up
+2007-10-15 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * ILGeneratorTest.cs: Improve test for DeclareLocal null check.
+ Added tests for null checks in Emit overloads.
+
2007-09-30 Gert Driesen <drieseng@users.sourceforge.net>
* DynamicMethodTest.cs: Marked test for bug #325444 as NotDotNet, and
using NUnit.Framework;
-namespace MonoTests.System.Reflection.Emit {
-
+namespace MonoTests.System.Reflection.Emit
+{
[TestFixture]
- public class ILGeneratorTest {
-
+ public class ILGeneratorTest
+ {
TypeBuilder tb;
ILGenerator il_gen;
- static TypeBuilder DefineDynType ()
- {
- AssemblyName assemblyName = new AssemblyName ();
- assemblyName.Name = "MonoTests.System.Reflection.Emit.ILGeneratorTest";
-
- AssemblyBuilder assembly = Thread.GetDomain ().DefineDynamicAssembly (
- assemblyName, AssemblyBuilderAccess.Run);
-
- ModuleBuilder module = assembly.DefineDynamicModule ("module1");
- return module.DefineType ("T", TypeAttributes.Public);
- }
-
void DefineBasicMethod ()
{
MethodBuilder mb = tb.DefineMethod("F",
[SetUp]
public void SetUp ()
- {
- tb = DefineDynType ();
+ {
+ AssemblyName assemblyName = new AssemblyName ();
+ assemblyName.Name = "MonoTests.System.Reflection.Emit.ILGeneratorTest";
+
+ AssemblyBuilder assembly = Thread.GetDomain ().DefineDynamicAssembly (
+ assemblyName, AssemblyBuilderAccess.Run);
+
+ ModuleBuilder module = assembly.DefineDynamicModule ("module1");
+ tb = module.DefineType ("T", TypeAttributes.Public);
}
[Test]
- [ExpectedException (typeof (ArgumentNullException))]
- public void DeclareLocal_NULL ()
+ public void DeclareLocal_LocalType_Null ()
{
DefineBasicMethod ();
- il_gen.DeclareLocal (null);
+ try {
+ il_gen.DeclareLocal (null);
+ Assert.Fail ("#A1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#A2");
+ Assert.IsNull (ex.InnerException, "#A3");
+ Assert.IsNotNull (ex.Message, "#A4");
+ Assert.IsNotNull (ex.ParamName, "#A5");
+ Assert.AreEqual ("localType", ex.ParamName, "#A");
+ }
+
+#if NET_2_0
+ try {
+ il_gen.DeclareLocal (null, false);
+ Assert.Fail ("#B1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ Assert.IsNotNull (ex.ParamName, "#B5");
+ Assert.AreEqual ("localType", ex.ParamName, "#B6");
+ }
+#endif
}
[Test]
public void DefineFilterBodyWithTypeNotNull ()
{
DefineBasicMethod ();
-
il_gen.BeginExceptionBlock ();
il_gen.EmitWriteLine ("in try");
il_gen.BeginExceptFilterBlock ();
il_gen.EmitWriteLine ("in filter body");
il_gen.EndExceptionBlock ();
}
-
- // Bug 81431
- [Test]
+
+ [Test] // bug #81431
public void FilterAndCatchBlock ()
{
DefineBasicMethod ();
il_gen.Emit (OpCodes.Ret);
}
+ [Test] // Emit (OpCode, ConstructorInfo)
+#if NET_2_0
+ [Category ("NotDotNet")] // MS bug: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304610
+#endif
+ public void Emit3_Constructor_Null ()
+ {
+ DefineBasicMethod ();
+ try {
+ il_gen.Emit (OpCodes.Newobj, (ConstructorInfo) null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ }
+ }
+
+#if NET_2_0
+ [Test] // Emit (OpCode, ConstructorInfo)
+ [Category ("NotWorking")] // MS bug: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304610
+ public void Emit3_Constructor_Null_MS ()
+ {
+ DefineBasicMethod ();
+ try {
+ il_gen.Emit (OpCodes.Newobj, (ConstructorInfo) null);
+ Assert.Fail ("#1");
+ } catch (NullReferenceException) {
+ }
+ }
+#endif
+
+ [Test] // Emit (OpCode, FieldInfo)
+ public void Emit5_Field_Null ()
+ {
+ DefineBasicMethod ();
+ try {
+ il_gen.Emit (OpCodes.Ldsfld, (FieldInfo) null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ }
+ }
+
+ [Test] // Emit (OpCode, Label [])
+ [Category ("NotDotNet")] // MS bug: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304610
+ public void Emit10_Labels_Null ()
+ {
+ DefineBasicMethod ();
+ try {
+ il_gen.Emit (OpCodes.Switch, (Label []) null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("labels", ex.ParamName, "#6");
+ }
+ }
+
+ [Test]
+ [Category ("NotWorking")] // MS bug: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304610
+ public void Emit10_Labels_Null_MS ()
+ {
+ DefineBasicMethod ();
+ try {
+ il_gen.Emit (OpCodes.Switch, (Label []) null);
+ Assert.Fail ("#1");
+ } catch (NullReferenceException) {
+ }
+ }
+
+ [Test] // Emit (OpCode, LocalBuilder)
+ public void Emit11_Local_Null ()
+ {
+ DefineBasicMethod ();
+ try {
+ il_gen.Emit (OpCodes.Switch, (LocalBuilder) null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("local", ex.ParamName, "#6");
+ }
+ }
+
+ [Test] // Emit (OpCode, MethodInfo)
+ public void Emit12_Method_Null ()
+ {
+ DefineBasicMethod ();
+ try {
+ il_gen.Emit (OpCodes.Switch, (MethodInfo) null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("meth", ex.ParamName, "#6");
+ }
+ }
+
+ [Test] // Emit (OpCode, SignatureHelper)
+ public void Emit14_Signature_Null ()
+ {
+ DefineBasicMethod ();
+ try {
+ il_gen.Emit (OpCodes.Switch, (SignatureHelper) null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ }
+ }
+
+ [Test] // Emit (OpCode, String)
+ public void Emit16_String_Null ()
+ {
+ DefineBasicMethod ();
+ try {
+ il_gen.Emit (OpCodes.Switch, (String) null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ }
+ }
+
+ [Test] // Emit (OpCode, Type)
+ public void Emit16_Type_Null ()
+ {
+ DefineBasicMethod ();
+ try {
+ il_gen.Emit (OpCodes.Switch, (Type) null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ }
+ }
+
+ [Test]
+ public void EmitCall_MethodInfo_Null ()
+ {
+ DefineBasicMethod ();
+ try {
+ il_gen.EmitCall (OpCodes.Call, (MethodInfo) null, null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("methodInfo", ex.ParamName, "#6");
+ }
+ }
+
[Test]
public void TestFilterEmittingWithHandlerExecution ()
{
Assert.IsNull (obj, "#03");
}
- [Test]
+ [Test] // bug #49114
#if NET_2_0
[Category ("NotWorking")]
[ExpectedException (typeof (ArgumentException))]
#else
[ExpectedException (typeof (TypeLoadException))]
#endif
- public void TestGetType ()
+ public void GetType_TypeName_Invalid ()
{
- // Bug #49114
typeof (int).Assembly.GetType ("&blabla", true, true);
}
+ [Test] // bug #334203
+ public void GetType_TypeName_AssemblyName ()
+ {
+ Assembly a = typeof (int).Assembly;
+ string typeName = typeof (string).AssemblyQualifiedName;
+ try {
+ a.GetType (typeName, true, false);
+ Assert.Fail ("#A1");
+#if NET_2_0
+ } catch (ArgumentException ex) {
+ Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A2");
+ Assert.IsNull (ex.InnerException, "#A3");
+ Assert.IsNotNull (ex.Message, "#A4");
+ Assert.IsNull (ex.ParamName, "#A5");
+ }
+#else
+ } catch (TypeLoadException ex) {
+ Assert.AreEqual (typeof (TypeLoadException), ex.GetType (), "#A2");
+ Assert.IsNull (ex.InnerException, "#A3");
+ Assert.IsNotNull (ex.Message, "#A4");
+ Assert.IsTrue (ex.Message.IndexOf (typeName) != -1, "#A5");
+ }
+#endif
+
+ Type type = a.GetType (typeName, false);
+ Assert.IsNull (type, "#B1");
+ type = a.GetType (typeName, false, true);
+ Assert.IsNull (type, "#B2");
+ }
+
[Test]
public void GetEntryAssembly ()
{
+2007-10-17 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * AssemblyTest.cs: Enabled test for bug #334204.
+
+2007-10-16 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * AssemblyTest.cs: Added test for bug #334203. Use more meaningful name
+ for test for bug #49114.
+
2007-10-04 Raja R Harinath <rharinath@novell.com>
* AssemblyTest.cs (bug328812): New test.
+2007-10-14 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * SecurityElementTest.cs: Added tests for using single quotes as
+ delimiter of which one passes on Mono and one on MS (due to bug).
+
+2007-10-14 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * SecurityElementTest.cs: Modified test for bug #333699 to use double
+ quote as delimiter to work around MS bug. Added test for bug #333725.
+
+2007-10-14 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * SecurityElementTest.cs: No longer derive from Assertion. Added and
+ improved ctor tests. Improved AddAttribute and AddChild tests.
+ Added comment to mono's Attributes test and added test that passes
+ on MS (to track fix for MS bug). Improved IsValid* tests. Added tests
+ for Tag and Text. Improved FromString test to verify behavior wrt
+ namespace prefixes. Added test for bug #333699.
+
2005-10-28 Sebastien Pouliot <sebastien@ximian.com>
* SecureStringCas.cs: New. CAS unit tests for SecureString.
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
-using NUnit.Framework;
using System;
using System.Collections;
+using System.Globalization;
using System.Security;
+using NUnit.Framework;
+
namespace MonoTests.System.Security {
[TestFixture]
- public class SecurityElementTest : Assertion {
+ public class SecurityElementTest {
SecurityElement elem;
elem.AddAttribute ("class", "System");
elem.AddAttribute ("version", "1");
- SecurityElement child = new SecurityElement ("ConnectAccess");
+ SecurityElement child = new SecurityElement ("ConnectAccess");
elem.AddChild (child);
- SecurityElement grandchild = new SecurityElement ("ENDPOINT", "some text");
+ SecurityElement grandchild = new SecurityElement ("ENDPOINT", "some text");
grandchild.AddAttribute ("transport", "All");
grandchild.AddAttribute ("host", "localhost");
grandchild.AddAttribute ("port", "8080");
child.AddChild (grandchild);
- SecurityElement grandchild2 = new SecurityElement ("ENDPOINT");
+ SecurityElement grandchild2 = new SecurityElement ("ENDPOINT");
grandchild2.AddAttribute ("transport", "Tcp");
grandchild2.AddAttribute ("host", "www.ximian.com");
grandchild2.AddAttribute ("port", "All");
- child.AddChild (grandchild2);
+ child.AddChild (grandchild2);
- return elem;
+ return elem;
}
[Test]
- public void ConstructorsTagTest ()
+ public void Constructor1 ()
{
- SecurityElement se = new SecurityElement ("tag", "text");
- AssertNull ("EmptyAttributes", se.Attributes);
- AssertNull ("EmptyChildren", se.Children);
- AssertEquals ("Tag", "tag", se.Tag);
- AssertEquals ("Text", "text", se.Text);
+ SecurityElement se = new SecurityElement ("tag");
+ Assert.IsNull (se.Attributes, "#A1");
+ Assert.IsNull (se.Children, "#A2");
+ Assert.AreEqual ("tag", se.Tag, "#A3");
+ Assert.IsNull (se.Text, "#A4");
+
+ se = new SecurityElement (string.Empty);
+ Assert.IsNull (se.Attributes, "#B1");
+ Assert.IsNull (se.Children, "#B2");
+ Assert.AreEqual (string.Empty, se.Tag, "#B3");
+ Assert.IsNull (se.Text, "#B4");
}
[Test]
- [ExpectedException (typeof (ArgumentNullException))]
- public void ConstructorsTagNullText ()
+ public void Constructor1_Tag_Invalid ()
{
- SecurityElement se = new SecurityElement (null, "text");
+ try {
+ new SecurityElement ("Na<me");
+ Assert.Fail ("#A1");
+ } catch (ArgumentException ex) {
+ // Invalid element tag Nam<e
+ Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A2");
+ Assert.IsNull (ex.InnerException, "#A3");
+ Assert.IsNotNull (ex.Message, "#A4");
+ Assert.IsTrue (ex.Message.IndexOf ("Na<me") != -1, "#A5");
+ Assert.IsNull (ex.ParamName, "#A6");
+ }
+
+ try {
+ new SecurityElement ("Nam>e");
+ Assert.Fail ("#B1");
+ } catch (ArgumentException ex) {
+ // Invalid element tag Nam>e
+ Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ Assert.IsTrue (ex.Message.IndexOf ("Nam>e") != -1, "#B5");
+ Assert.IsNull (ex.ParamName, "#B6");
+ }
}
[Test]
- public void ConstructorsTagTextNull ()
+ public void Constructor1_Tag_Null ()
{
- SecurityElement se = new SecurityElement ("tag", null);
- AssertNull ("EmptyAttributes", se.Attributes);
- AssertNull ("EmptyChildren", se.Children);
- AssertEquals ("Tag", "tag", se.Tag);
- AssertNull ("Text", se.Text);
+ try {
+ new SecurityElement (null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("tag", ex.ParamName, "#6");
+ }
}
[Test]
- public void ConstructorsTag ()
+ public void Constructor2 ()
{
- SecurityElement se = new SecurityElement ("tag");
- AssertNull ("EmptyAttributes", se.Attributes);
- AssertNull ("EmptyChildren", se.Children);
- AssertEquals ("Tag", "tag", se.Tag);
- AssertNull ("Text", se.Text);
+ SecurityElement se = new SecurityElement ("tag", "text");
+ Assert.IsNull (se.Attributes, "EmptyAttributes");
+ Assert.IsNull (se.Children, "EmptyChildren");
+ Assert.AreEqual ("tag", se.Tag, "Tag");
+ Assert.AreEqual ("text", se.Text, "Text");
}
[Test]
- [ExpectedException (typeof (ArgumentNullException))]
- public void ConstructorsTagNull ()
+ public void Constructor2_Tag_Invalid ()
{
- SecurityElement se = new SecurityElement (null);
+ try {
+ new SecurityElement ("Na<me", "text");
+ Assert.Fail ("#A1");
+ } catch (ArgumentException ex) {
+ // Invalid element tag Nam<e
+ Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A2");
+ Assert.IsNull (ex.InnerException, "#A3");
+ Assert.IsNotNull (ex.Message, "#A4");
+ Assert.IsTrue (ex.Message.IndexOf ("Na<me") != -1, "#A5");
+ Assert.IsNull (ex.ParamName, "#A6");
+ }
+
+ try {
+ new SecurityElement ("Nam>e", "text");
+ Assert.Fail ("#B1");
+ } catch (ArgumentException ex) {
+ // Invalid element tag Nam>e
+ Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ Assert.IsTrue (ex.Message.IndexOf ("Nam>e") != -1, "#B5");
+ Assert.IsNull (ex.ParamName, "#B6");
+ }
}
-
+
[Test]
- [ExpectedException (typeof (ArgumentNullException))]
- public void AddAttribute_NameNullValue ()
+ public void Constructor2_Tag_Null ()
{
- elem.AddAttribute (null, "valid");
+ try {
+ new SecurityElement (null, "text");
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("tag", ex.ParamName, "#6");
+ }
}
[Test]
- [ExpectedException (typeof (ArgumentNullException))]
- public void AddAttribute_NameValueNull ()
+ public void Constructor2_Text_Null ()
{
- elem.AddAttribute ("valid", null);
+ SecurityElement se = new SecurityElement ("tag", null);
+ Assert.IsNull (se.Attributes, "EmptyAttributes");
+ Assert.IsNull (se.Children, "EmptyChildren");
+ Assert.AreEqual ("tag", se.Tag, "Tag");
+ Assert.IsNull (se.Text, "Text");
+ }
+
+ [Test]
+ public void AddAttribute_Name_Null ()
+ {
+ try {
+ elem.AddAttribute (null, "valid");
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("name", ex.ParamName, "#6");
+ }
+ }
+
+ [Test]
+ public void AddAttribute_Value_Null ()
+ {
+ try {
+ elem.AddAttribute ("valid", null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("value", ex.ParamName, "#6");
+ }
}
[Test]
[ExpectedException (typeof (ArgumentException))]
- public void AddAttribute_InvalidName ()
+ public void AddAttribute_Name_Invalid ()
{
elem.AddAttribute ("<invalid>", "valid");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
- public void AddAttribute_InvalidValue ()
+ public void AddAttribute_Value_Invalid ()
{
elem.AddAttribute ("valid", "invalid\"");
}
}
[Test]
- [ExpectedException (typeof (ArgumentNullException))]
public void AddChild_Null ()
{
- elem.AddChild (null);
+ try {
+ elem.AddChild (null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("child", ex.ParamName, "#6");
+ }
}
[Test]
int n = elem.Children.Count;
// add itself
elem.AddChild (elem);
- AssertEquals ("Count", (n+1), elem.Children.Count);
+ Assert.AreEqual ((n + 1), elem.Children.Count, "Count");
}
[Test]
- [ExpectedException (typeof (ArgumentException))]
- [Category ("NotDotNet")] // this will result in an InvalidCastException on MS.Net - I have no clue why
- public void Attributes_StrangeCase ()
+ [Category ("NotDotNet")] // MS bug: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304549
+ public void Attributes_Name_Invalid ()
{
Hashtable h = elem.Attributes;
h.Add ("<invalid>", "valid");
- elem.Attributes = h;
+ try {
+ elem.Attributes = h;
+ Assert.Fail ("#1");
+ } catch (ArgumentException ex) {
+ // Invalid attribute name '<invalid>'
+ Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsTrue (ex.Message.IndexOf ("<invalid>") != -1, "#5");
+ Assert.IsNull (ex.ParamName, "#6");
+ }
}
[Test]
- [ExpectedException (typeof (ArgumentException))]
- public void Attributes_ArgumentException ()
+ [Category ("NotWorking")] // MS bug: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304549
+ public void Attributes_Name_Invalid_MS ()
+ {
+ Hashtable h = elem.Attributes;
+ h.Add ("<invalid>", "valid");
+ try {
+ elem.Attributes = h;
+ Assert.Fail ();
+ } catch (InvalidCastException) {
+ }
+ }
+
+ [Test]
+ public void Attributes_Value_Invalid ()
{
Hashtable h = elem.Attributes;
h.Add ("valid", "\"invalid\"");
- elem.Attributes = h;
+ try {
+ elem.Attributes = h;
+ Assert.Fail ("#1");
+ } catch (ArgumentException ex) {
+ // Invalid attribute value '"invalid"'
+ Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsTrue (ex.Message.IndexOf ("\"invalid\"") != -1, "#5");
+ Assert.IsNull (ex.ParamName, "#6");
+ }
}
[Test]
h = elem.Attributes;
h.Add ("foo", "bar");
- Assert ("#1", elem.Attributes.Count != h.Count);
+ Assert.IsTrue (elem.Attributes.Count != h.Count, "#1");
elem.Attributes = h;
- AssertNotNull ("#2", elem.Attribute ("foo"));
+ Assert.IsNotNull (elem.Attribute ("foo"), "#2");
}
[Test]
int iTest = 0;
SecurityElement elem2 = CreateElement ();
iTest++;
- Assert ("#1", elem.Equal (elem2));
+ Assert.IsTrue (elem.Equal (elem2), "#1");
iTest++;
SecurityElement child = (SecurityElement) elem2.Children [0];
iTest++;
iTest++;
child.Text = "some text";
iTest++;
- Assert ("#2", !elem.Equal (elem2));
+ Assert.IsFalse (elem.Equal (elem2), "#2");
}
[Test]
public void Escape ()
{
- AssertEquals ("#1", "foo<>"'& bar", SecurityElement.Escape ("foo<>\"'& bar"));
+ Assert.AreEqual ("foo<>"'& bar",
+ SecurityElement.Escape ("foo<>\"'& bar"), "#1");
+ Assert.IsNull (SecurityElement.Escape (null), "#2");
}
-
+
[Test]
public void IsValidAttributeName ()
{
- Assert ("#1", !SecurityElement.IsValidAttributeName ("x x"));
- Assert ("#2", !SecurityElement.IsValidAttributeName ("x<x"));
- Assert ("#3", !SecurityElement.IsValidAttributeName ("x>x"));
- Assert ("#4", SecurityElement.IsValidAttributeName ("x\"x"));
- Assert ("#5", SecurityElement.IsValidAttributeName ("x'x"));
- Assert ("#6", SecurityElement.IsValidAttributeName ("x&x"));
+ Assert.IsFalse (SecurityElement.IsValidAttributeName ("x x"), "#1");
+ Assert.IsFalse (SecurityElement.IsValidAttributeName ("x<x"), "#2");
+ Assert.IsFalse (SecurityElement.IsValidAttributeName ("x>x"), "#3");
+ Assert.IsTrue (SecurityElement.IsValidAttributeName ("x\"x"), "#4");
+ Assert.IsTrue (SecurityElement.IsValidAttributeName ("x'x"), "#5");
+ Assert.IsTrue (SecurityElement.IsValidAttributeName ("x&x"), "#6");
+ Assert.IsFalse (SecurityElement.IsValidAttributeName (null), "#7");
+ Assert.IsTrue (SecurityElement.IsValidAttributeName (string.Empty), "#8");
}
[Test]
public void IsValidAttributeValue ()
{
- Assert ("#1", SecurityElement.IsValidAttributeValue ("x x"));
- Assert ("#2", !SecurityElement.IsValidAttributeValue ("x<x"));
- Assert ("#3", !SecurityElement.IsValidAttributeValue ("x>x"));
- Assert ("#4", !SecurityElement.IsValidAttributeValue ("x\"x"));
- Assert ("#5", SecurityElement.IsValidAttributeValue ("x'x"));
- Assert ("#6", SecurityElement.IsValidAttributeValue ("x&x"));
+ Assert.IsTrue (SecurityElement.IsValidAttributeValue ("x x"), "#1");
+ Assert.IsFalse (SecurityElement.IsValidAttributeValue ("x<x"), "#2");
+ Assert.IsFalse (SecurityElement.IsValidAttributeValue ("x>x"), "#3");
+ Assert.IsFalse (SecurityElement.IsValidAttributeValue ("x\"x"), "#4");
+ Assert.IsTrue (SecurityElement.IsValidAttributeValue ("x'x"), "#5");
+ Assert.IsTrue (SecurityElement.IsValidAttributeValue ("x&x"), "#6");
+ Assert.IsFalse (SecurityElement.IsValidAttributeValue (null), "#7");
+ Assert.IsTrue (SecurityElement.IsValidAttributeValue (string.Empty), "#8");
}
[Test]
public void IsValidTag ()
{
- Assert ("#1", !SecurityElement.IsValidTag ("x x"));
- Assert ("#2", !SecurityElement.IsValidTag ("x<x"));
- Assert ("#3", !SecurityElement.IsValidTag ("x>x"));
- Assert ("#4", SecurityElement.IsValidTag ("x\"x"));
- Assert ("#5", SecurityElement.IsValidTag ("x'x"));
- Assert ("#6", SecurityElement.IsValidTag ("x&x"));
+ Assert.IsFalse (SecurityElement.IsValidTag ("x x"), "#1");
+ Assert.IsFalse (SecurityElement.IsValidTag ("x<x"), "#2");
+ Assert.IsFalse (SecurityElement.IsValidTag ("x>x"), "#3");
+ Assert.IsTrue (SecurityElement.IsValidTag ("x\"x"), "#4");
+ Assert.IsTrue (SecurityElement.IsValidTag ("x'x"), "#5");
+ Assert.IsTrue (SecurityElement.IsValidTag ("x&x"), "#6");
+ Assert.IsFalse (SecurityElement.IsValidTag (null), "#7");
+ Assert.IsTrue (SecurityElement.IsValidTag (string.Empty), "#8");
}
[Test]
public void IsValidText ()
{
- Assert ("#1", SecurityElement.IsValidText ("x x"));
- Assert ("#2", !SecurityElement.IsValidText ("x<x"));
- Assert ("#3", !SecurityElement.IsValidText ("x>x"));
- Assert ("#4", SecurityElement.IsValidText ("x\"x"));
- Assert ("#5", SecurityElement.IsValidText ("x'x"));
- Assert ("#6", SecurityElement.IsValidText ("x&x"));
+ Assert.IsTrue (SecurityElement.IsValidText ("x x"), "#1");
+ Assert.IsFalse (SecurityElement.IsValidText ("x<x"), "#2");
+ Assert.IsFalse (SecurityElement.IsValidText ("x>x"), "#3");
+ Assert.IsTrue (SecurityElement.IsValidText ("x\"x"), "#4");
+ Assert.IsTrue (SecurityElement.IsValidText ("x'x"), "#5");
+ Assert.IsTrue (SecurityElement.IsValidText ("x&x"), "#6");
+ Assert.IsFalse (SecurityElement.IsValidText (null), "#7");
+ Assert.IsTrue (SecurityElement.IsValidText (string.Empty), "#8");
}
[Test]
- [ExpectedException (typeof (ArgumentNullException))]
public void SearchForChildByTag_Null ()
{
- SecurityElement child = elem.SearchForChildByTag (null);
+ try {
+ elem.SearchForChildByTag (null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("tag", ex.ParamName, "#6");
+ }
}
[Test]
public void SearchForChildByTag ()
{
- SecurityElement child = elem.SearchForChildByTag ("doesnotexist");
- AssertNull ("#1", child);
+ SecurityElement child = elem.SearchForChildByTag ("doesnotexist");
+ Assert.IsNull (child, "#1");
child = elem.SearchForChildByTag ("ENDPOINT");
- AssertNull ("#2", child);
+ Assert.IsNull (child, "#2");
child = (SecurityElement) elem.Children [0];
child = child.SearchForChildByTag ("ENDPOINT");
- AssertEquals ("#3", "All", child.Attribute ("transport"));
+ Assert.AreEqual ("All", child.Attribute ("transport"), "#3");
}
[Test]
- [ExpectedException (typeof (ArgumentNullException))]
- public void SearchForTextOfTag_Null ()
+ public void SearchForTextOfTag_Tag_Null ()
{
- string s = elem.SearchForTextOfTag (null);
+ try {
+ elem.SearchForTextOfTag (null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("tag", ex.ParamName, "#6");
+ }
}
[Test]
public void SearchForTextOfTag ()
{
string s = elem.SearchForTextOfTag ("ENDPOINT");
- AssertEquals ("SearchForTextOfTag", "some text", s);
+ Assert.AreEqual ("some text", s);
+ }
+
+ [Test]
+ public void Tag ()
+ {
+ SecurityElement se = new SecurityElement ("Values");
+ Assert.AreEqual ("Values", se.Tag, "#A1");
+ Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
+ "<Values/>{0}", Environment.NewLine),
+ se.ToString (), "#A2");
+ se.Tag = "abc:Name";
+ Assert.AreEqual ("abc:Name", se.Tag, "#B1");
+ Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
+ "<abc:Name/>{0}", Environment.NewLine),
+ se.ToString (), "#B2");
+ se.Tag = "Name&Address";
+ Assert.AreEqual ("Name&Address", se.Tag, "#C1");
+ Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
+ "<Name&Address/>{0}", Environment.NewLine),
+ se.ToString (), "#C2");
+ se.Tag = string.Empty;
+ Assert.AreEqual (string.Empty, se.Tag, "#D1");
+ Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
+ "</>{0}", Environment.NewLine),
+ se.ToString (), "#D2");
+ }
+
+ [Test]
+ public void Tag_Invalid ()
+ {
+ SecurityElement se = new SecurityElement ("Values");
+
+ try {
+ se.Tag = "Na<me";
+ Assert.Fail ("#A1");
+ } catch (ArgumentException ex) {
+ // Invalid element tag Nam<e
+ Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A2");
+ Assert.IsNull (ex.InnerException, "#A3");
+ Assert.IsNotNull (ex.Message, "#A4");
+ Assert.IsTrue (ex.Message.IndexOf ("Na<me") != -1, "#A5");
+ Assert.IsNull (ex.ParamName, "#A6");
+ }
+
+ try {
+ se.Tag = "Nam>e";
+ Assert.Fail ("#B1");
+ } catch (ArgumentException ex) {
+ // Invalid element tag Nam>e
+ Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ Assert.IsTrue (ex.Message.IndexOf ("Nam>e") != -1, "#B5");
+ Assert.IsNull (ex.ParamName, "#B6");
+ }
}
[Test]
- [ExpectedException (typeof (ArgumentNullException))]
public void Tag_Null ()
{
- elem.Tag = null;
- AssertNull ("Tag", elem.Tag);
+ try {
+ elem.Tag = null;
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("Tag", ex.ParamName, "#6");
+ }
}
[Test]
- public void Text_Null ()
+ public void Text ()
{
+ elem.Text = "Miguel&Sébastien";
+ Assert.AreEqual ("Miguel&Sébastien", elem.Text, "#1");
elem.Text = null;
- AssertNull ("Text", elem.Text);
+ Assert.IsNull (elem.Text, "#2");
+ elem.Text = "Sébastien\"Miguel";
+ Assert.AreEqual ("Sébastien\"Miguel", elem.Text, "#3");
+ elem.Text = string.Empty;
+ Assert.AreEqual (string.Empty, elem.Text, "#4");
+ }
+
+ [Test]
+ public void Text_Invalid ()
+ {
+ try {
+ elem.Text = "Mig<uelSébastien";
+ Assert.Fail ("#A1");
+ } catch (ArgumentException ex) {
+ // Invalid element tag Mig<uelSébastien
+ Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A2");
+ Assert.IsNull (ex.InnerException, "#A3");
+ Assert.IsNotNull (ex.Message, "#A4");
+ Assert.IsTrue (ex.Message.IndexOf ("Mig<uelSébastien") != -1, "#A5");
+ Assert.IsNull (ex.ParamName, "#A6");
+ }
+
+ try {
+ elem.Text = "Mig>uelSébastien";
+ Assert.Fail ("#B1");
+ } catch (ArgumentException ex) {
+ // Invalid element tag Mig>uelSébastien
+ Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2");
+ Assert.IsNull (ex.InnerException, "#B3");
+ Assert.IsNotNull (ex.Message, "#B4");
+ Assert.IsTrue (ex.Message.IndexOf ("Mig>uelSébastien") != -1, "#B5");
+ Assert.IsNull (ex.ParamName, "#B6");
+ }
}
[Test]
#else
string expected = String.Format ("<Multiple Attribute1=\"One\"{0} Attribute2=\"Two\"/>{0}", Environment.NewLine);
#endif
- AssertEquals ("ToString()", expected, se.ToString ());
+ Assert.AreEqual (expected, se.ToString (), "ToString()");
}
#if NET_2_0
{
SecurityElement se = SecurityElement.FromString ("<tag attribute=\"value\"><child attr=\"1\">mono</child><child/></tag>");
SecurityElement copy = se.Copy ();
- Assert ("se!ReferenceEquals", !Object.ReferenceEquals (se, copy));
- Assert ("c1=ReferenceEquals", Object.ReferenceEquals (se.Children [0], copy.Children [0]));
- Assert ("c2=ReferenceEquals", Object.ReferenceEquals (se.Children [1], copy.Children [1]));
+ Assert.IsFalse (Object.ReferenceEquals (se, copy), "se!ReferenceEquals");
+ Assert.IsTrue (Object.ReferenceEquals (se.Children [0], copy.Children [0]), "c1=ReferenceEquals");
+ Assert.IsTrue (Object.ReferenceEquals (se.Children [1], copy.Children [1]), "c2=ReferenceEquals");
}
[Test]
- [ExpectedException (typeof (ArgumentNullException))]
public void FromString_Null ()
{
- SecurityElement.FromString (null);
+ try {
+ SecurityElement.FromString (null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("xml", ex.ParamName, "#6");
+ }
}
[Test]
[Test]
public void FromString ()
{
- SecurityElement se = SecurityElement.FromString ("<tag attribute=\"value\"><child attr=\"1\">mono</child><child/></tag>");
- AssertEquals ("Tag", "tag", se.Tag);
- AssertNull ("Text", se.Text);
- AssertEquals ("Attribute.Count", 1, se.Attributes.Count);
- AssertEquals ("Attribute", "value", se.Attribute ("attribute"));
- AssertEquals ("Children.Count", 2, se.Children.Count);
+ SecurityElement se = SecurityElement.FromString ("<tag attribute=\"value\"><x:child attr=\"1\">mono</x:child><child/></tag>");
+ Assert.AreEqual ("tag", se.Tag, "#A1");
+ Assert.IsNull (se.Text, "#A2");
+ Assert.AreEqual (1, se.Attributes.Count, "#A3");
+ Assert.AreEqual ("value", se.Attribute ("attribute"), "#A4");
+ Assert.AreEqual (2, se.Children.Count, "#A5");
SecurityElement child = (SecurityElement) se.Children [0];
- AssertEquals ("Child1.Tag", "child", child.Tag);
- AssertEquals ("Child1.Text", "mono", child.Text);
- AssertEquals ("Child1.Attribute.Count", 1, child.Attributes.Count);
- AssertEquals ("Child1.Attribute", "1", child.Attribute ("attr"));
+ Assert.AreEqual ("x:child", child.Tag, "#B1");
+ Assert.AreEqual ("mono", child.Text, "#B2");
+ Assert.AreEqual (1, child.Attributes.Count, "#B3");
+ Assert.AreEqual ("1", child.Attribute ("attr"), "#B4");
child = (SecurityElement) se.Children [1];
- AssertEquals ("Child2.Tag", "child", child.Tag);
- AssertNull ("Child2.Text", child.Text);
- AssertNull ("Child2.Attribute", child.Attributes);
+ Assert.AreEqual ("child", child.Tag, "#C1");
+ Assert.IsNull (child.Text, "#C2");
+ Assert.IsNull (child.Attributes, "#C3");
+ }
+
+ [Test]
+ [Category ("NotDotNet")] // MS bug: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304583
+ public void FromString_Quote_Delimiter ()
+ {
+ const string xml = "<value name='Company'>Novell</value>";
+ SecurityElement se = SecurityElement.FromString (xml);
+ Assert.AreEqual ("Company", se.Attribute ("name"), "#1");
+ Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
+ "<value name=\"Company\">Novell</value>{0}",
+ Environment.NewLine), se.ToString (), "#2");
+ }
+
+ [Test]
+ [Category ("NotWorking")] // MS bug: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304583
+ public void FromString_Quote_Delimiter_MS ()
+ {
+ const string xml = "<value name='Company'>Novell</value>";
+ SecurityElement se = SecurityElement.FromString (xml);
+ Assert.AreEqual ("'Company'", se.Attribute ("name"), "#1");
+ Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
+ "<value name=\"'Company'\">Novell</value>{0}",
+ Environment.NewLine), se.ToString (), "#2");
+ }
+
+ [Test] // bug #333699
+ [Category ("NotWorking")]
+ public void FromString_EntityReferences ()
+ {
+ const string xml = @"
+ <values>
+ <value name="""name"&<address>""><'Suds' & "Soda">!</value>
+ </values>";
+
+ SecurityElement se = SecurityElement.FromString (xml);
+ Assert.IsNotNull (se, "#A1");
+ Assert.IsNull (se.Attributes, "#A2");
+ Assert.IsNotNull (se.Children, "#A3");
+ Assert.AreEqual (1, se.Children.Count, "#A4");
+ Assert.AreEqual ("values", se.Tag, "#A5");
+ Assert.IsNull (se.Text, "#A6");
+
+ SecurityElement child = se.Children [0] as SecurityElement;
+ Assert.IsNotNull (child, "#B1");
+ Assert.IsNotNull (child.Attributes, "#B2");
+ Assert.AreEqual ("\"name\"&<address>", child.Attribute ("name"), "#B3");
+ Assert.AreEqual ("value", child.Tag, "#B4");
+ Assert.AreEqual ("<'Suds' & \"Soda\">!", child.Text, "#B5");
+ Assert.IsNull (child.Children, "#B6");
+ }
+
+ [Test] // bug #333725
+ [Category ("NotWorking")]
+ public void FromString_CharacterReferences ()
+ {
+ const string xml = @"
+ <value name=""name&address"">Suds&Soda&</value>";
+
+ SecurityElement se = SecurityElement.FromString (xml);
+ Assert.IsNotNull (se, "#1");
+ Assert.IsNotNull (se.Attributes, "#2");
+ Assert.AreEqual ("name&address", se.Attribute ("name"), "#3");
+ Assert.AreEqual ("value", se.Tag, "#4");
+ Assert.AreEqual ("Suds&Soda&", se.Text, "#5");
+ Assert.IsNull (se.Children, "#6");
}
#endif
}
//
// <c> 2002 Mike Kestner
-using NUnit.Framework;
-using System.Text;
using System;
+using System.Text;
+using NUnit.Framework;
-namespace MonoTests.System.Text {
-
- public class ASCIIEncodingTest : TestCase {
-
+namespace MonoTests.System.Text
+{
+ public class ASCIIEncodingTest
+ {
private char[] testchars;
private byte[] testbytes;
- protected override void SetUp ()
+ [SetUp]
+ public void SetUp ()
{
testchars = new char[4];
testchars[0] = 'T';
testbytes[3] = (byte) 't';
}
- // Test GetBytes(char[])
+ [Test]
+ public void IsBrowserDisplay ()
+ {
+ Assert.IsFalse (Encoding.ASCII.IsBrowserDisplay);
+ }
+
+ [Test]
+ public void IsBrowserSave ()
+ {
+ Assert.IsFalse (Encoding.ASCII.IsBrowserSave);
+ }
+
+ [Test]
+ public void IsMailNewsDisplay ()
+ {
+ Assert.IsFalse (Encoding.ASCII.IsMailNewsDisplay);
+ }
+
+ [Test]
+ public void IsMailNewsSave ()
+ {
+ Assert.IsFalse (Encoding.ASCII.IsMailNewsSave);
+ }
+
+ [Test] // Test GetBytes(char[])
public void TestGetBytes1 ()
{
- Encoding ascii_encoding = Encoding.ASCII;
+ Encoding ascii_encoding = Encoding.ASCII;
byte[] bytes = ascii_encoding.GetBytes(testchars);
for (int i = 0; i < testchars.Length; i++)
- AssertEquals (testchars[i], (char) bytes[i]);
- }
+ Assert.AreEqual (testchars[i], (char) bytes[i]);
+ }
- // Test GetBytes(char[], int, int)
+ [Test] // Test GetBytes(char[], int, int)
public void TestGetBytes2 ()
{
- Encoding ascii_encoding = Encoding.ASCII;
+ Encoding ascii_encoding = Encoding.ASCII;
byte[] bytes = ascii_encoding.GetBytes(testchars, 1, 1);
- AssertEquals (1, bytes.Length);
- AssertEquals (testchars[1], (char) bytes[0]);
- }
+ Assert.AreEqual (1, bytes.Length, "#1");
+ Assert.AreEqual (testchars [1], (char) bytes [0], "#2");
+ }
- // Test non-ASCII char in char[]
+ [Test] // Test non-ASCII char in char[]
public void TestGetBytes3 ()
{
- Encoding ascii_encoding = Encoding.ASCII;
+ Encoding ascii_encoding = Encoding.ASCII;
testchars[2] = (char) 0x80;
byte[] bytes = ascii_encoding.GetBytes(testchars);
- AssertEquals ('T', (char) bytes[0]);
- AssertEquals ('e', (char) bytes[1]);
- AssertEquals ('?', (char) bytes[2]);
- AssertEquals ('t', (char) bytes[3]);
- }
+ Assert.AreEqual ('T', (char) bytes [0], "#1");
+ Assert.AreEqual ('e', (char) bytes [1], "#2");
+ Assert.AreEqual ('?', (char) bytes [2], "#3");
+ Assert.AreEqual ('t', (char) bytes [3], "#4");
+ }
- // Test GetBytes(char[], int, int, byte[], int)
+ [Test] // Test GetBytes(char[], int, int, byte[], int)
public void TestGetBytes4 ()
{
- Encoding ascii_encoding = Encoding.ASCII;
+ Encoding ascii_encoding = Encoding.ASCII;
byte[] bytes = new Byte[1];
int cnt = ascii_encoding.GetBytes(testchars, 1, 1, bytes, 0);
- AssertEquals (1, cnt);
- AssertEquals (testchars[1], (char) bytes[0]);
- }
+ Assert.AreEqual (1, cnt, "#1");
+ Assert.AreEqual (testchars [1], (char) bytes [0], "#2");
+ }
- // Test GetBytes(string, int, int, byte[], int)
+ [Test] // Test GetBytes(string, int, int, byte[], int)
public void TestGetBytes5 ()
{
- Encoding ascii_encoding = Encoding.ASCII;
+ Encoding ascii_encoding = Encoding.ASCII;
byte[] bytes = new Byte[1];
int cnt = ascii_encoding.GetBytes("Test", 1, 1, bytes, 0);
- AssertEquals ('e', (char) bytes[0]);
- }
+ Assert.AreEqual ('e', (char) bytes [0], "#1");
+ }
- // Test GetBytes(string)
+ [Test] // Test GetBytes(string)
public void TestGetBytes6 ()
{
- Encoding ascii_encoding = Encoding.ASCII;
+ Encoding ascii_encoding = Encoding.ASCII;
byte[] bytes = ascii_encoding.GetBytes("Test");
for (int i = 0; i < testchars.Length; i++)
- AssertEquals (testchars[i], (char) bytes[i]);
- }
+ Assert.AreEqual (testchars [i], (char) bytes [i]);
+ }
- // Test GetChars(byte[])
+ [Test] // Test GetChars(byte[])
public void TestGetChars1 ()
{
- Encoding ascii_encoding = Encoding.ASCII;
+ Encoding ascii_encoding = Encoding.ASCII;
char[] chars = ascii_encoding.GetChars(testbytes);
for (int i = 0; i < testbytes.Length; i++)
- AssertEquals (testbytes[i], (byte) chars[i]);
- }
+ Assert.AreEqual (testbytes[i], (byte) chars[i]);
+ }
- // Test GetChars(byte[], int, int)
+ [Test] // Test GetChars(byte[], int, int)
public void TestGetChars2 ()
{
- Encoding ascii_encoding = Encoding.ASCII;
+ Encoding ascii_encoding = Encoding.ASCII;
char[] chars = ascii_encoding.GetChars(testbytes, 1, 1);
- AssertEquals (1, chars.Length);
- AssertEquals (testbytes[1], (byte) chars[0]);
- }
+ Assert.AreEqual (1, chars.Length, "#1");
+ Assert.AreEqual (testbytes [1], (byte) chars [0], "#2");
+ }
- // Test non-ASCII char in byte[]
+ [Test] // Test non-ASCII char in byte[]
public void TestGetChars3 ()
{
- Encoding ascii_encoding = Encoding.ASCII;
+ Encoding ascii_encoding = Encoding.ASCII;
testbytes[2] = 0x80;
char[] chars = ascii_encoding.GetChars(testbytes);
- AssertEquals ('T', chars[0]);
- AssertEquals ('e', chars[1]);
- AssertEquals ('?', chars[2]);
- AssertEquals ('t', chars[3]);
- }
+ Assert.AreEqual ('T', chars [0], "#1");
+ Assert.AreEqual ('e', chars [1], "#2");
+ Assert.AreEqual ('?', chars [2], "#3");
+ Assert.AreEqual ('t', chars [3], "#4");
+ }
- // Test GetChars(byte[], int, int, char[], int)
+ [Test] // Test GetChars(byte[], int, int, char[], int)
public void TestGetChars4 ()
{
- Encoding ascii_encoding = Encoding.ASCII;
+ Encoding ascii_encoding = Encoding.ASCII;
char[] chars = new char[1];
int cnt = ascii_encoding.GetChars(testbytes, 1, 1, chars, 0);
- AssertEquals (1, cnt);
- AssertEquals (testbytes[1], (byte) chars[0]);
- }
+ Assert.AreEqual (1, cnt, "#1");
+ Assert.AreEqual (testbytes [1], (byte) chars [0], "#2");
+ }
- // Test GetString(char[])
+ [Test] // Test GetString(char[])
public void TestGetString1 ()
{
- Encoding ascii_encoding = Encoding.ASCII;
+ Encoding ascii_encoding = Encoding.ASCII;
string str = ascii_encoding.GetString(testbytes);
- AssertEquals ("Test", str);
- }
+ Assert.AreEqual ("Test", str);
+ }
- // Test GetString(char[], int, int)
+ [Test] // Test GetString(char[], int, int)
public void TestGetString2 ()
{
- Encoding ascii_encoding = Encoding.ASCII;
+ Encoding ascii_encoding = Encoding.ASCII;
string str = ascii_encoding.GetString(testbytes, 1, 2);
- AssertEquals ("es", str);
- }
+ Assert.AreEqual ("es", str);
+ }
- // Test invalid byte handling
+ [Test] // Test invalid byte handling
public void TestGetString3 ()
{
Encoding encoding = Encoding.ASCII;
byte [] bytes = new byte [] {0x61, 0xE1, 0xE2};
string s = encoding.GetString (bytes, 0, 3);
#if NET_2_0
- AssertEquals ("a??", s);
+ Assert.AreEqual ("a??", s);
#else
- AssertEquals ("aab", s);
+ Assert.AreEqual ("aab", s);
#endif
}
- // Test Decoder
+ [Test] // Test Decoder
public void TestDecoder ()
{
- Encoding ascii_encoding = Encoding.ASCII;
+ Encoding ascii_encoding = Encoding.ASCII;
char[] chars = new char[1];
int cnt = ascii_encoding.GetDecoder().GetChars(testbytes, 1, 1, chars, 0);
- AssertEquals (1, cnt);
- AssertEquals (testbytes[1], (byte) chars[0]);
+ Assert.AreEqual (1, cnt, "#1");
+ Assert.AreEqual (testbytes [1], (byte) chars [0], "#2");
}
- // Test Decoder
+ [Test] // Test Decoder
public void TestEncoder ()
{
- Encoding ascii_encoding = Encoding.ASCII;
+ Encoding ascii_encoding = Encoding.ASCII;
byte[] bytes = new Byte[1];
int cnt = ascii_encoding.GetEncoder().GetBytes(testchars, 1, 1, bytes, 0, false);
- AssertEquals (1, cnt);
- AssertEquals (testchars[1], (char) bytes[0]);
+ Assert.AreEqual (1, cnt, "#1");
+ Assert.AreEqual (testchars [1], (char) bytes [0], "#2");
}
+ [Test]
public void TestZero ()
{
Encoding encoding = Encoding.ASCII;
- AssertEquals ("#01", encoding.GetString (new byte [0]), "");
- AssertEquals ("#02", encoding.GetString (new byte [0], 0, 0), "");
+ Assert.AreEqual (string.Empty, encoding.GetString (new byte [0]), "#1");
+ Assert.AreEqual (string.Empty, encoding.GetString (new byte [0], 0, 0), "#2");
}
#if NET_2_0
}
#endif
}
-
}
+2007-10-16 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * TestEncoding.cs: Also make class available on 1.0 profile.
+ * EncodingTest.cs: Added tests for Is* properties.
+ * UTF7EncodingTest.cs: Added tests for Is* properties.
+ * UnicodeEncodingTest.cs: Added tests for Is* properties. Fixed
+ line endings.
+ * UTF8EncodingTest.cs: Added tests for Is* properties. Spaces to
+ tabs. Numbered tests.
+ * ASCIIEncodingTest.cs: Added tests for Is* properties. No longer
+ derive from TestCase class. Spaces to tabs.
+ * UTF32EncodingTest.cs: Added tests for Is* properties. No longer
+ derive from deprecated Assertion class.
+
2007-07-06 Gert Driesen <drieseng@users.sourceforge.net>
* DecoderReplacementFallbackTest.cs: Fixed DontChangeReadOnlyCodePage-
[TestFixture]
public class EncodingTest
{
+ [Test]
+ [Category ("NotWorking")]
+ [ExpectedException (typeof (NotSupportedException))]
+ public void IsBrowserDisplay ()
+ {
+ MyEncoding enc = new MyEncoding ();
+ Assert.IsFalse (enc.IsBrowserDisplay);
+ }
+
+ [Test]
+ [Category ("NotWorking")]
+ [ExpectedException (typeof (NotSupportedException))]
+ public void IsBrowserSave ()
+ {
+ MyEncoding enc = new MyEncoding ();
+ Assert.IsFalse (enc.IsBrowserSave);
+ }
+
+ [Test]
+ [Category ("NotWorking")]
+ [ExpectedException (typeof (NotSupportedException))]
+ public void IsMailNewsDisplay ()
+ {
+ MyEncoding enc = new MyEncoding ();
+ Assert.IsFalse (enc.IsMailNewsDisplay);
+ }
+
+ [Test]
+ [Category ("NotWorking")]
+ [ExpectedException (typeof (NotSupportedException))]
+ public void IsMailNewsSave ()
+ {
+ MyEncoding enc = new MyEncoding ();
+ Assert.IsFalse (enc.IsMailNewsSave);
+ }
+
[Test]
public void GetEncoding_CodePage_Default ()
{
// Used for testing custom encoding.
//
-#if NET_2_0
-
using System;
using System.IO;
using System.Text;
+
using NUnit.Framework;
namespace MonoTests.System.Text
}
}
}
-
-#endif
-
-using NUnit.Framework;
+#if NET_2_0
using System;
using System.Text;
-#if NET_2_0
-
-namespace MonoTests.System.Text {
+using NUnit.Framework;
+namespace MonoTests.System.Text
+{
[TestFixture]
- public class UTF32EncodingTest : Assertion {
+ public class UTF32EncodingTest
+ {
+ [Test]
+ public void IsBrowserDisplay ()
+ {
+ UTF32Encoding le = new UTF32Encoding (false, true);
+ Assert.IsFalse (le.IsBrowserDisplay, "#1");
+
+ UTF32Encoding be = new UTF32Encoding (true, true);
+ Assert.IsFalse (be.IsBrowserDisplay, "#2");
+ }
+
+ [Test]
+ public void IsBrowserSave ()
+ {
+ UTF32Encoding le = new UTF32Encoding (false, true);
+ Assert.IsFalse (le.IsBrowserSave);
+
+ UTF32Encoding be = new UTF32Encoding (true, true);
+ Assert.IsFalse (be.IsBrowserSave, "#2");
+ }
+
+ [Test]
+ public void IsMailNewsDisplay ()
+ {
+ UTF32Encoding le = new UTF32Encoding (false, true);
+ Assert.IsFalse (le.IsMailNewsDisplay);
+
+ UTF32Encoding be = new UTF32Encoding (true, true);
+ Assert.IsFalse (be.IsMailNewsDisplay, "#2");
+ }
+
+ [Test]
+ public void IsMailNewsSave ()
+ {
+ UTF32Encoding le = new UTF32Encoding (false, true);
+ Assert.IsFalse (le.IsMailNewsSave);
+
+ UTF32Encoding be = new UTF32Encoding (true, true);
+ Assert.IsFalse (be.IsMailNewsSave, "#2");
+ }
[Test]
public void TestGetPreamble() {
byte[] lePreamble = new UTF32Encoding(false, true).GetPreamble();
- if (!AreEqual(lePreamble, new byte[]{ 0xff, 0xfe, 0, 0 })) {
- Fail ("Little-endian UTF32 preamble is incorrect");
- }
+ Assert.AreEqual (new byte [] { 0xff, 0xfe, 0, 0 }, lePreamble, "#1");
byte[] bePreamble = new UTF32Encoding(true, true).GetPreamble();
- if (!AreEqual(bePreamble, new byte[]{ 0, 0, 0xfe, 0xff })) {
- Fail ("Big-endian UTF32 preamble is incorrect");
- }
- }
-
- private bool AreEqual(byte[] a, byte[] b) {
- if (a.Length != b.Length)
- return false;
- for (int i = 0; i < a.Length; ++i) {
- if (a[i] != b[i])
- return false;
- }
- return true;
+ Assert.AreEqual (new byte [] { 0, 0, 0xfe, 0xff }, bePreamble, "#2");
}
}
}
-
#endif
-
[TestFixture]
public class UTF7EncodingTest : Assertion
{
+ [Test]
+ public void IsBrowserDisplay ()
+ {
+ UTF7Encoding utf7 = new UTF7Encoding ();
+ Assert (!utf7.IsBrowserDisplay);
+ }
+
+ [Test]
+ public void IsBrowserSave ()
+ {
+ UTF7Encoding utf7 = new UTF7Encoding ();
+ Assert (!utf7.IsBrowserSave);
+ }
+
+ [Test]
+ public void IsMailNewsDisplay ()
+ {
+ UTF7Encoding utf7 = new UTF7Encoding ();
+ Assert (utf7.IsMailNewsDisplay);
+ }
+
+ [Test]
+ public void IsMailNewsSave ()
+ {
+ UTF7Encoding utf7 = new UTF7Encoding ();
+ Assert (utf7.IsMailNewsSave);
+ }
+
[Test]
public void TestDirectlyEncoded1()
{
using AssertType = NUnit.Framework.Assert;
-namespace MonoTests.System.Text {
-
+namespace MonoTests.System.Text
+{
[TestFixture]
- public class UTF8EncodingTest : Assertion {
-
+ public class UTF8EncodingTest : Assertion
+ {
private UTF8Encoding utf8;
[SetUp]
utf8 = new UTF8Encoding (true, true);
}
- [Test]
- public void TestEncodingGetBytes1()
- {
- UTF8Encoding utf8Enc = new UTF8Encoding ();
- string UniCode = "\u0041\u2262\u0391\u002E";
-
- // "A<NOT IDENTICAL TO><ALPHA>." may be encoded as 41 E2 89 A2 CE 91 2E
- // see (RFC 2044)
- byte[] utf8Bytes = utf8Enc.GetBytes (UniCode);
-
- Assertion.AssertEquals ("UTF #1", 0x41, utf8Bytes [0]);
- Assertion.AssertEquals ("UTF #2", 0xE2, utf8Bytes [1]);
- Assertion.AssertEquals ("UTF #3", 0x89, utf8Bytes [2]);
- Assertion.AssertEquals ("UTF #4", 0xA2, utf8Bytes [3]);
- Assertion.AssertEquals ("UTF #5", 0xCE, utf8Bytes [4]);
- Assertion.AssertEquals ("UTF #6", 0x91, utf8Bytes [5]);
- Assertion.AssertEquals ("UTF #7", 0x2E, utf8Bytes [6]);
- }
-
- [Test]
- public void TestEncodingGetBytes2()
- {
- UTF8Encoding utf8Enc = new UTF8Encoding ();
- string UniCode = "\u0048\u0069\u0020\u004D\u006F\u006D\u0020\u263A\u0021";
-
- // "Hi Mom <WHITE SMILING FACE>!" may be encoded as 48 69 20 4D 6F 6D 20 E2 98 BA 21
- // see (RFC 2044)
- byte[] utf8Bytes = new byte [11];
-
- int ByteCnt = utf8Enc.GetBytes (UniCode.ToCharArray(), 0, UniCode.Length, utf8Bytes, 0);
-
- Assertion.AssertEquals ("UTF #1", 11, ByteCnt);
- Assertion.AssertEquals ("UTF #2", 0x48, utf8Bytes [0]);
- Assertion.AssertEquals ("UTF #3", 0x69, utf8Bytes [1]);
- Assertion.AssertEquals ("UTF #4", 0x20, utf8Bytes [2]);
- Assertion.AssertEquals ("UTF #5", 0x4D, utf8Bytes [3]);
- Assertion.AssertEquals ("UTF #6", 0x6F, utf8Bytes [4]);
- Assertion.AssertEquals ("UTF #7", 0x6D, utf8Bytes [5]);
- Assertion.AssertEquals ("UTF #8", 0x20, utf8Bytes [6]);
- Assertion.AssertEquals ("UTF #9", 0xE2, utf8Bytes [7]);
- Assertion.AssertEquals ("UTF #10", 0x98, utf8Bytes [8]);
- Assertion.AssertEquals ("UTF #11", 0xBA, utf8Bytes [9]);
- Assertion.AssertEquals ("UTF #12", 0x21, utf8Bytes [10]);
- }
-
- [Test]
- public void TestDecodingGetChars1()
- {
- UTF8Encoding utf8Enc = new UTF8Encoding ();
- // 41 E2 89 A2 CE 91 2E may be decoded as "A<NOT IDENTICAL TO><ALPHA>."
- // see (RFC 2044)
- byte[] utf8Bytes = new byte [] {0x41, 0xE2, 0x89, 0xA2, 0xCE, 0x91, 0x2E};
- char[] UniCodeChars = utf8Enc.GetChars(utf8Bytes);
-
- Assertion.AssertEquals ("UTF #1", 0x0041, UniCodeChars [0]);
- Assertion.AssertEquals ("UTF #2", 0x2262, UniCodeChars [1]);
- Assertion.AssertEquals ("UTF #3", 0x0391, UniCodeChars [2]);
- Assertion.AssertEquals ("UTF #4", 0x002E, UniCodeChars [3]);
- }
-
- [Test]
+ [Test]
+ public void IsBrowserDisplay ()
+ {
+ Assert (utf8.IsBrowserDisplay);
+ }
+
+ [Test]
+ public void IsBrowserSave ()
+ {
+ Assert (utf8.IsBrowserSave);
+ }
+
+ [Test]
+ public void IsMailNewsDisplay ()
+ {
+ Assert (utf8.IsMailNewsDisplay);
+ }
+
+ [Test]
+ public void IsMailNewsSave ()
+ {
+ Assert (utf8.IsMailNewsSave);
+ }
+
+ [Test]
+ public void TestEncodingGetBytes1()
+ {
+ UTF8Encoding utf8Enc = new UTF8Encoding ();
+ string UniCode = "\u0041\u2262\u0391\u002E";
+
+ // "A<NOT IDENTICAL TO><ALPHA>." may be encoded as 41 E2 89 A2 CE 91 2E
+ // see (RFC 2044)
+ byte[] utf8Bytes = utf8Enc.GetBytes (UniCode);
+
+ Assertion.AssertEquals ("UTF #1", 0x41, utf8Bytes [0]);
+ Assertion.AssertEquals ("UTF #2", 0xE2, utf8Bytes [1]);
+ Assertion.AssertEquals ("UTF #3", 0x89, utf8Bytes [2]);
+ Assertion.AssertEquals ("UTF #4", 0xA2, utf8Bytes [3]);
+ Assertion.AssertEquals ("UTF #5", 0xCE, utf8Bytes [4]);
+ Assertion.AssertEquals ("UTF #6", 0x91, utf8Bytes [5]);
+ Assertion.AssertEquals ("UTF #7", 0x2E, utf8Bytes [6]);
+ }
+
+ [Test]
+ public void TestEncodingGetBytes2()
+ {
+ UTF8Encoding utf8Enc = new UTF8Encoding ();
+ string UniCode = "\u0048\u0069\u0020\u004D\u006F\u006D\u0020\u263A\u0021";
+
+ // "Hi Mom <WHITE SMILING FACE>!" may be encoded as 48 69 20 4D 6F 6D 20 E2 98 BA 21
+ // see (RFC 2044)
+ byte[] utf8Bytes = new byte [11];
+
+ int ByteCnt = utf8Enc.GetBytes (UniCode.ToCharArray(), 0, UniCode.Length, utf8Bytes, 0);
+ Assertion.AssertEquals ("UTF #1", 11, ByteCnt);
+ Assertion.AssertEquals ("UTF #2", 0x48, utf8Bytes [0]);
+ Assertion.AssertEquals ("UTF #3", 0x69, utf8Bytes [1]);
+ Assertion.AssertEquals ("UTF #4", 0x20, utf8Bytes [2]);
+ Assertion.AssertEquals ("UTF #5", 0x4D, utf8Bytes [3]);
+ Assertion.AssertEquals ("UTF #6", 0x6F, utf8Bytes [4]);
+ Assertion.AssertEquals ("UTF #7", 0x6D, utf8Bytes [5]);
+ Assertion.AssertEquals ("UTF #8", 0x20, utf8Bytes [6]);
+ Assertion.AssertEquals ("UTF #9", 0xE2, utf8Bytes [7]);
+ Assertion.AssertEquals ("UTF #10", 0x98, utf8Bytes [8]);
+ Assertion.AssertEquals ("UTF #11", 0xBA, utf8Bytes [9]);
+ Assertion.AssertEquals ("UTF #12", 0x21, utf8Bytes [10]);
+ }
+
+ [Test]
+ public void TestDecodingGetChars1()
+ {
+ UTF8Encoding utf8Enc = new UTF8Encoding ();
+ // 41 E2 89 A2 CE 91 2E may be decoded as "A<NOT IDENTICAL TO><ALPHA>."
+ // see (RFC 2044)
+ byte[] utf8Bytes = new byte [] {0x41, 0xE2, 0x89, 0xA2, 0xCE, 0x91, 0x2E};
+ char[] UniCodeChars = utf8Enc.GetChars(utf8Bytes);
+
+ Assertion.AssertEquals ("UTF #1", 0x0041, UniCodeChars [0]);
+ Assertion.AssertEquals ("UTF #2", 0x2262, UniCodeChars [1]);
+ Assertion.AssertEquals ("UTF #3", 0x0391, UniCodeChars [2]);
+ Assertion.AssertEquals ("UTF #4", 0x002E, UniCodeChars [3]);
+ }
+
+ [Test]
#if NET_2_0
- [Category ("NotWorking")]
+ [Category ("NotWorking")]
#endif
- public void TestMaxCharCount()
- {
- UTF8Encoding UTF8enc = new UTF8Encoding ();
+ public void TestMaxCharCount()
+ {
+ UTF8Encoding UTF8enc = new UTF8Encoding ();
#if NET_2_0
- // hmm, where is this extra 1 coming from?
- Assertion.AssertEquals ("UTF #1", 51, UTF8enc.GetMaxCharCount(50));
+ // hmm, where is this extra 1 coming from?
+ Assertion.AssertEquals ("UTF #1", 51, UTF8enc.GetMaxCharCount(50));
#else
- Assertion.AssertEquals ("UTF #1", 50, UTF8enc.GetMaxCharCount(50));
+ Assertion.AssertEquals ("UTF #1", 50, UTF8enc.GetMaxCharCount(50));
#endif
- }
-
- [Test]
+ }
+
+ [Test]
#if NET_2_0
- [Category ("NotWorking")]
+ [Category ("NotWorking")]
#endif
- public void TestMaxByteCount()
- {
- UTF8Encoding UTF8enc = new UTF8Encoding ();
+ public void TestMaxByteCount()
+ {
+ UTF8Encoding UTF8enc = new UTF8Encoding ();
#if NET_2_0
- // maybe under .NET 2.0 insufficient surrogate pair is just not handled, and 3 is Preamble size.
- Assertion.AssertEquals ("UTF #1", 153, UTF8enc.GetMaxByteCount(50));
+ // maybe under .NET 2.0 insufficient surrogate pair is
+ // just not handled, and 3 is Preamble size.
+ Assertion.AssertEquals ("UTF #1", 153, UTF8enc.GetMaxByteCount(50));
#else
- Assertion.AssertEquals ("UTF #1", 200, UTF8enc.GetMaxByteCount(50));
+ Assertion.AssertEquals ("UTF #1", 200, UTF8enc.GetMaxByteCount(50));
#endif
- }
+ }
// regression for bug #59648
[Test]
byte[] data = new byte [] { 0xC0, 0xAF };
string s = u.GetString (data);
- AssertEquals (0, s.Length);
+ AssertEquals ("#A1", 0, s.Length);
data = new byte [] { 0x30, 0x31, 0xC0, 0xAF, 0x30, 0x32 };
s = u.GetString (data);
- AssertEquals (4, s.Length);
- AssertEquals (0x30, (int) s [0]);
- AssertEquals (0x31, (int) s [1]);
- AssertEquals (0x30, (int) s [2]);
- AssertEquals (0x32, (int) s [3]);
+ AssertEquals ("#B1", 4, s.Length);
+ AssertEquals ("#B2", 0x30, (int) s [0]);
+ AssertEquals ("#B3", 0x31, (int) s [1]);
+ AssertEquals ("#B4", 0x30, (int) s [2]);
+ AssertEquals ("#B5", 0x32, (int) s [3]);
}
// UTF8 decoding tests from http://www.cl.cam.ac.uk/~mgk25/
}
[Test]
-// MS Fx 1.1 accept this
+ // MS Fx 1.1 accept this
// [ExpectedException (typeof (DecoderException))]
public void T3_Malformed_3_LastContinuationMissing_337 ()
{
-//\r
-// UnicodeEncodingTest.cs - NUnit Test Cases for System.Text.UnicodeEncoding\r
-//\r
-// Author:\r
-// Patrick Kalkman kalkman@cistron.nl\r
-//\r
-// (C) 2003 Patrick Kalkman\r
-// \r
-using NUnit.Framework;\r
-using System;\r
-using System.Text;\r
-\r
-namespace MonoTests.System.Text\r
-{\r
- [TestFixture]\r
- public class UnicodeEncodingTest \r
- {\r
- [Test]\r
- public void TestEncodingGetBytes1()\r
- {\r
- //pi and sigma in unicode\r
- string Unicode = "\u03a0\u03a3";\r
- byte[] UniBytes;\r
- UnicodeEncoding UnicodeEnc = new UnicodeEncoding (); //little-endian\r
- UniBytes = UnicodeEnc.GetBytes (Unicode);\r
- \r
- Assertion.AssertEquals ("Uni #1", 0xA0, UniBytes [0]);\r
- Assertion.AssertEquals ("Uni #2", 0x03, UniBytes [1]);\r
- Assertion.AssertEquals ("Uni #3", 0xA3, UniBytes [2]);\r
- Assertion.AssertEquals ("Uni #4", 0x03, UniBytes [3]);\r
- }\r
- \r
- [Test]\r
- public void TestEncodingGetBytes2()\r
- {\r
- //pi and sigma in unicode\r
- string Unicode = "\u03a0\u03a3";\r
- byte[] UniBytes;\r
- UnicodeEncoding UnicodeEnc = new UnicodeEncoding (true, true); //big-endian\r
- UniBytes = UnicodeEnc.GetBytes (Unicode);\r
- \r
- Assertion.AssertEquals ("Uni #1", 0x03, UniBytes [0]);\r
- Assertion.AssertEquals ("Uni #2", 0xA0, UniBytes [1]);\r
- Assertion.AssertEquals ("Uni #3", 0x03, UniBytes [2]);\r
- Assertion.AssertEquals ("Uni #4", 0xA3, UniBytes [3]);\r
- }\r
-\r
- [Test]\r
- public void TestEncodingGetBytes3()\r
- {\r
- //pi and sigma in unicode\r
- string Unicode = "\u03a0\u03a3";\r
- byte[] UniBytes = new byte [4];\r
- UnicodeEncoding UnicodeEnc = new UnicodeEncoding (); //little-endian \r
- int Cnt = UnicodeEnc.GetBytes (Unicode.ToCharArray(), 0, Unicode.Length, UniBytes, 0);\r
- \r
- Assertion.AssertEquals ("Uni #1", 4, Cnt);\r
- Assertion.AssertEquals ("Uni #2", 0xA0, UniBytes [0]);\r
- Assertion.AssertEquals ("Uni #3", 0x03, UniBytes [1]);\r
- Assertion.AssertEquals ("Uni #4", 0xA3, UniBytes [2]);\r
- Assertion.AssertEquals ("Uni #5", 0x03, UniBytes [3]);\r
- }\r
- \r
- [Test]\r
- public void TestEncodingDecodingGetBytes1()\r
- {\r
- //pi and sigma in unicode\r
- string Unicode = "\u03a0\u03a3";\r
- UnicodeEncoding UnicodeEnc = new UnicodeEncoding (); //little-endian \r
- //Encode the unicode string.\r
- byte[] UniBytes = UnicodeEnc.GetBytes (Unicode);\r
- //Decode the bytes to a unicode char array.\r
- char[] UniChars = UnicodeEnc.GetChars (UniBytes);\r
- string Result = new string(UniChars);\r
- \r
- Assertion.AssertEquals ("Uni #1", Unicode, Result);\r
- }\r
-\r
- [Test]\r
- public void TestEncodingDecodingGetBytes2()\r
- {\r
- //pi and sigma in unicode\r
- string Unicode = "\u03a0\u03a3";\r
- UnicodeEncoding UnicodeEnc = new UnicodeEncoding (true, true); //big-endian \r
- //Encode the unicode string.\r
- byte[] UniBytes = UnicodeEnc.GetBytes (Unicode);\r
- //Decode the bytes to a unicode char array.\r
- char[] UniChars = UnicodeEnc.GetChars (UniBytes);\r
- string Result = new string(UniChars);\r
- \r
- Assertion.AssertEquals ("Uni #1", Unicode, Result);\r
- }\r
-\r
- [Test]\r
- public void TestEncodingGetCharCount ()\r
- {\r
- byte[] b = new byte[] {255, 254, 115, 0, 104, 0, 105, 0};\r
- UnicodeEncoding encoding = new UnicodeEncoding ();\r
-\r
- Assertion.AssertEquals ("GetCharCount #1", 3,\r
- encoding.GetCharCount (b, 2, b.Length - 2));\r
- }\r
-\r
- \r
- \r
- [Test]\r
- public void TestPreamble1()\r
- {\r
- //litle-endian with byte order mark.\r
- UnicodeEncoding UnicodeEnc = new UnicodeEncoding (false, true); \r
- byte[] PreAmble = UnicodeEnc.GetPreamble();\r
-\r
- Assertion.AssertEquals ("Uni #1", 0xFF, PreAmble [0]);\r
- Assertion.AssertEquals ("Uni #2", 0xFE, PreAmble [1]);\r
- }\r
-\r
- [Test]\r
- public void TestPreamble2()\r
- {\r
- //big-endian with byte order mark.\r
- UnicodeEncoding UnicodeEnc = new UnicodeEncoding (true, true); \r
- byte[] PreAmble = UnicodeEnc.GetPreamble();\r
-\r
- Assertion.AssertEquals ("Uni #1", 0xFE, PreAmble [0]);\r
- Assertion.AssertEquals ("Uni #2", 0xFF, PreAmble [1]);\r
- }\r
-\r
- [Test]\r
- public void TestPreamble3()\r
- {\r
- //little-endian without byte order mark.\r
- UnicodeEncoding UnicodeEnc = new UnicodeEncoding (false, false); \r
- byte[] PreAmble = UnicodeEnc.GetPreamble();\r
-\r
- Assertion.AssertEquals ("Uni #1", 0, PreAmble.Length);\r
- }\r
- \r
- [Test]\r
-#if NET_2_0\r
- [Category ("NotWorking")]\r
-#endif\r
- public void TestMaxCharCount()\r
- {\r
- UnicodeEncoding UnicodeEnc = new UnicodeEncoding ();\r
-#if NET_2_0\r
- // where is this extra 1 coming from?\r
- Assertion.AssertEquals ("UTF #1", 25, UnicodeEnc.GetMaxCharCount(51));\r
-#else\r
- Assertion.AssertEquals ("UTF #1", 25, UnicodeEnc.GetMaxCharCount(50));\r
-#endif\r
- }\r
- \r
- [Test]\r
-#if NET_2_0\r
- [Category ("NotWorking")]\r
-#endif\r
- public void TestMaxByteCount()\r
- {\r
- UnicodeEncoding UnicodeEnc = new UnicodeEncoding ();\r
-#if NET_2_0\r
- // is this extra 2 BOM?\r
- Assertion.AssertEquals ("UTF #1", 102, UnicodeEnc.GetMaxByteCount(50));\r
-#else\r
- Assertion.AssertEquals ("UTF #1", 100, UnicodeEnc.GetMaxByteCount(50));\r
-#endif\r
- }\r
-\r
- [Test]\r
- public void ZeroLengthArrays ()\r
- {\r
- UnicodeEncoding encoding = new UnicodeEncoding ();\r
- encoding.GetCharCount (new byte [0]);\r
- encoding.GetChars (new byte [0]);\r
- encoding.GetCharCount (new byte [0], 0, 0);\r
- encoding.GetChars (new byte [0], 0, 0);\r
- encoding.GetChars (new byte [0], 0, 0, new char [0], 0);\r
- encoding.GetByteCount (new char [0]);\r
- encoding.GetBytes (new char [0]);\r
- encoding.GetByteCount (new char [0], 0, 0);\r
- encoding.GetBytes (new char [0], 0, 0);\r
- encoding.GetBytes (new char [0], 0, 0, new byte [0], 0);\r
- encoding.GetByteCount ("");\r
- encoding.GetBytes ("");\r
- }\r
-\r
- [Test]\r
- public void ByteOrderMark ()\r
- {\r
- string littleEndianString = "\ufeff\u0042\u004f\u004d";\r
- string bigEndianString = "\ufffe\u4200\u4f00\u4d00";\r
- byte [] littleEndianBytes = new byte [] {0xff, 0xfe, 0x42, 0x00, 0x4f, 0x00, 0x4d, 0x00};\r
- byte [] bigEndianBytes = new byte [] {0xfe, 0xff, 0x00, 0x42, 0x00, 0x4f, 0x00, 0x4d};\r
- UnicodeEncoding encoding;\r
- \r
- encoding = new UnicodeEncoding (false, true);\r
- Assertion.AssertEquals ("BOM #1", encoding.GetBytes (littleEndianString), littleEndianBytes);\r
- Assertion.AssertEquals ("BOM #2", encoding.GetBytes (bigEndianString), bigEndianBytes);\r
- Assertion.AssertEquals ("BOM #3", encoding.GetString (littleEndianBytes), littleEndianString);\r
- Assertion.AssertEquals ("BOM #4", encoding.GetString (bigEndianBytes), bigEndianString);\r
-\r
- encoding = new UnicodeEncoding (true, true);\r
- Assertion.AssertEquals ("BOM #5", encoding.GetBytes (littleEndianString), bigEndianBytes);\r
- Assertion.AssertEquals ("BOM #6", encoding.GetBytes (bigEndianString), littleEndianBytes);\r
- Assertion.AssertEquals ("BOM #7", encoding.GetString (littleEndianBytes), bigEndianString);\r
- Assertion.AssertEquals ("BOM #8", encoding.GetString (bigEndianBytes), littleEndianString);\r
- }\r
- }\r
-}\r
+//
+// UnicodeEncodingTest.cs - NUnit Test Cases for System.Text.UnicodeEncoding
+//
+// Author:
+// Patrick Kalkman kalkman@cistron.nl
+//
+// (C) 2003 Patrick Kalkman
+//
+using NUnit.Framework;
+using System;
+using System.Text;
+
+namespace MonoTests.System.Text
+{
+ [TestFixture]
+ public class UnicodeEncodingTest
+ {
+ [Test]
+ public void IsBrowserDisplay ()
+ {
+ UnicodeEncoding enc = new UnicodeEncoding ();
+ Assert.IsFalse (enc.IsBrowserDisplay);
+ }
+
+ [Test]
+ public void IsBrowserSave ()
+ {
+ UnicodeEncoding enc = new UnicodeEncoding ();
+ Assert.IsTrue (enc.IsBrowserSave);
+ }
+
+ [Test]
+ public void IsMailNewsDisplay ()
+ {
+ UnicodeEncoding enc = new UnicodeEncoding ();
+ Assert.IsFalse (enc.IsMailNewsDisplay);
+ }
+
+ [Test]
+ public void IsMailNewsSave ()
+ {
+ UnicodeEncoding enc = new UnicodeEncoding ();
+ Assert.IsFalse (enc.IsMailNewsSave);
+ }
+
+ [Test]
+ public void TestEncodingGetBytes1()
+ {
+ //pi and sigma in unicode
+ string Unicode = "\u03a0\u03a3";
+ byte[] UniBytes;
+ UnicodeEncoding UnicodeEnc = new UnicodeEncoding (); //little-endian
+ UniBytes = UnicodeEnc.GetBytes (Unicode);
+
+ Assertion.AssertEquals ("Uni #1", 0xA0, UniBytes [0]);
+ Assertion.AssertEquals ("Uni #2", 0x03, UniBytes [1]);
+ Assertion.AssertEquals ("Uni #3", 0xA3, UniBytes [2]);
+ Assertion.AssertEquals ("Uni #4", 0x03, UniBytes [3]);
+ }
+
+ [Test]
+ public void TestEncodingGetBytes2()
+ {
+ //pi and sigma in unicode
+ string Unicode = "\u03a0\u03a3";
+ byte[] UniBytes;
+ UnicodeEncoding UnicodeEnc = new UnicodeEncoding (true, true); //big-endian
+ UniBytes = UnicodeEnc.GetBytes (Unicode);
+
+ Assertion.AssertEquals ("Uni #1", 0x03, UniBytes [0]);
+ Assertion.AssertEquals ("Uni #2", 0xA0, UniBytes [1]);
+ Assertion.AssertEquals ("Uni #3", 0x03, UniBytes [2]);
+ Assertion.AssertEquals ("Uni #4", 0xA3, UniBytes [3]);
+ }
+
+ [Test]
+ public void TestEncodingGetBytes3()
+ {
+ //pi and sigma in unicode
+ string Unicode = "\u03a0\u03a3";
+ byte[] UniBytes = new byte [4];
+ UnicodeEncoding UnicodeEnc = new UnicodeEncoding (); //little-endian
+ int Cnt = UnicodeEnc.GetBytes (Unicode.ToCharArray(), 0, Unicode.Length, UniBytes, 0);
+
+ Assertion.AssertEquals ("Uni #1", 4, Cnt);
+ Assertion.AssertEquals ("Uni #2", 0xA0, UniBytes [0]);
+ Assertion.AssertEquals ("Uni #3", 0x03, UniBytes [1]);
+ Assertion.AssertEquals ("Uni #4", 0xA3, UniBytes [2]);
+ Assertion.AssertEquals ("Uni #5", 0x03, UniBytes [3]);
+ }
+
+ [Test]
+ public void TestEncodingDecodingGetBytes1()
+ {
+ //pi and sigma in unicode
+ string Unicode = "\u03a0\u03a3";
+ UnicodeEncoding UnicodeEnc = new UnicodeEncoding (); //little-endian
+ //Encode the unicode string.
+ byte[] UniBytes = UnicodeEnc.GetBytes (Unicode);
+ //Decode the bytes to a unicode char array.
+ char[] UniChars = UnicodeEnc.GetChars (UniBytes);
+ string Result = new string(UniChars);
+
+ Assertion.AssertEquals ("Uni #1", Unicode, Result);
+ }
+
+ [Test]
+ public void TestEncodingDecodingGetBytes2()
+ {
+ //pi and sigma in unicode
+ string Unicode = "\u03a0\u03a3";
+ UnicodeEncoding UnicodeEnc = new UnicodeEncoding (true, true); //big-endian
+ //Encode the unicode string.
+ byte[] UniBytes = UnicodeEnc.GetBytes (Unicode);
+ //Decode the bytes to a unicode char array.
+ char[] UniChars = UnicodeEnc.GetChars (UniBytes);
+ string Result = new string(UniChars);
+
+ Assertion.AssertEquals ("Uni #1", Unicode, Result);
+ }
+
+ [Test]
+ public void TestEncodingGetCharCount ()
+ {
+ byte[] b = new byte[] {255, 254, 115, 0, 104, 0, 105, 0};
+ UnicodeEncoding encoding = new UnicodeEncoding ();
+
+ Assertion.AssertEquals ("GetCharCount #1", 3,
+ encoding.GetCharCount (b, 2, b.Length - 2));
+ }
+
+
+
+ [Test]
+ public void TestPreamble1()
+ {
+ //litle-endian with byte order mark.
+ UnicodeEncoding UnicodeEnc = new UnicodeEncoding (false, true);
+ byte[] PreAmble = UnicodeEnc.GetPreamble();
+
+ Assertion.AssertEquals ("Uni #1", 0xFF, PreAmble [0]);
+ Assertion.AssertEquals ("Uni #2", 0xFE, PreAmble [1]);
+ }
+
+ [Test]
+ public void TestPreamble2()
+ {
+ //big-endian with byte order mark.
+ UnicodeEncoding UnicodeEnc = new UnicodeEncoding (true, true);
+ byte[] PreAmble = UnicodeEnc.GetPreamble();
+
+ Assertion.AssertEquals ("Uni #1", 0xFE, PreAmble [0]);
+ Assertion.AssertEquals ("Uni #2", 0xFF, PreAmble [1]);
+ }
+
+ [Test]
+ public void TestPreamble3()
+ {
+ //little-endian without byte order mark.
+ UnicodeEncoding UnicodeEnc = new UnicodeEncoding (false, false);
+ byte[] PreAmble = UnicodeEnc.GetPreamble();
+
+ Assertion.AssertEquals ("Uni #1", 0, PreAmble.Length);
+ }
+
+ [Test]
+#if NET_2_0
+ [Category ("NotWorking")]
+#endif
+ public void TestMaxCharCount()
+ {
+ UnicodeEncoding UnicodeEnc = new UnicodeEncoding ();
+#if NET_2_0
+ // where is this extra 1 coming from?
+ Assertion.AssertEquals ("UTF #1", 25, UnicodeEnc.GetMaxCharCount(51));
+#else
+ Assertion.AssertEquals ("UTF #1", 25, UnicodeEnc.GetMaxCharCount(50));
+#endif
+ }
+
+ [Test]
+#if NET_2_0
+ [Category ("NotWorking")]
+#endif
+ public void TestMaxByteCount()
+ {
+ UnicodeEncoding UnicodeEnc = new UnicodeEncoding ();
+#if NET_2_0
+ // is this extra 2 BOM?
+ Assertion.AssertEquals ("UTF #1", 102, UnicodeEnc.GetMaxByteCount(50));
+#else
+ Assertion.AssertEquals ("UTF #1", 100, UnicodeEnc.GetMaxByteCount(50));
+#endif
+ }
+
+ [Test]
+ public void ZeroLengthArrays ()
+ {
+ UnicodeEncoding encoding = new UnicodeEncoding ();
+ encoding.GetCharCount (new byte [0]);
+ encoding.GetChars (new byte [0]);
+ encoding.GetCharCount (new byte [0], 0, 0);
+ encoding.GetChars (new byte [0], 0, 0);
+ encoding.GetChars (new byte [0], 0, 0, new char [0], 0);
+ encoding.GetByteCount (new char [0]);
+ encoding.GetBytes (new char [0]);
+ encoding.GetByteCount (new char [0], 0, 0);
+ encoding.GetBytes (new char [0], 0, 0);
+ encoding.GetBytes (new char [0], 0, 0, new byte [0], 0);
+ encoding.GetByteCount ("");
+ encoding.GetBytes ("");
+ }
+
+ [Test]
+ public void ByteOrderMark ()
+ {
+ string littleEndianString = "\ufeff\u0042\u004f\u004d";
+ string bigEndianString = "\ufffe\u4200\u4f00\u4d00";
+ byte [] littleEndianBytes = new byte [] {0xff, 0xfe, 0x42, 0x00, 0x4f, 0x00, 0x4d, 0x00};
+ byte [] bigEndianBytes = new byte [] {0xfe, 0xff, 0x00, 0x42, 0x00, 0x4f, 0x00, 0x4d};
+ UnicodeEncoding encoding;
+
+ encoding = new UnicodeEncoding (false, true);
+ Assertion.AssertEquals ("BOM #1", encoding.GetBytes (littleEndianString), littleEndianBytes);
+ Assertion.AssertEquals ("BOM #2", encoding.GetBytes (bigEndianString), bigEndianBytes);
+ Assertion.AssertEquals ("BOM #3", encoding.GetString (littleEndianBytes), littleEndianString);
+ Assertion.AssertEquals ("BOM #4", encoding.GetString (bigEndianBytes), bigEndianString);
+
+ encoding = new UnicodeEncoding (true, true);
+ Assertion.AssertEquals ("BOM #5", encoding.GetBytes (littleEndianString), bigEndianBytes);
+ Assertion.AssertEquals ("BOM #6", encoding.GetBytes (bigEndianString), littleEndianBytes);
+ Assertion.AssertEquals ("BOM #7", encoding.GetString (littleEndianBytes), bigEndianString);
+ Assertion.AssertEquals ("BOM #8", encoding.GetString (bigEndianBytes), littleEndianString);
+ }
+ }
+}
+2007-10-21 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * ThreadTest.cs: On 2.0 profile, enable > 0 tests for GetHashCode.
+ Added test that asserts if the hashcode of two threads is distinct.
+
+2007-10-20 Raja R Harinath <harinath@gmail.com>
+
+ * TimerTest.cs (TestHeavyCreationLoad): Don't shadow a variable name.
+
+2007-10-19 Dick Porter <dick@ximian.com>
+
+ * ThreadTest.cs: Re-enable ManagedThreadId test too
+
+2007-10-19 Dick Porter <dick@ximian.com>
+
+ * ThreadTest.cs: Re-enable GetHashCodeTest
+
2007-10-05 Dick Porter <dick@ximian.com>
* ThreadTest.cs: Disable GetHashCodeTest while I figure out why
}
[Test] // bug #325566
- [Category ("NotWorking")] // Until I figure out why GetHashCode
- // can sometimes return 0
public void GetHashCodeTest ()
{
C1Test test1 = new C1Test ();
Thread tA = new Thread (new ThreadStart (test1.TestMethod));
int hA1 = tA.GetHashCode ();
+#if NET_2_0
Assert.IsTrue (hA1 > 0, "#A1");
+#endif
tA.Start ();
int hA2 = tA.GetHashCode ();
Assert.AreEqual (hA1, hA2, "#A2");
test1 = new C1Test ();
Thread tB = new Thread (new ThreadStart (test1.TestMethod));
int hB1 = tB.GetHashCode ();
+#if NET_2_0
Assert.IsTrue (hB1 > 0, "#B1");
+#endif
tB.Start ();
int hB2 = tB.GetHashCode ();
Assert.AreEqual (hB1, hB2, "#B2");
#if NET_2_0
Assert.AreEqual (hB1, tB.ManagedThreadId, "#B4");
#endif
+ Assert.IsFalse (hA2 == hB2, "#B5");
}
#if NET_2_0
[Test] // bug #82700
- [Category ("NotWorking")]
public void ManagedThreadId ()
{
C1Test test1 = new C1Test ();
//
// Author:
// Zoltan Varga (vargaz@freemail.hu)
+// Rafael Ferreira (raf@ophion.org)
//
// (C) 2004 Novell, Inc (http://www.novell.com)
//
using NUnit.Framework;
using System;
using System.Threading;
+using System.Collections;
namespace MonoTests.System.Threading {
- [TestFixture]
//
// This whole test seems to fail randomly. Either
// - It is relying on a race it might not win (that the timer code runs)
// Am going with door #1, but it would be nice to investigate this.
// -- Ben
//
- public class TimerTest : Assertion {
+ [TestFixture]
+ public class TimerTest {
+ // this bucket is used to avoid non-theadlocal issues
+ class Bucket {
+ public int count;
+ }
+ [SetUp]
+ public void setup() {
+ //creating a timer that will never run just to make sure the
+ // scheduler is warm for the unit tests
+ // this makes fair for the "DueTime" test since it
+ // doesn't have to wait for the scheduler thread to be
+ // created.
+ new Timer(null,null,Timeout.Infinite,0);
+ }
+
[Test]
- [Category ("NotWorking")]
public void TestDueTime ()
{
- counter = 0;
- Timer t = new Timer (new TimerCallback (Callback), null, 200, Timeout.Infinite);
+ Bucket bucket = new Bucket();
+ Timer t = new Timer (new TimerCallback (Callback), bucket, 200, Timeout.Infinite);
Thread.Sleep (50);
- AssertEquals ("t0", 0, counter);
+ Assert.AreEqual (0, bucket.count);
Thread.Sleep (200);
- AssertEquals ("t1", 1, counter);
+ Assert.AreEqual (1, bucket.count);
Thread.Sleep (500);
- AssertEquals ("t2", 1, counter);
-
+ Assert.AreEqual (1, bucket.count);
t.Change (10, 10);
- Thread.Sleep (500);
- Assert ("t3", counter > 20);
+ Thread.Sleep (1000);
+ Assert.IsTrue(bucket.count > 20);
t.Dispose ();
}
[Test]
- [Category ("NotWorking")]
public void TestChange ()
{
- counter = 0;
- Timer t = new Timer (new TimerCallback (Callback), null, 1, 1);
+ Bucket bucket = new Bucket();
+ Timer t = new Timer (new TimerCallback (Callback), bucket, 1, 1);
Thread.Sleep (500);
- int c = counter;
- Assert ("t1", c > 20);
+ int c = bucket.count;
+ Assert.IsTrue(c > 20);
t.Change (100, 100);
Thread.Sleep (500);
- Assert ("t2", counter <= c + 6);
+ Assert.IsTrue(bucket.count <= c + 6);
t.Dispose ();
}
[Test]
- [Category ("NotWorking")]
public void TestZeroDueTime () {
- counter = 0;
+ Bucket bucket = new Bucket();
- Timer t = new Timer (new TimerCallback (Callback), null, 0, Timeout.Infinite);
+ Timer t = new Timer (new TimerCallback (Callback), bucket, 0, Timeout.Infinite);
Thread.Sleep (100);
- AssertEquals (1, counter);
+ Assert.AreEqual (1, bucket.count);
t.Change (0, Timeout.Infinite);
Thread.Sleep (100);
- AssertEquals (2, counter);
+ Assert.AreEqual (2, bucket.count);
t.Dispose ();
}
-
[Test]
- [Category ("NotWorking")]
public void TestDispose ()
- {
- counter = 0;
- Timer t = new Timer (new TimerCallback (CallbackTestDispose), null, 10, 10);
+ {
+ Bucket bucket = new Bucket();
+ Timer t = new Timer (new TimerCallback (Callback), bucket, 10, 10);
Thread.Sleep (200);
t.Dispose ();
Thread.Sleep (20);
- int c = counter;
- Assert (counter > 5);
+ int c = bucket.count;
+ Assert.IsTrue(bucket.count > 5);
Thread.Sleep (200);
- AssertEquals (c, counter);
+ Assert.AreEqual (c, bucket.count);
}
[Test] // bug #78208
public void TestDispose2 ()
{
- Timer t = new Timer (new TimerCallback (CallbackTestDispose), null, 10, 10);
+ Timer t = new Timer (new TimerCallback (Callback), null, 10, 10);
t.Dispose ();
t.Dispose ();
}
[Test]
- [Category ("NotWorking")]
- public void TestDisposeOnCallback () {
- counter = 0;
- t1 = new Timer (new TimerCallback (CallbackTestDisposeOnCallback), null, 0, 10);
- Thread.Sleep (200);
- AssertNull (t1);
+ public void TestHeavyCreationLoad() {
+ Bucket b = new Bucket();
+ for (int i = 0; i < 500; ++i)
+ new Timer(new TimerCallback(Callback),b,10,Timeout.Infinite);
+ // 1000 * 10 msec = 10,000 msec or 10 sec - if everything goes well
+ // we add some slack to cope with timing issues caused by system load etc.
+ for (int i = 0; i < 20; ++i) {
+ if (b.count == 500)
+ break;
+ Thread.Sleep(1000);
+ }
+ Assert.AreEqual(500,b.count);
- counter = 2;
- t1 = new Timer (new TimerCallback (CallbackTestDisposeOnCallback), null, 50, 0);
- Thread.Sleep (200);
- AssertNull (t1);
}
-
- private void CallbackTestDisposeOnCallback (object foo)
- {
- if (++counter == 3) {
- t1.Dispose ();
- t1 = null;
+ [Test]
+ public void TestQuickDisposeDeadlockBug() {
+ int i = 0;
+ Bucket b = new Bucket();
+ ArrayList timers = new ArrayList();
+ while (i < 500) {
+ Timer t = new Timer(new TimerCallback(Callback),b,10,Timeout.Infinite);
+ timers.Add(t);
+ i++;
+ t.Dispose();
}
+ Thread.Sleep(11*500);
+ }
+ [Test]
+ public void TestInt32MaxDelay() {
+ Bucket b = new Bucket();
+ new Timer(new TimerCallback(Callback),b,Int32.MaxValue,Timeout.Infinite);
+ Thread.Sleep(50);
+ Assert.AreEqual(0,b.count);
+
+ }
+ [Test]
+ public void TestInt32MaxPeriod() {
+ Bucket b = new Bucket();
+ new Timer(new TimerCallback(Callback),b,0,Int32.MaxValue);
+ Thread.Sleep(50);
+ Assert.AreEqual(1,b.count);
+
+ }
+ [Test]
+ public void TestNegativeDelay() {
+ Bucket b = new Bucket();
+ try {
+ new Timer(new TimerCallback(Callback),b,-10,Timeout.Infinite);
+ } catch (ArgumentOutOfRangeException) {
+ return;
+ }
+ Assert.Fail();
+
+ }
+ [Test]
+ public void TestNegativePeriod() {
+ Bucket b = new Bucket();
+ try {
+ new Timer(new TimerCallback(Callback),b,0,-10);
+ } catch (ArgumentOutOfRangeException) {
+ return;
+ }
+ Assert.Fail();
}
- private void CallbackTestDispose (object foo)
- {
- counter++;
+ [Test]
+ public void TestDelayZeroPeriodZero() {
+ Bucket b = new Bucket();
+ Timer t = new Timer(new TimerCallback(Callback),b,0,0);
+ /* we need to guess how many times the callback is invoked
+ * repeatedly in any given amount of time: this depends on cpu
+ * speed, schedule decisions, system load etc. so the numbers
+ * are quite relaxed and we assume success if it executed
+ * 50 times in less than 100 ms.
+ */
+ Thread.Sleep(100);
+ //stop the timer
+ t.Change (int.MaxValue, Timeout.Infinite);
+ Assert.IsTrue(b.count > 50);
+
}
+ [Category("NotWorking")]
+ public void TestDisposeOnCallback () {
+
+ Timer t1 = null;
+ t1 = new Timer (new TimerCallback (CallbackTestDisposeOnCallback), t1, 0, 10);
+ Thread.Sleep (200);
+ Assert.IsNull(t1);
+
+ }
+ private void CallbackTestDisposeOnCallback (object foo)
+ {
+ ((Timer)foo).Dispose();
+ }
+
private void Callback (object foo)
{
- counter++;
+ Bucket b = foo as Bucket;
+ b.count++;
}
-
- Timer t1;
- int counter;
}
}
+2007-10-15 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * EnvironmentTest.cs: Added test for bug #333740. Made names of some
+ existing tests more clear. Code formatting.
+
+2007-10-15 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * DateTimeTest.cs: Added test for bug #322510.
+
+2007-10-13 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * DelegateTest.cs: Enabled test for bug #333647.
+
+2007-10-13 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * DelegateTest.cs: Added test for bug #333647. Added trivial tests
+ that verify null argument checks in CreateDelegate.
+
2007-10-05 Alp Toker <alp@atoker.com>
* TypeTest.cs: Re-enable the regression test for #315863.
Assert.AreEqual (21, dt.Day, "#3");
}
+ [Test] // bug #322510
+ public void Parse_HourDesignator ()
+ {
+ DateTime dt;
+ DateTime now = DateTime.Now;
+
+ dt = DateTime.Parse ("12:00:00 AM", new CultureInfo ("en-US"));
+ Assert.AreEqual (now.Year, dt.Year, "#A1");
+ Assert.AreEqual (now.Month, dt.Month, "#A2");
+ Assert.AreEqual (now.Day, dt.Day, "#A3");
+ Assert.AreEqual (0, dt.Hour, "#A4");
+ Assert.AreEqual (0, dt.Minute, "#A5");
+ Assert.AreEqual (0, dt.Second, "#A6");
+ Assert.AreEqual (0, dt.Millisecond, "#A7");
+
+ dt = DateTime.Parse ("12:00:00 PM", new CultureInfo ("en-US"));
+ Assert.AreEqual (now.Year, dt.Year, "#B1");
+ Assert.AreEqual (now.Month, dt.Month, "#B2");
+ Assert.AreEqual (now.Day, dt.Day, "#B3");
+ Assert.AreEqual (12, dt.Hour, "#B4");
+ Assert.AreEqual (0, dt.Minute, "#B5");
+ Assert.AreEqual (0, dt.Second, "#B6");
+ Assert.AreEqual (0, dt.Millisecond, "#B7");
+ }
+
[Test]
// FIXME: This test doesn't work on cultures like es-DO which have patterns
// for both dd/MM/yyyy & MM/dd/yyyy
// (C) Ximian, Inc. http://www.ximian.com
//
-using NUnit.Framework;
using System;
using System.Reflection;
+using NUnit.Framework;
+
namespace MonoTests.System
{
+ [TestFixture]
+ public class DelegateTest
+ {
+ [Test] // CreateDelegate (Type, MethodInfo)
+ public void CreateDelegate1_Method_Static ()
+ {
+ C c = new C ();
+ MethodInfo mi = typeof (C).GetMethod ("S");
+ Delegate dg = Delegate.CreateDelegate (typeof (D), mi);
+ Assert.AreSame (mi, dg.Method, "#1");
+ Assert.IsNull (dg.Target, "#2");
+ D d = (D) dg;
+ d (c);
+ }
-[TestFixture]
-public class DelegateTest : Assertion
-{
+ [Test] // CreateDelegate (Type, MethodInfo)
+ public void CreateDelegate1_Method_Instance ()
+ {
+ C c = new C ();
+ MethodInfo mi = typeof (C).GetMethod ("M");
#if NET_2_0
- class ParentClass {
- }
+ Delegate dg = Delegate.CreateDelegate (typeof (D), mi);
+ Assert.AreSame (mi, dg.Method, "#1");
+ Assert.IsNull (dg.Target, "#2");
+ D d = (D) dg;
+ d (c);
+#else
+ try {
+ Delegate.CreateDelegate (typeof (D), mi);
+ Assert.Fail ("#1");
+ } catch (ArgumentException ex) {
+ // Method must be a static method
+ Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("method", ex.ParamName, "#6");
+ }
+#endif
+ }
- class Subclass : ParentClass {
- }
+ [Test] // CreateDelegate (Type, MethodInfo)
+ public void CreateDelegate1_Method_Null ()
+ {
+ try {
+ Delegate.CreateDelegate (typeof (D), (MethodInfo) null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("method", ex.ParamName, "#6");
+ }
+ }
- delegate ParentClass CoContraVariantDelegate (Subclass s);
+ [Test] // CreateDelegate (Type, MethodInfo)
+ public void CreateDelegate1_Type_Null ()
+ {
+ MethodInfo mi = typeof (C).GetMethod ("S");
+ try {
+ Delegate.CreateDelegate ((Type) null, mi);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("type", ex.ParamName, "#6");
+ }
+ }
- static Subclass CoContraVariantMethod (ParentClass s) {
- return null;
- }
+ [Test] // CreateDelegate (Type, Object, String)
+ public void CreateDelegate2_Method_Null ()
+ {
+ C c = new C ();
+ try {
+ Delegate.CreateDelegate (typeof (D), c, (string) null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("method", ex.ParamName, "#6");
+ }
+ }
- [Test]
- [Category ("TargetJvmNotWorking")]
- public void CoContraVariance () {
- CoContraVariantDelegate d = (CoContraVariantDelegate)Delegate.CreateDelegate (typeof (CoContraVariantDelegate), typeof (DelegateTest).GetMethod ("CoContraVariantMethod", BindingFlags.NonPublic|BindingFlags.Static));
+ [Test] // CreateDelegate (Type, Object, String)
+ public void CreateDelegate2_Target_Null ()
+ {
+ try {
+ Delegate.CreateDelegate (typeof (D),null, "N");
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("target", ex.ParamName, "#6");
+ }
+ }
- d (null);
- }
+ [Test] // CreateDelegate (Type, Object, String)
+ public void CreateDelegate2_Type_Null ()
+ {
+ C c = new C ();
+ try {
+ Delegate.CreateDelegate ((Type) null, c, "N");
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("type", ex.ParamName, "#6");
+ }
+ }
+
+ [Test] // CreateDelegate (Type, Type, String)
+ public void CreateDelegate3_Method_Null ()
+ {
+ try {
+ Delegate.CreateDelegate (typeof (D), typeof (C), (string) null);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("method", ex.ParamName, "#6");
+ }
+ }
+
+ [Test] // CreateDelegate (Type, Type, String)
+ public void CreateDelegate3_Target_Null ()
+ {
+ try {
+ Delegate.CreateDelegate (typeof (D), (Type) null, "S");
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("target", ex.ParamName, "#6");
+ }
+ }
+
+ [Test] // CreateDelegate (Type, Type, String)
+ public void CreateDelegate3_Type_Null ()
+ {
+ try {
+ Delegate.CreateDelegate ((Type) null, typeof (C), "S");
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("type", ex.ParamName, "#6");
+ }
+ }
+
+ [Test] // CreateDelegate (Type, Object, String, Boolean)
+ public void CreateDelegate4_Method_Null ()
+ {
+ C c = new C ();
+ try {
+ Delegate.CreateDelegate (typeof (D), c, (string) null, true);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("method", ex.ParamName, "#6");
+ }
+ }
+
+ [Test] // CreateDelegate (Type, Object, String, Boolean)
+ public void CreateDelegate4_Target_Null ()
+ {
+ try {
+ Delegate.CreateDelegate (typeof (D), null, "N", true);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("target", ex.ParamName, "#6");
+ }
+ }
+
+ [Test] // CreateDelegate (Type, Object, String, Boolean)
+ public void CreateDelegate4_Type_Null ()
+ {
+ C c = new C ();
+ try {
+ Delegate.CreateDelegate ((Type) null, c, "N", true);
+ Assert.Fail ("#1");
+ } catch (ArgumentNullException ex) {
+ Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
+ Assert.IsNull (ex.InnerException, "#3");
+ Assert.IsNotNull (ex.Message, "#4");
+ Assert.IsNotNull (ex.ParamName, "#5");
+ Assert.AreEqual ("type", ex.ParamName, "#6");
+ }
+ }
+
+#if NET_2_0
+ class ParentClass
+ {
+ }
+
+ class Subclass : ParentClass
+ {
+ }
+
+ delegate ParentClass CoContraVariantDelegate (Subclass s);
+
+ static Subclass CoContraVariantMethod (ParentClass s)
+ {
+ return null;
+ }
+
+ [Test]
+ [Category ("TargetJvmNotWorking")]
+ public void CoContraVariance ()
+ {
+ CoContraVariantDelegate d = (CoContraVariantDelegate)
+ Delegate.CreateDelegate (typeof (CoContraVariantDelegate),
+ typeof (DelegateTest).GetMethod ("CoContraVariantMethod",
+ BindingFlags.NonPublic|BindingFlags.Static));
+ d (null);
+ }
#endif
-}
+ public class C
+ {
+ public void M ()
+ {
+ }
+
+ public void N (C c)
+ {
+ }
+
+ public static void S (C c)
+ {
+ }
+ }
+
+ public delegate void D (C c);
+ }
}
// (C) 2004-2005 Novell (http://www.novell.com)
//
-using NUnit.Framework;
-using System;\r
+using System;
using System.Collections;
-namespace MonoTests.System {
+using NUnit.Framework;
+namespace MonoTests.System
+{
[TestFixture]
- public class EnvironmentTest {
-
+ public class EnvironmentTest
+ {
private void ExpandEquals (string toExpand, string toMatch)
{
string expanded = Environment.ExpandEnvironmentVariables (toExpand);
private void ExpandStartsEnds (string toExpand, string start, string end)
{
string expanded = Environment.ExpandEnvironmentVariables (toExpand);
- Assert.IsTrue (expanded.StartsWith (start), "ExpandEnvironmentVariables(" + toExpand + ").Start");\r
+ Assert.IsTrue (expanded.StartsWith (start), "ExpandEnvironmentVariables(" + toExpand + ").Start");
Assert.IsTrue (expanded.EndsWith (end), "ExpandEnvironmentVariables(" + toExpand + ").End");
}
ExpandDifferent ("%PATH%%PATH%");
string path = Environment.GetEnvironmentVariable ("PATH");
if (path != null) {
- string expanded = Environment.ExpandEnvironmentVariables ("%PATH%%PATH%");\r
+ string expanded = Environment.ExpandEnvironmentVariables ("%PATH%%PATH%");
Assert.AreEqual (path + path, expanded, "#01");
}
}
public void ExpandEnvironmentVariables_ExpandableAndNonExpandable ()
{
string path = Environment.GetEnvironmentVariable ("PATH");
- string expanded=Environment.ExpandEnvironmentVariables("%PATH% PATH%");\r
+ string expanded=Environment.ExpandEnvironmentVariables("%PATH% PATH%");
Assert.AreEqual (path + " PATH%", expanded);
}
public void ExpandEnvironmentVariables_ComplexExpandable2 ()
{
ExpandStartsEnds ("Hello %%PATH%%%", "Hello %", "%%");
- }\r
-\r
- [Test]\r
- public void GetEnvironmentVariables ()\r
- {\r
- IDictionary d = Environment.GetEnvironmentVariables ();\r
- Assert.IsTrue ((d is Hashtable), "Hashtable");\r
- Assert.IsFalse (d.IsFixedSize, "IsFixedSize");\r
- Assert.IsFalse (d.IsReadOnly, "IsReadOnly");\r
- Assert.IsFalse (d.IsSynchronized, "IsSynchronized");\r
}
+ [Test]
+ public void GetEnvironmentVariables ()
+ {
+ IDictionary d = Environment.GetEnvironmentVariables ();
+ Assert.IsTrue ((d is Hashtable), "Hashtable");
+ Assert.IsFalse (d.IsFixedSize, "IsFixedSize");
+ Assert.IsFalse (d.IsReadOnly, "IsReadOnly");
+ Assert.IsFalse (d.IsSynchronized, "IsSynchronized");
+ }
+
+#if NET_2_0 && !TARGET_JVM
+ [Test] // bug #333740
+ [Category ("NotWorking")]
+ public void GetEnvironmentVariables_NewlySet ()
+ {
+ Environment.SetEnvironmentVariable ("MonoTestVariable", "TestValue");
+ IDictionary d = Environment.GetEnvironmentVariables ();
+ Assert.AreEqual ("TestValue", d ["MonoTestVariable"], "#1");
+ Environment.SetEnvironmentVariable ("MonoTestVariable", string.Empty);
+ Assert.AreEqual ("TestValue", d ["MonoTestVariable"], "#2");
+ d = Environment.GetEnvironmentVariables ();
+ Assert.IsNull (d ["MonoTestVariable"], "#3");
+ }
+#endif
+
[Test]
public void GetCommandLineArgs ()
{
#if NET_2_0
[Test]
[ExpectedException (typeof (ArgumentException))]
- public void GetEnvironmentVariable_Target ()
+ public void GetEnvironmentVariable_Target_Invalid ()
{
Environment.GetEnvironmentVariable ("MONO", (EnvironmentVariableTarget)Int32.MinValue);
}
- [Test]\r
- [ExpectedException (typeof (ArgumentException))]\r
- public void GetEnvironmentVariables_Target ()
+ [Test]
+ [ExpectedException (typeof (ArgumentException))]
+ public void GetEnvironmentVariables_Target_Invalid ()
{
Environment.GetEnvironmentVariables ((EnvironmentVariableTarget)Int32.MinValue);
}
#if !TARGET_JVM // Environment.SetEnvironmentVariable not supported under TARGET_JVM
- [Test]\r
- [ExpectedException (typeof (ArgumentException))]\r
- public void SetEnvironmentVariable_Target ()
+ [Test]
+ [ExpectedException (typeof (ArgumentException))]
+ public void SetEnvironmentVariable_Target_Invalid ()
{
Environment.SetEnvironmentVariable ("MONO", "GO", (EnvironmentVariableTarget)Int32.MinValue);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
- public void SetEnvironmentVariable_NameNull ()
+ public void SetEnvironmentVariable_Name_Null ()
{
Environment.SetEnvironmentVariable (null, "A");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
- public void SetEnvironmentVariable_NameEmpty ()
+ public void SetEnvironmentVariable_Name_Empty ()
{
Environment.SetEnvironmentVariable ("", "A");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
- public void SetEnvironmentVariable_NameZeroChar ()
+ public void SetEnvironmentVariable_Name_ZeroChar ()
{
Environment.SetEnvironmentVariable ("\0", "A");
}
// Test delete
Environment.SetEnvironmentVariable ("A1", null);
- Assert.AreEqual (Environment.GetEnvironmentVariables ()["A1"], null);
+ Assert.IsNull (Environment.GetEnvironmentVariables ()["A1"]);
Environment.SetEnvironmentVariable ("A2", "");
- Assert.AreEqual (Environment.GetEnvironmentVariables ()["A2"], null);
+ Assert.IsNull (Environment.GetEnvironmentVariables ()["A2"]);
Environment.SetEnvironmentVariable ("A3", "\0");
- Assert.AreEqual (Environment.GetEnvironmentVariables ()["A3"], null);
+ Assert.IsNull (Environment.GetEnvironmentVariables ()["A3"]);
}
#endif // TARGET_JVM
#endif
+2007-10-17 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * cs0177-8.cs: New test based on #325478.
+
2007-10-09 Jb Evain <jbevain@novell.com>
* known-issues-mcs: test asserting that assembly
--- /dev/null
+// CS0082: A member `ISample.set_Item(int, int)' is already reserved
+// Line: 6
+
+public interface ISample {
+ int this[int i] { set; }
+ void set_Item (int a, int b);
+}
--- /dev/null
+// CS0082: A member `Test.get_Value()' is already reserved
+// Line: 6
+
+public class Test
+{
+ public string Value {
+ set { }
+ }
+ public string get_Value () { return null; }
+}
--- /dev/null
+// CS0082: A member `Test.set_Item(int, string)' is already reserved
+// Line : 6
+
+public class Test
+{
+ public string this [int i] {
+ get { return ""; }
+ }
+ public void set_Item (int i, string s) { }
+}
--- /dev/null
+// CS0082: A member `I.set_Item(int[], params int[])' is already reserved
+// Line : 7
+
+interface I
+{
+ void set_Item (int[] a, params int[] b);
+ int[] this [params int[] ii] { get; }
+}
--- /dev/null
+// CS0082: A member `Test.get_Value()' is already reserved\r
+// Line: 7\r
+\r
+public partial class Test\r
+{\r
+ public string get_Value () { return null; }\r
+}\r
+\r
+public partial class Test\r
+{\r
+ public string Value {\r
+ get { }\r
+ }\r
+}\r
--- /dev/null
+// CS0082: A member `ISample.set_Item(int, int)' is already reserved
+// Line: 6
+
+public interface ISample {
+ void set_Item (int a, int b);
+ int this[int i] { set; }
+}
--- /dev/null
+// CS0082: A member `ErrorClass.get_Blah(int)' is already reserved
+// Line: 8
+
+using System.Runtime.CompilerServices;
+class ErrorClass {
+ [IndexerName ("Blah")]
+ public int this [int a] {
+ get { return 1; }
+ }
+
+ public void get_Blah (int b) {}
+
+ public static void Main ()
+ {
+ }
+}
--- /dev/null
+// CS0082: A member `Test.add_XX(Test.MyEvent)' is already reserved
+// Line: 12
+
+public class Test
+{
+ public delegate void MyEvent ();
+ public event MyEvent XX {
+ add { }
+ remove { }
+ }
+
+ public void add_XX (MyEvent e) { return; }
+}
+
--- /dev/null
+// CS0082: A member `Class.op_Implicit(byte)' is already reserved
+// Line: 9
+
+public class Class {
+ static public implicit operator Class(byte value) {
+ return new Class();
+ }
+
+ public static void op_Implicit (byte value) {}
+}
--- /dev/null
+// CS0082: A member `Test.get_Value()' is already reserved
+// Line: 7
+
+public class Test
+{
+ public string get_Value () { return null; }
+ public string Value {
+ get { }
+ }
+}
-// cs0102.cs: The type `Test' already contains a definition for `add_XX'
-// Line: 12
+// CS0102: The type `C' already contains a definition for `Item'
+// Line: 7
-public class Test
+class C
{
- public delegate void MyEvent ();
- public event MyEvent XX {
- add { }
- remove { }
- }
-
- public void add_XX (MyEvent e) { return; }
+ bool this [int i] { get { return false; } }
+ bool Item (int i) { return false; }
}
-
+++ /dev/null
-// cs0111-10.cs: `Test.get_Value()' is already defined. Rename this member or use different parameter types
-// Line: 7
-
-public class Test
-{
- public string get_Value () { return null; }
- public string Value {
- get { }
- }
-}
-// cs0111-11.cs: `Blah.I.M()' is already defined. Rename this member or use different parameter types
+// CS0111: A member `Blah.I.M()' is already defined. Rename this member or use different parameter types
// Line : 12
public interface I
+++ /dev/null
-// cs0111-12.cs: `Test.get_Value()' is already defined. Rename this member or use different parameter types
-// Line : 6
-
-public class Test
-{
- public string Value {
- set { }
- }
- public string get_Value () { return null; }
-}
+++ /dev/null
-// cs0111-14.cs: `Test.set_Item(int, string)' is already defined. Rename this member or use different parameter types
-// Line : 6
-
-public class Test
-{
- public string this [int i] {
- get { return ""; }
- }
- public void set_Item (int i, string s) { }
-}
+++ /dev/null
-// cs0111-15.cs: `I.set_Item(int[], params int[])' is already defined. Rename this member or use different parameter types
-// Line : 7
-
-interface I
-{
- void set_Item (int[] a, params int[] b);
- int[] this [params int[] ii] { get; }
-}
-// cs0111-16.cs: `T.T()' is already defined. Rename this member or use different parameter types\r
-// Line : 9\r
+// CS0111: A member `T.T()' is already defined. Rename this member or use different parameter types\r
+// Line: 9\r
\r
partial class T {\r
T () {}\r
+++ /dev/null
-// cs0111-17.cs: `Test.get_Value()' is already defined. Rename this member or use different parameter types\r
-// Line: 7\r
-\r
-public partial class Test\r
-{\r
- public string get_Value () { return null; }\r
-}\r
-\r
-public partial class Test\r
-{\r
- public string Value {\r
- get { }\r
- }\r
-}\r
-// CS0111: `C.this[int[]]' is already defined. Rename this member or use different parameter types
+// CS0111: A member `C.this[params int[]]' is already defined. Rename this member or use different parameter types
// Line: 6
class C
+++ /dev/null
-// cs0111-2.cs: `ISample.set_Item(int, int)' is already defined. Rename this member or use different parameter types
-// Line: 6
-
-public interface ISample {
- void set_Item (int a, int b);
- int this[int i] { set; }
-}
+++ /dev/null
-// cs0111-3.cs: `Class.implicit operator Class(byte)' is already defined. Rename this member or use different parameter types
-// Line: 9
-
-public class Class {
- static public implicit operator Class(byte value) {
- return new Class();
- }
-
- public static void op_Implicit (byte value) {}
-}
\ No newline at end of file
+++ /dev/null
-// cs0111-4.cs: `ErrorClass.get_Blah(int)' is already defined. Rename this member or use different parameter types
-// Line: 8
-
-using System.Runtime.CompilerServices;
-class ErrorClass {
- [IndexerName ("Blah")]
- public int this [int a] {
- get { return 1; }
- }
-
- public void get_Blah (int b) {}
-
- public static void Main ()
- {
- }
-}
-// cs0111-5.cs: `ISample.Blah()' is already defined. Rename this member or use different parameter types
+// CS0111: A member `ISample.Blah()' is already defined. Rename this member or use different parameter types
// Line: 6
public interface ISample {
int Blah ();
int Blah ();
-}
\ No newline at end of file
+}
-// cs0111-6.cs: `T.T()' is already defined. Rename this member or use different parameter types
+// CS0111: A member `T.T()' is already defined. Rename this member or use different parameter types
// Line : 6
class T {
-// cs0111-7.cs: `T.T()' is already defined. Rename this member or use different parameter types
+// CS0111: A member `T.T()' is already defined. Rename this member or use different parameter types
// Line : 6
class T {
-// cs0111-9.cs: `C.this[int]' is already defined. Rename this member or use different parameter types
+// CS0111: A member `C.this[int]' is already defined. Rename this member or use different parameter types
// Line: 6
class C
-// cs0111.cs: `Blah.Foo(int, int)' is already defined. Rename this member or use different parameter types
+// CS0111: A member `Blah.Foo(int, int)' is already defined. Rename this member or use different parameter types
// Line : 10
public class Blah {
--- /dev/null
+// cs0177-8.cs: The out parameter `parameterModifiers' must be assigned to before control leaves the current method
+// Line: 17
+
+using System;
+using System.Reflection;
+
+/// <summary>
+/// MS does not report CS0177 for structs:
+/// https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304489
+/// </summary>
+class Program
+{
+ bool GetArgsForCall (object [] originalArgs, out ParameterModifier parameterModifiers)
+ {
+ int countOfArgs = originalArgs.Length;
+ if (countOfArgs == 0)
+ return false;
+
+ parameterModifiers = new ParameterModifier (countOfArgs);
+ return true;
+ }
+}
--- /dev/null
+// CS0663: An overloaded method `Test.Test(out int)' cannot differ on use of parameter modifiers only
+// Line: 10
+
+public class Test
+{
+ public Test (ref int i)
+ {
+ }
+
+ public Test (out int i)
+ {
+ }
+}
-// cs0663.cs: `WrongInterface.Test(ref int)': Methods cannot differ only on their use of ref and out on a parameters
+// CS0663: An overloaded method `WrongInterface.Test(ref int)' cannot differ on use of parameter modifiers only
// Line: 6
public interface WrongInterface {
-// gcs0111-2.cs: `Blah.I.M<U>(int)' is already defined. Rename this member or use different parameter types\r
+// CS0111: A member `Blah.I.M<U>(int)' is already defined. Rename this member or use different parameter types\r
// Line : 12\r
\r
public interface I\r
--- /dev/null
+// CS0111: A member `C.Foo<U>(U)' is already defined. Rename this member or use different parameter types
+// Line : 12
+
+public class C
+{
+ void Foo<T> (T i)
+ {
+ }
+
+ void Foo<U> (U i)
+ {
+ }
+}
--- /dev/null
+// CS0111: A member `C.Foo<U>(U)' is already defined. Rename this member or use different parameter types
+// Line : 12
+
+public class C
+{
+ void Foo (int i)
+ {
+ }
+
+ void Foo<T> (T i)
+ {
+ }
+
+ void Foo<U> (U i)
+ {
+ }
+}
-// CS0111: `Dictionary<K,V>.Add(V)' is already defined. Rename this member or use different parameter types
+// CS0111: A member `Dictionary<K,V>.Add(V)' is already defined. Rename this member or use different parameter types
// Line: 14
+
using System;
using System.Collections.Generic;
+2007-10-23 Marek Safar <marek.safar@gmail.com>
+
+ * class.cs, decl.cs: Rewrote member overloads check to cope with
+ generics and to use member cache for member checking. It also improves
+ performance and fixes remaining overloads issues.
+
+2007-10-20 Marek Safar <marek.safar@gmail.com>
+
+ * class.cs, const.cs, decl.cs, delegate.cs, enum.cs, generic.cs,
+ roottypes.cs, typemanager.cs:
+
+ A member cache creation logic changed to add members immediately and
+ not rely on fallback. The member cache is now only prefered way
+ how to access and find type declaration members. It saves 5 MB of memory
+ during MWF compilation and makes code ready for more optimizations and
+ clean-ups, it's also a pre-requirement for partial methods.
+
+2007-10-18 Raja R Harinath <harinath@gmail.com>
+
+ * ecore.cs (Expression.Error_ValueCannotBeConverted): Add special
+ handling for generic parameters.
+
+2007-10-15 Marek Safar <marek.safar@gmail.com>
+
+ * class.cs (FixedField): Removed redundant volatile check.
+
+2007-10-15 Marek Safar <marek.safar@gmail.com>
+
+ * class.cs, decl.cs: Fixed overload members verification to do only one
+ check per possible collision.
+
2007-10-13 Marek Safar <marek.safar@gmail.com>
A fix for bug #325478
// basenames in the defined_names array.
//
//
-#define CACHE
using System;
using System.Collections;
using System.Collections.Specialized;
protected ArrayList initialized_static_fields;
// Holds the list of constants
- MemberCoreArrayList constants;
+ protected MemberCoreArrayList constants;
// Holds the methods.
MemberCoreArrayList methods;
// The base member cache and our member cache
MemberCache base_cache;
- MemberCache member_cache;
+ protected MemberCache member_cache;
public const string DefaultIndexerName = "Item";
public void AddMethod (Method method)
{
- if (!AddMember (method))
+ MemberName mn = method.MemberName;
+ if (!AddToContainer (method, mn.IsGeneric ? mn.Basename : mn.MethodName))
return;
-
+
if (methods == null)
methods = new MemberCoreArrayList ();
}
bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
+ if (!AddToContainer (c, is_static ?
+ ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
+ return;
if (is_static){
if (default_static_constructor != null) {
- Report.SymbolRelatedToPreviousError (default_static_constructor);
- Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
- return;
+ Report.SymbolRelatedToPreviousError (default_static_constructor);
+ Report.Error (111, c.Location,
+ "A member `{0}' is already defined. Rename this member or use different parameter types",
+ c.GetSignatureForError ());
+ return;
}
default_static_constructor = c;
} else {
- if (c.Parameters.Empty){
- if (default_constructor != null) {
- Report.SymbolRelatedToPreviousError (default_constructor);
- Report.Error (111, c.Location, Error111, c.GetSignatureForError ());
- return;
- }
+ if (c.Parameters.Empty)
default_constructor = c;
- }
if (instance_constructors == null)
instance_constructors = new MemberCoreArrayList ();
}
}
- internal static string Error111 {
- get {
- return "`{0}' is already defined. Rename this member or use different parameter types";
- }
- }
-
public bool AddField (FieldBase field)
{
if (!AddMember (field))
ConstructedType ct = base_type as ConstructedType;
if ((ct != null) && !ct.CheckConstraints (this))
return false;
+
+ member_cache = new MemberCache (base_type.Type, this);
+ } else if (Kind == Kind.Interface) {
+ member_cache = new MemberCache (null, this);
+ Type [] ifaces = TypeManager.GetInterfaces (TypeBuilder);
+ for (int i = 0; i < ifaces.Length; ++i)
+ member_cache.AddInterface (TypeManager.LookupMemberCache (ifaces [i]));
+ } else {
+ member_cache = new MemberCache (null, this);
+ }
+
+ if (types != null)
+ foreach (TypeContainer tc in types)
+ member_cache.AddNestedType (tc);
+
+ if (delegates != null)
+ foreach (Delegate d in delegates)
+ member_cache.AddNestedType (d);
+
+ if (partial_parts != null) {
+ foreach (TypeContainer part in partial_parts)
+ part.member_cache = member_cache;
}
if (!IsTopLevel) {
GenericType = CurrentType;
}
-#if CACHE
- member_cache = new MemberCache (this);
- if (partial_parts != null) {
- foreach (TypeContainer part in partial_parts)
- part.member_cache = member_cache;
- }
-#endif
+#if GMCS_SOURCE
+ //
+ // FIXME: This hack is needed because member cache does not work
+ // with generic types, we rely on runtime to inflate dynamic types.
+ // TODO: This hack requires member cache refactoring to be removed
+ //
+ if (TypeBuilder.IsGenericType)
+ member_cache = new MemberCache (this);
+#endif
return true;
}
//
// Since the whole process is a no-op, it is fine to check for null here.
//
+ // TODO: This approach will be one day completely removed, it's already
+ // used at few places only
+ //
+ //
public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
MemberFilter filter, object criteria)
{
}
}
- MemberCache IMemberContainer.MemberCache {
- get {
- return member_cache;
- }
- }
-
bool IMemberContainer.IsInterface {
get {
return Kind == Kind.Interface;
get { return "T:"; }
}
- public virtual MemberCache BaseCache {
+ public MemberCache BaseCache {
get {
if (base_cache != null)
return base_cache;
{
}
- protected override bool CheckForDuplications ()
- {
- throw new NotSupportedException ();
- }
-
protected override bool VerifyClsCompliance ()
{
if (!base.VerifyClsCompliance ())
if (!DefineParameters (Parameters))
return false;
- if (!base.CheckBase ())
- return false;
-
- return true;
- }
-
- // TODO: create a special method for operators only to make code better
- protected bool IsDuplicateImplementation (MethodCore method)
- {
- if (method == this)
- return false;
-
- Operator op2 = null;
- Operator op1 = null;
-
- if (!(method.MemberName.Equals (MemberName)))
- {
- op1 = this as Operator;
- if (op1 == null || !(op1.OperatorType == Operator.OpType.Explicit || op1.OperatorType == Operator.OpType.Implicit))
+ if ((caching_flags & Flags.MethodOverloadsExist) != 0) {
+ if (!Parent.MemberCache.CheckExistingMembersOverloads (this, Name, Parameters))
return false;
- op2 = method as Operator;
- if (op2 == null || !(op2.OperatorType == Operator.OpType.Explicit || op2.OperatorType == Operator.OpType.Implicit))
- return false;
- } else {
- op1 = this as Operator;
- op2 = method as Operator;
- }
-
- Type[] param_types = method.ParameterTypes;
- // This never happen. Rewrite this as Equal
- if (param_types == null && ParameterTypes == null)
- return true;
- if (param_types == null || ParameterTypes == null)
- return false;
-
- if (param_types.Length != ParameterTypes.Length)
- return false;
-
- if (method.Parameters.HasArglist != Parameters.HasArglist)
- return false;
-
- bool equal = true;
-
- for (int i = 0; i < param_types.Length; i++) {
- if (param_types [i] != ParameterTypes [i])
- equal = false;
- }
-
- if (IsExplicitImpl && (method.InterfaceType != InterfaceType))
- equal = false;
-
- // TODO: make operator compatible with MethodCore to avoid this
- if (op1 != null && op2 != null) {
- if (MemberType != method.MemberType)
- equal = false;
- }
-
- if (equal) {
- //
- // Try to report 663: method only differs on out/ref
- //
- Parameters info = ParameterInfo;
- Parameters other_info = method.ParameterInfo;
- for (int i = 0; i < info.Count; i++){
- if (info.ParameterModifier (i) != other_info.ParameterModifier (i)){
- Report.SymbolRelatedToPreviousError (method);
- Report.Error (663, Location, "`{0}': Methods cannot differ only on their use of ref and out on a parameters",
- GetSignatureForError ());
+ // TODO: Find a better way how to check reserved accessors collision
+ Method m = this as Method;
+ if (m != null) {
+ if (!m.CheckForDuplications ())
return false;
- }
}
-
- Report.SymbolRelatedToPreviousError (method);
- if (this is Operator && method is Operator)
- Report.Error (557, Location, "Duplicate user-defined conversion in type `{0}'", Parent.Name);
- else
- Report.Error (111, Location, TypeContainer.Error111, GetSignatureForError ());
-
- return true;
}
- return false;
+ if (!base.CheckBase ())
+ return false;
+
+ return true;
}
//
get { return "M:"; }
}
+ public override bool EnableOverloadChecks (MemberCore overload)
+ {
+ if (overload is MethodCore || overload is AbstractPropertyEventMethod) {
+ caching_flags |= Flags.MethodOverloadsExist;
+ return true;
+ }
+
+ return false;
+ }
+
public virtual void SetYields ()
{
ModFlags |= Modifiers.METHOD_YIELDS;
if (!base.CheckBase ())
return false;
- if ((caching_flags & Flags.TestMethodDuplication) != 0 && !CheckForDuplications ())
- return false;
-
if (IsExplicitImpl)
return true;
}
}
- /// <summary>
- /// For custom member duplication search in a container
- /// </summary>
- protected abstract bool CheckForDuplications ();
-
/// <summary>
/// Gets base method and its return type
/// </summary>
if (!MethodData.Define (Parent.PartialContainer))
return false;
-
+
MethodBuilder = MethodData.MethodBuilder;
+#if GMCS_SOURCE
+ if (MethodBuilder.IsGenericMethod)
+ Parent.MemberCache.AddGenericMember (MethodBuilder, this);
+#endif
+
+ Parent.MemberCache.AddMember (MethodBuilder, this);
+
if (!TypeManager.IsGenericParameter (MemberType)) {
if (MemberType.IsAbstract && MemberType.IsSealed) {
Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
GetSignatureForError ());
}
- public override bool MarkForDuplicationCheck ()
- {
- caching_flags |= Flags.TestMethodDuplication;
- return true;
- }
-
public override string[] ValidAttributeTargets {
get {
return attribute_targets;
base.ApplyAttributeBuilder (a, cb);
}
- protected override bool CheckForDuplications ()
+ public bool CheckForDuplications ()
{
- ArrayList ar = Parent.PartialContainer.Methods;
- if (ar != null) {
- int arLen = ar.Count;
-
- for (int i = 0; i < arLen; i++) {
- Method m = (Method) ar [i];
- if (IsDuplicateImplementation (m))
- return false;
- }
- }
-
- ar = Parent.PartialContainer.Properties;
+ ArrayList ar = Parent.PartialContainer.Properties;
if (ar != null) {
for (int i = 0; i < ar.Count; ++i) {
PropertyBase pb = (PropertyBase) ar [i];
}
}
- ar = Parent.PartialContainer.Events;
- if (ar != null) {
- for (int i = 0; i < ar.Count; ++i) {
- Event ev = (Event) ar [i];
- if (ev.AreAccessorsDuplicateImplementation (this))
- return false;
- }
- }
-
return true;
}
}
}
+ public override bool EnableOverloadChecks (MemberCore overload)
+ {
+ // TODO: It can be deleted when members will be defined in correct order
+ if (overload is Operator)
+ return overload.EnableOverloadChecks (this);
+
+ if (overload is Indexer)
+ return false;
+
+ return base.EnableOverloadChecks (overload);
+ }
+
public static void Error1599 (Location loc, Type t)
{
Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
if (base_constructor_group == null)
return false;
-
+
base_constructor_group = base_constructor_group.OverloadResolve (
ec, argument_list, false, loc);
if (base_constructor_group == null)
return false;
-
+
ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
if (base_ctor == caller_builder){
return true;
}
- protected override bool CheckForDuplications ()
- {
- ArrayList ar = Parent.PartialContainer.InstanceConstructors;
- if (ar != null) {
- int arLen = ar.Count;
-
- for (int i = 0; i < arLen; i++) {
- Constructor m = (Constructor) ar [i];
- if (IsDuplicateImplementation (m))
- return false;
- }
- }
- return true;
- }
-
protected override bool CheckBase ()
{
if ((ModFlags & Modifiers.STATIC) != 0) {
if (!DefineParameters (Parameters))
return false;
- if (!CheckForDuplications ())
- return false;
+ if ((caching_flags & Flags.MethodOverloadsExist) != 0)
+ Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorBuilder.ConstructorName,
+ Parameters);
if (Parent.PartialContainer.Kind == Kind.Struct) {
if (ParameterTypes.Length == 0) {
ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
}
+ Parent.MemberCache.AddMember (ConstructorBuilder, this);
TypeManager.AddMethod (ConstructorBuilder, this);
return true;
if (ParameterInfo.Count > 0) {
ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
- if (al.Count > 3)
+ if (al.Count > 2)
MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
if (Parent.TypeBuilder.IsSubclassOf (TypeManager.attribute_type)) {
if (RootContext.Version == LanguageVersion.ISO_1)
Report.FeatureIsNotISO1 (loc, "fixed size buffers");
- if ((mod & Modifiers.VOLATILE) != 0)
- Modifiers.Error_InvalidModifier (loc, Modifiers.Name (Modifiers.VOLATILE));
-
this.size_expr = size_expr;
}
RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
+
+ Parent.MemberCache.AddMember (FieldBuilder, this);
TypeManager.RegisterFieldBase (FieldBuilder, this);
return true;
FieldBuilder = Parent.TypeBuilder.DefineField (
Name, MemberType, Modifiers.FieldAttr (ModFlags));
+ Parent.MemberCache.AddMember (FieldBuilder, this);
TypeManager.RegisterFieldBase (FieldBuilder, this);
}
catch (ArgumentException) {
method_data.Emit (parent);
}
+ public override bool EnableOverloadChecks (MemberCore overload)
+ {
+ // This can only happen with indexers and it will
+ // be catched as indexer difference
+ if (overload is AbstractPropertyEventMethod)
+ return true;
+
+ if (overload is MethodCore) {
+ caching_flags |= Flags.MethodOverloadsExist;
+ return true;
+ }
+ return false;
+ }
+
public override bool IsClsComplianceRequired()
{
return false;
return false;
Report.SymbolRelatedToPreviousError (method);
- Report.Error (111, Location, TypeContainer.Error111, method.GetSignatureForError ());
+ Report.Error (82, Location, "A member `{0}' is already reserved",
+ method.GetSignatureForError ());
return true;
}
}
}
- public override bool MarkForDuplicationCheck ()
- {
- caching_flags |= Flags.TestMethodDuplication;
- return true;
- }
-
protected bool CheckForDuplications ()
{
- if ((caching_flags & Flags.TestMethodDuplication) == 0)
+ if ((caching_flags & Flags.MethodOverloadsExist) == 0)
return true;
-
- ArrayList ar = Parent.PartialContainer.Methods;
- if (ar != null) {
- int arLen = ar.Count;
-
- for (int i = 0; i < arLen; i++) {
- Method m = (Method) ar [i];
- if (IsDuplicateImplementation (m))
- return false;
- }
- }
- return true;
+ return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
}
}
PropertyBuilder = Parent.TypeBuilder.DefineProperty (
MemberName.ToString (), PropertyAttributes.None, MemberType, null);
- if (!Get.IsDummy)
+ if (!Get.IsDummy) {
PropertyBuilder.SetGetMethod (GetBuilder);
-
- if (!Set.IsDummy)
+ Parent.MemberCache.AddMember (GetBuilder, Get);
+ }
+
+ if (!Set.IsDummy) {
PropertyBuilder.SetSetMethod (SetBuilder);
+ Parent.MemberCache.AddMember (SetBuilder, Set);
+ }
TypeManager.RegisterProperty (PropertyBuilder, this);
+ Parent.MemberCache.AddMember (PropertyBuilder, this);
return true;
}
EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);
EventBuilder.SetAddOnMethod (AddBuilder);
EventBuilder.SetRemoveOnMethod (RemoveBuilder);
+
+ Parent.MemberCache.AddMember (EventBuilder, this);
+ Parent.MemberCache.AddMember (AddBuilder, Add);
+ Parent.MemberCache.AddMember (RemoveBuilder, Remove);
+
return true;
}
}
- public class Indexer : PropertyBase {
-
+ public class Indexer : PropertyBase
+ {
class GetIndexerMethod : GetMethod
{
public GetIndexerMethod (PropertyBase method):
base (method, accessor)
{
}
+
+ public override bool EnableOverloadChecks (MemberCore overload)
+ {
+ if (base.EnableOverloadChecks (overload)) {
+ overload.caching_flags |= Flags.MethodOverloadsExist;
+ return true;
+ }
+
+ return false;
+ }
public override Parameters ParameterInfo {
get {
parameters = Parameters.MergeGenerated (((Indexer)method).parameters,
new Parameter (method.MemberType, "value", Parameter.Modifier.NONE, null, method.Location));
}
+
+ public override bool EnableOverloadChecks (MemberCore overload)
+ {
+ if (base.EnableOverloadChecks (overload)) {
+ overload.caching_flags |= Flags.MethodOverloadsExist;
+ return true;
+ }
+
+ return false;
+ }
}
const int AllowedModifiers =
Set = new SetIndexerMethod (this, set_block);
}
- protected override bool CheckForDuplications ()
- {
- ArrayList ar = Parent.PartialContainer.Indexers;
- if (ar != null) {
- int arLen = ar.Count;
-
- for (int i = 0; i < arLen; i++) {
- Indexer m = (Indexer) ar [i];
- if (IsDuplicateImplementation (m))
- return false;
- }
- }
-
- return true;
- }
-
- bool IsDuplicateImplementation (Indexer indexer)
- {
- if (this == indexer)
- return false;
-
- if (!MemberName.Equals (indexer.MemberName))
- return false;
-
- Type[] param_types = indexer.parameters.Types;
-
- // When it is not yet defined
- if (param_types == null)
- return false;
-
- if (param_types.Length != parameters.Count)
- return false;
-
- for (int i = 0; i < param_types.Length; i++)
- if (param_types [i] != parameters.Types [i])
- return false;
-
- Report.SymbolRelatedToPreviousError (indexer);
- Report.Error (111, Location, TypeContainer.Error111, indexer.GetSignatureForError ());
- return true;
- }
-
-
public override bool Define ()
{
if (!DoDefineBase ())
if (!CheckBase ())
return false;
+
+ if ((caching_flags & Flags.MethodOverloadsExist) != 0) {
+ if (!Parent.MemberCache.CheckExistingMembersOverloads (this, Name, parameters))
+ return false;
+ }
+
flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
if (!DefineAccessors ())
PropertyBuilder = Parent.TypeBuilder.DefineProperty (
Name, PropertyAttributes.None, MemberType, parameters.Types);
-
- if (!Get.IsDummy)
+
+ if (!Get.IsDummy) {
PropertyBuilder.SetGetMethod (GetBuilder);
+ Parent.MemberCache.AddMember (GetBuilder, Get);
+ }
- if (!Set.IsDummy)
+ if (!Set.IsDummy) {
PropertyBuilder.SetSetMethod (SetBuilder);
+ Parent.MemberCache.AddMember (SetBuilder, Set);
+ }
TypeManager.RegisterIndexer (PropertyBuilder, GetBuilder, SetBuilder, parameters.Types);
-
+ Parent.MemberCache.AddMember (PropertyBuilder, this);
return true;
}
+ public override bool EnableOverloadChecks (MemberCore overload)
+ {
+ if (overload is Indexer) {
+ caching_flags |= Flags.MethodOverloadsExist;
+ return true;
+ }
+
+ return false;
+ }
+
public override string GetDocCommentName (DeclSpace ds)
{
return DocUtil.GetMethodDocCommentName (this, parameters, ds);
return sb.ToString ();
}
- public override bool MarkForDuplicationCheck ()
- {
- caching_flags |= Flags.TestMethodDuplication;
- return true;
- }
-
protected override PropertyInfo ResolveBaseProperty ()
{
return Parent.PartialContainer.BaseCache.FindMemberToOverride (
base.ApplyAttributeBuilder (a, cb);
}
- protected override bool CheckForDuplications ()
- {
- ArrayList ar = Parent.PartialContainer.Operators;
- if (ar != null) {
- int arLen = ar.Count;
-
- for (int i = 0; i < arLen; i++) {
- Operator o = (Operator) ar [i];
- if (IsDuplicateImplementation (o))
- return false;
- }
- }
-
- ar = Parent.PartialContainer.Methods;
- if (ar != null) {
- int arLen = ar.Count;
-
- for (int i = 0; i < arLen; i++) {
- Method m = (Method) ar [i];
- if (IsDuplicateImplementation (m))
- return false;
- }
- }
-
- return true;
- }
-
public override bool Define ()
{
const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
return false;
}
- // imlicit and explicit operator of same types are not allowed
- if (OperatorType == OpType.Explicit || OperatorType == OpType.Implicit)
- MarkForDuplicationCheck ();
-
if (!base.Define ())
return false;
+ // imlicit and explicit operator of same types are not allowed
+ if (OperatorType == OpType.Explicit)
+ Parent.MemberCache.CheckExistingMembersOverloads (this, "op_Implicit", Parameters);
+ else if (OperatorType == OpType.Implicit)
+ Parent.MemberCache.CheckExistingMembersOverloads (this, "op_Explicit", Parameters);
+
if (MemberType == TypeManager.void_type) {
Report.Error (590, Location, "User-defined operators cannot return void");
return false;
FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType, field_attr);
TypeManager.RegisterConstant (FieldBuilder, this);
+ Parent.MemberCache.AddMember (FieldBuilder, this);
if (ttype == TypeManager.decimal_type)
Parent.PartialContainer.RegisterFieldForInitialization (this,
ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
Excluded = 1 << 9, // Method is conditional
- TestMethodDuplication = 1 << 10, // Test for duplication must be performed
+ MethodOverloadsExist = 1 << 10, // Test for duplication must be performed
IsUsed = 1 << 11,
IsAssigned = 1 << 12, // Field is assigned
HasExplicitLayout = 1 << 13
}
/// <summary>
- /// It helps to handle error 102 & 111 detection
+ /// Returns true when a member supports multiple overloads (methods, indexers, etc)
/// </summary>
- public virtual bool MarkForDuplicationCheck ()
+ public virtual bool EnableOverloadChecks (MemberCore overload)
{
return false;
}
return true;
}
- if (symbol.MarkForDuplicationCheck () && mc.MarkForDuplicationCheck ())
+ if (symbol.EnableOverloadChecks (mc))
return true;
Report.SymbolRelatedToPreviousError (mc);
private Type LookupNestedTypeInHierarchy (string name)
{
+ Type t = null;
// if the member cache has been created, lets use it.
// the member cache is MUCH faster.
- if (MemberCache != null)
- return MemberCache.FindNestedType (name);
+ if (MemberCache != null) {
+ t = MemberCache.FindNestedType (name);
+ if (t == null)
+ return null;
+
+ //
+ // FIXME: This hack is needed because member cache does not work
+ // with nested base generic types, it does only type name copy and
+ // not type construction
+ //
+#if !GMCS_SOURCE
+ return t;
+#endif
+ }
// no member cache. Do it the hard way -- reflection
- Type t = null;
for (Type current_type = TypeBuilder;
current_type != null && current_type != TypeManager.object_type;
current_type = current_type.BaseType) {
/// be used while the type is still being created since it doesn't use the cache
/// and relies on the filter doing the member name check.
/// </remarks>
- public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
- MemberFilter filter, object criteria);
+ ///
+ // [Obsolete ("Only MemberCache approach should be used")]
+ public virtual MemberList FindMembers (MemberTypes mt, BindingFlags bf,
+ MemberFilter filter, object criteria)
+ {
+ throw new NotSupportedException ();
+ }
/// <remarks>
/// If we have a MemberCache, return it. This property may return null if the
List = list;
}
- public static readonly MemberList Empty = new MemberList (new ArrayList ());
+ public static readonly MemberList Empty = new MemberList (new ArrayList (0));
/// <summary>
/// Cast the MemberList into a MemberInfo[] array.
/// this method is called multiple times with different BindingFlags.
/// </remarks>
MemberList GetMembers (MemberTypes mt, BindingFlags bf);
-
- /// <summary>
- /// Return the container's member cache.
- /// </summary>
- MemberCache MemberCache {
- get;
- }
}
/// <summary>
Timer.StopTimer (TimerType.CacheInit);
}
+ public MemberCache (Type baseType, IMemberContainer container)
+ {
+ this.Container = container;
+ if (baseType == null)
+ this.member_hash = new Hashtable ();
+ else
+ this.member_hash = SetupCache (TypeManager.LookupMemberCache (baseType));
+ }
+
public MemberCache (Type[] ifaces)
{
//
/// </summary>
static Hashtable SetupCache (MemberCache base_class)
{
- Hashtable hash = new Hashtable ();
-
if (base_class == null)
- return hash;
+ return new Hashtable ();
+ Hashtable hash = new Hashtable (base_class.member_hash.Count);
IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
while (it.MoveNext ()) {
- hash [it.Key] = ((ArrayList) it.Value).Clone ();
+ hash.Add (it.Key, ((ArrayList) it.Value).Clone ());
}
return hash;
}
+
+ //
+ // Converts ModFlags to BindingFlags
+ //
+ static BindingFlags GetBindingFlags (int modifiers)
+ {
+ BindingFlags bf;
+ if ((modifiers & Modifiers.STATIC) != 0)
+ bf = BindingFlags.Static;
+ else
+ bf = BindingFlags.Instance;
+
+ if ((modifiers & Modifiers.PRIVATE) != 0)
+ bf |= BindingFlags.NonPublic;
+ else
+ bf |= BindingFlags.Public;
+
+ return bf;
+ }
/// <summary>
/// Add the contents of `cache' to the member_hash.
AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
}
+ public void AddMember (MemberInfo mi, MemberCore mc)
+ {
+ AddMember (mi.MemberType, GetBindingFlags (mc.ModFlags), Container, mi.Name, mi);
+ }
+
+ public void AddGenericMember (MemberInfo mi, MemberCore mc)
+ {
+ AddMember (mi.MemberType, GetBindingFlags (mc.ModFlags), Container, mc.MemberName.Basename, mi);
+ }
+
+ public void AddNestedType (DeclSpace type)
+ {
+ AddMember (MemberTypes.NestedType, GetBindingFlags (type.ModFlags), (IMemberContainer) type.Parent,
+ type.TypeBuilder.Name, type.TypeBuilder);
+ }
+
+ public void AddInterface (MemberCache baseCache)
+ {
+ if (baseCache.member_hash.Count > 0)
+ AddCacheContents (baseCache);
+ }
+
void AddMember (MemberTypes mt, BindingFlags bf, IMemberContainer container,
string name, MemberInfo member)
{
{
if (using_global)
throw new Exception ();
-
+
bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
bool method_search = mt == MemberTypes.Method;
// If we have a method cache and we aren't already doing a method-only search,
throw new NotImplementedException (result.ToString ());
}
}
+
+ public bool CheckExistingMembersOverloads (MemberCore member, string name, Parameters parameters)
+ {
+ ArrayList entries = (ArrayList)member_hash [name];
+ if (entries == null)
+ return true;
+
+ int method_param_count = parameters.Count;
+ for (int i = entries.Count - 1; i >= 0; --i) {
+ CacheEntry ce = (CacheEntry) entries [i];
+
+ if (ce.Container != member.Parent.PartialContainer)
+ return true;
+
+ Type [] p_types;
+ ParameterData pd = null;
+ if ((ce.EntryType & EntryType.Property) != 0) {
+ p_types = TypeManager.GetArgumentTypes ((PropertyInfo) ce.Member);
+ } else {
+ pd = TypeManager.GetParameterData ((MethodBase)ce.Member);
+ p_types = pd.Types;
+ }
+
+ if (p_types.Length != method_param_count)
+ continue;
+
+ if (method_param_count > 0) {
+ int ii = method_param_count - 1;
+ Type type_a, type_b;
+ do {
+ type_a = parameters.ParameterType (ii);
+ type_b = p_types [ii];
+#if GMCS_SOURCE
+ if (type_a.IsGenericParameter && type_a.DeclaringMethod != null)
+ type_a = null;
+
+ if (type_b.IsGenericParameter && type_b.DeclaringMethod != null)
+ type_b = null;
+#endif
+ } while (type_a == type_b && ii-- != 0);
+
+ if (ii >= 0)
+ continue;
+
+ //
+ // Operators can differ in return type only
+ //
+ if ((ce.EntryType & EntryType.Method) != 0 && member is Operator) {
+ Operator op = TypeManager.GetMethod ((MethodBase) ce.Member) as Operator;
+ if (op != null && op.ReturnType != ((Operator) member).ReturnType)
+ continue;
+ }
+
+ //
+ // Report difference in parameter modifiers only
+ //
+ if (pd != null && !(member is AbstractPropertyEventMethod)) {
+ ii = method_param_count;
+ while (ii-- != 0 && parameters.ParameterModifier (ii) == pd.ParameterModifier (ii));
+
+ if (ii >= 0) {
+ Report.SymbolRelatedToPreviousError (ce.Member);
+ Report.Error (663, member.Location,
+ "An overloaded method `{0}' cannot differ on use of parameter modifiers only",
+ member.GetSignatureForError ());
+ return false;
+ }
+ }
+ }
+
+ Report.SymbolRelatedToPreviousError (ce.Member);
+ if ((ce.EntryType & EntryType.Method) != 0) {
+ IMethodData duplicate_member = TypeManager.GetMethod ((MethodBase) ce.Member);
+
+ if (member is Operator && duplicate_member is Operator) {
+ Report.Error (557, member.Location, "Duplicate user-defined conversion in type `{0}'",
+ member.Parent.GetSignatureForError ());
+ return false;
+ }
+
+ bool is_reserved_a = member is AbstractPropertyEventMethod || member is Operator;
+ bool is_reserved_b = duplicate_member is AbstractPropertyEventMethod || duplicate_member is Operator;
+
+ if (is_reserved_a || is_reserved_b) {
+ Report.Error (82, member.Location, "A member `{0}' is already reserved",
+ is_reserved_a ?
+ TypeManager.GetFullNameSignature (ce.Member) :
+ member.GetSignatureForError ());
+ return false;
+ }
+ }
+
+ Report.Error (111, member.Location,
+ "A member `{0}' is already defined. Rename this member or use different parameter types",
+ member.GetSignatureForError ());
+ return false;
+ }
+
+ return true;
+ }
}
}
/// <summary>
/// Holds Delegates
/// </summary>
- public class Delegate : DeclSpace {
+ public class Delegate : DeclSpace, IMemberContainer
+ {
public Expression ReturnType;
public Parameters Parameters;
Expression instance_expr;
MethodBase delegate_method;
ReturnParameter return_attributes;
+
+ MemberCache member_cache;
const int AllowedModifiers =
Modifiers.NEW |
}
}
#endif
+ member_cache = new MemberCache (TypeManager.multicast_delegate_type, this);
// FIXME: POSSIBLY make this static, as it is always constant
//
const_parameters.Resolve (null);
TypeManager.RegisterMethod (ConstructorBuilder, const_parameters);
-
+ member_cache.AddMember (ConstructorBuilder, this);
ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
TypeManager.RegisterMethod (InvokeBuilder, Parameters);
+ member_cache.AddMember (InvokeBuilder, this);
//
// BeginInvoke
BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
TypeManager.RegisterMethod (BeginInvokeBuilder, async_parameters);
+ member_cache.AddMember (BeginInvokeBuilder, this);
//
// EndInvoke is a bit more interesting, all the parameters labeled as
end_parameters.ApplyAttributes (EndInvokeBuilder);
TypeManager.RegisterMethod (EndInvokeBuilder, end_parameters);
+ member_cache.AddMember (EndInvokeBuilder, this);
return true;
}
return sb.ToString ();
}
- // Hack around System.Reflection as found everywhere else
- public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
- MemberFilter filter, object criteria)
- {
- ArrayList members = new ArrayList (2);
-
- if ((mt & MemberTypes.Constructor) != 0) {
- if (ConstructorBuilder != null && filter (ConstructorBuilder, criteria))
- members.Add (ConstructorBuilder);
- }
-
- if ((mt & MemberTypes.Method) != 0) {
- if (InvokeBuilder != null)
- if (filter (InvokeBuilder, criteria))
- members.Add (InvokeBuilder);
-
- if (BeginInvokeBuilder != null)
- if (filter (BeginInvokeBuilder, criteria))
- members.Add (BeginInvokeBuilder);
-
- if (EndInvokeBuilder != null)
- if (filter (EndInvokeBuilder, criteria))
- members.Add (EndInvokeBuilder);
- }
-
- return new MemberList (members);
- }
-
public override MemberCache MemberCache {
get {
- return null;
+ return member_cache;
}
}
public override string DocCommentHeader {
get { return "T:"; }
}
+
+ #region IMemberContainer Members
+
+ string IMemberContainer.Name
+ {
+ get { throw new NotImplementedException (); }
+ }
+
+ Type IMemberContainer.Type
+ {
+ get { throw new NotImplementedException (); }
+ }
+
+ MemberCache IMemberContainer.BaseCache
+ {
+ get { throw new NotImplementedException (); }
+ }
+
+ bool IMemberContainer.IsInterface {
+ get {
+ return false;
+ }
+ }
+
+ MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
+ {
+ throw new NotImplementedException ();
+ }
+
+ #endregion
}
//
if (type == TypeManager.anonymous_method_type)
return;
- if (Type.FullName == target.FullName){
+ if (TypeManager.IsGenericParameter (Type) && TypeManager.IsGenericParameter (target) && type.Name == target.Name) {
+#if GMCS_SOURCE
+ string sig1 = Type.DeclaringMethod == null ?
+ TypeManager.CSharpName (Type.DeclaringType) :
+ TypeManager.CSharpSignature (Type.DeclaringMethod);
+ string sig2 = target.DeclaringMethod == null ?
+ TypeManager.CSharpName (target.DeclaringType) :
+ TypeManager.CSharpSignature (target.DeclaringMethod);
+ Report.ExtraInformation (loc,
+ String.Format (
+ "The generic parameter `{0}' of `{1}' cannot be converted to the generic parameter `{0}' of `{2}' (in the previous ",
+ Type.Name, sig1, sig2));
+#endif
+ } else if (Type.FullName == target.FullName){
Report.ExtraInformation (loc,
String.Format (
- "The type {0} has two conflicting definitions, one comes from {1} and the other from {2}",
+ "The type `{0}' has two conflicting definitions, one comes from `{1}' and the other from `{2}' (in the previous ",
Type.FullName, Type.Assembly.FullName, target.Assembly.FullName));
-
}
if (expl) {
{
const FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal;
FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType, attr);
+ Parent.MemberCache.AddMember (FieldBuilder, this);
TypeManager.RegisterConstant (FieldBuilder, this);
return true;
}
return true;
}
+ protected override bool DoDefineMembers ()
+ {
+ member_cache = new MemberCache (TypeManager.enum_type, this);
+ DefineContainerMembers (constants);
+ return true;
+ }
+
//
// Used for error reporting only
//
throw new NotImplementedException ();
}
- MemberCache IMemberContainer.MemberCache {
- get { throw new NotImplementedException (); }
- }
-
public bool IsSubclassOf (Type t)
{
throw new NotImplementedException ();
{
}
- public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
- MemberFilter filter, object criteria)
- {
- throw new NotImplementedException ();
- }
-
public override MemberCache MemberCache {
get { throw new NotImplementedException (); }
}
throw new InternalErrorException ("should not be called");
}
- public override MemberList FindMembers (MemberTypes mt, BindingFlags bf, MemberFilter filter, object criteria)
- {
- throw new InternalErrorException ("should not be called");
- }
-
public override MemberCache MemberCache {
get { return PartialContainer.MemberCache; }
}
public static MemberCache LookupMemberCache (Type t)
{
- if (t.Assembly == CodeGen.Assembly.Builder) {
- IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
+ if (t.Module == CodeGen.Module.Builder) {
+ DeclSpace container = (DeclSpace)builder_to_declspace [t];
if (container != null)
return container.MemberCache;
}
#if GMCS_SOURCE
if (t is GenericTypeParameterBuilder) {
- IMemberContainer container = builder_to_type_param [t] as IMemberContainer;
+ TypeParameter container = builder_to_type_param [t] as TypeParameter;
if (container != null)
return container.MemberCache;
/// <summary>
/// Returns the TypeHandle for TypeManager.array_type.
/// </summary>
- public static IMemberContainer ArrayType {
+ public static TypeHandle ArrayType {
get {
if (array_type != null)
return array_type;
private TypeHandle (Type type)
{
this.type = type;
-#if MS_COMPATIBLE && GMCS_SOURCE
- if (type.IsGenericType && !type.IsGenericTypeDefinition)
- this.type = this.type.GetGenericTypeDefinition ();
-#endif
full_name = type.FullName != null ? type.FullName : type.Name;
if (type.BaseType != null) {
base_cache = TypeManager.LookupMemberCache (type.BaseType);
public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
{
- MemberInfo [] members;
+ MemberInfo [] members;
#if GMCS_SOURCE
if (type is GenericTypeParameterBuilder)
#endif
if (mt == MemberTypes.Event)
- members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
- else
- members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
- null, null);
- Array.Reverse (members);
+ members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
+ else
+ members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
+ null, null);
+
+ if (members.Length == 0)
+ return MemberList.Empty;
- return new MemberList (members);
+ Array.Reverse (members);
+ return new MemberList (members);
}
// IMemberFinder methods
<AppDesignerFolder>Properties</AppDesignerFolder>\r
<RootNamespace>nunit_console</RootNamespace>\r
<AssemblyName>nunit-console</AssemblyName>\r
- <JDKName>1.5.0_05</JDKName>\r
+ <JDKName>1.6</JDKName>\r
<GHProjectType>1</GHProjectType>\r
<Version>2.0</Version>\r
<ProjectTypeGuids>{F6B19D50-1E2E-4e87-ADFB-10393B439DE0};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\r
<Project>{995DE32D-06AB-4926-97FF-565B9205D5F8}</Project>\r
<Name>nunit.core.dll20.J2EE</Name>\r
</ProjectReference>\r
+ <ProjectReference Include="..\framework\nunit.framework.dll20.J2EE.csproj">\r
+ <Project>{ACDA29DB-62AB-4AF8-8862-B3B4FC755BBC}</Project>\r
+ <Name>nunit.framework.dll20.J2EE</Name>\r
+ </ProjectReference>\r
<ProjectReference Include="..\util\nunit.util.dll20.J2EE.csproj">\r
<Project>{170EE6EB-1DEF-4BC6-88B7-6A90358BAA6B}</Project>\r
<Name>nunit.util.dll20.J2EE</Name>\r
--- /dev/null
+class C
+{
+ class O : M
+ {
+ public override void Foo ()
+ {
+ }
+ }
+
+ class N
+ {
+ public virtual void Foo ()
+ {
+ }
+ }
+
+ class M : N
+ {
+ }
+
+ public static void Main ()
+ {
+ }
+}
+
+
--- /dev/null
+class C
+{
+ void Foo (int i)
+ {
+ }
+
+ void Foo (ref int i)
+ {
+ }
+
+ void Bar (out bool b)
+ {
+ b = false;
+ }
+
+ void Bar (bool b)
+ {
+ }
+
+ public static void Main ()
+ {
+ }
+}
+
+
+2007-10-19 Marek Habersack <mhabersack@novell.com>
+
+ * Makefile: fix the buildbot build - mconfig should be
+ listed also in DIST_ONLY_SUBDIRS
+
+2007-10-19 Marek Habersack <mhabersack@novell.com>
+
+ * Makefile (net_2_0_SUBDIRS): added mconfig to the build
+
2007-09-10 Wade Berrier <wberrier@novell.com>
* removecomments.sh: use `` instead of $() since it works on
net_1_1_bootstrap_SUBDIRS = gacutil security resgen culevel
net_2_0_bootstrap_SUBDIRS = resgen
-net_2_0_SUBDIRS = al corcompare wsdl compiler-tester monop xbuild resgen mono-service mkbundle sgen security
+net_2_0_SUBDIRS = al corcompare wsdl compiler-tester monop xbuild resgen mono-service mkbundle sgen security mconfig
net_2_1_SUBDIRS = tuner
-DIST_ONLY_SUBDIRS = xbuild sgen
+DIST_ONLY_SUBDIRS = xbuild sgen mconfig
include ../build/rules.make
--- /dev/null
+2007-10-22 Marek Habersack <mhabersack@novell.com>
+
+ * mconfig.cs: do not use Mono.GetOptions. Added own option parsing
+ code instead.
+
+2007-10-19 Marek Habersack <mhabersack@novell.com>
+
+ * Makefile: include consts.cs.in in the dist tarball.
+ Extra distribution files should be named in EXTRA_DISTFILES.
+
+2007-10-19 Marek Habersack <mhabersack@novell.com>
+
+ * Makefile (DISTFILES): added
+
+2007-10-19 Marek Habersack <mhabersack@novell.com>
+
+ * Initial import
+
--- /dev/null
+thisdir = tools/mconfig
+SUBDIRS =
+include ../../build/rules.make
+
+LOCAL_MCS_FLAGS = -r:System.Xml.dll -r:Mono.GetOptions.dll
+PROGRAM = mconfig.exe
+
+BUILT_SOURCES=Mono.MonoConfig/consts.cs
+
+Mono.MonoConfig/consts.cs: Mono.MonoConfig/consts.cs.in
+ sed -e "s;@MONO_PREFIX@;$(prefix);g" < $< > $@
+
+install-local: install-local-data
+
+install-local-data:
+ $(MKINSTALLDIRS) $(DESTDIR)$(prefix)/etc/mono/mconfig/
+ $(INSTALL_DATA) data/config.xml $(DESTDIR)$(prefix)/etc/mono/mconfig
+
+EXTRA_DISTFILES = TODO data/config.xml Mono.MonoConfig/consts.cs.in
+
+include ../../build/executable.make
--- /dev/null
+//
+// AssemblyInfo.cs
+//
+// Author:
+// Marek Habersack <mhabersack@novell.com>
+//
+// (C) 2007 Marek Habersack
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+[assembly: AssemblyTitle ("Mono.MonoConfig")]
+[assembly: AssemblyDescription ("Utility for modifying .NET configuration files")]
+[assembly: AssemblyConfiguration ("Development version")]
+[assembly: AssemblyProduct ("mconfig")]
+[assembly: AssemblyCompany ("MONO development team")]
+[assembly: AssemblyCopyright ("Copyright (c) 2007 Novell, Inc")]
+[assembly: AssemblyCulture ("")]
+
+[assembly: CLSCompliant (false)]
+[assembly: ComVisible (false)]
+
+[assembly: AssemblyVersion ("0.1.0.0")]
+
+#if KEYFILE
+[assembly: AssemblyKeyFile("../../mono.snk")]
+#endif
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Xml;
+using System.Xml.XPath;
+
+namespace Mono.MonoConfig
+{
+ public class ConfigBlockBlock
+ {
+ string name;
+ Section requires;
+ string contents;
+
+ public string Name {
+ get { return name; }
+ }
+
+ public Section Requires {
+ get { return requires; }
+ }
+
+ public string Contents {
+ get { return contents; }
+ }
+
+ public ConfigBlockBlock (string name, Section requires, string contents)
+ {
+ this.name = name;
+ this.requires = requires;
+ this.contents = contents;
+ }
+ }
+}
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Xml;
+using System.Xml.XPath;
+
+namespace Mono.MonoConfig
+{
+ public class ConfigBlockNodeHandler : IDocumentNodeHandler, IStorageConsumer, IConfigBlockContainer
+ {
+ string name;
+ Section requirements;
+ string contents;
+ Dictionary <string, ConfigBlockBlock> storage;
+
+ public void ReadConfiguration (XPathNavigator nav)
+ {
+ name = Helpers.GetRequiredNonEmptyAttribute (nav, "name");
+
+ requirements = new Section ();
+ Helpers.BuildSectionTree (nav.Select ("requires/section[string-length(@name) > 0]"), requirements);
+
+ XPathNodeIterator iter = nav.Select ("contents/text()");
+ StringBuilder sb = new StringBuilder ();
+
+ while (iter.MoveNext ())
+ sb.Append (iter.Current.Value);
+ if (sb.Length > 0)
+ contents = sb.ToString ();
+ }
+
+ public void StoreConfiguration ()
+ {
+ AssertStorage ();
+
+ ConfigBlockBlock block = new ConfigBlockBlock (name, requirements, contents);
+ if (storage.ContainsKey (name))
+ storage [name] = block; // allow for silent override
+ else
+ storage.Add (name, block);
+
+ // Prepare to handle more sections
+ requirements = new Section ();
+ contents = null;
+ }
+
+ public void SetStorage (object storage)
+ {
+ this.storage = storage as Dictionary <string, ConfigBlockBlock>;
+ if (this.storage == null)
+ throw new ApplicationException ("Invalid storage type.");
+ }
+
+ public ConfigBlockBlock FindConfigBlock (string name)
+ {
+ AssertStorage ();
+
+ if (storage.ContainsKey (name))
+ return storage [name];
+
+ return null;
+ }
+
+ void AssertStorage ()
+ {
+ if (storage == null)
+ throw new ApplicationException ("No storage attached");
+ }
+ }
+}
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Xml;
+using System.Xml.XPath;
+
+namespace Mono.MonoConfig
+{
+ class HandlerDescription
+ {
+ Type handlerType;
+ Type handlerStorageType;
+ string section;
+
+ object handler;
+ object storage;
+
+ public object Handler {
+ get {
+ if (handler != null)
+ return handler;
+ handler = Activator.CreateInstance (handlerType);
+ return handler;
+ }
+ }
+
+ public object Storage {
+ get {
+ if (storage != null)
+ return storage;
+
+ storage = Activator.CreateInstance (handlerStorageType);
+ return storage;
+ }
+ }
+
+ public string Section {
+ get { return section; }
+ }
+
+ public bool Implements (string interfaceName)
+ {
+ return handlerType.GetInterface (interfaceName) != null;
+ }
+
+ public HandlerDescription (string handlerTypeName, string handlerStorageTypeName, string section)
+ {
+ handlerType = Type.GetType (handlerTypeName, true);
+ if (handlerType.GetInterface ("Mono.MonoConfig.IDocumentNodeHandler") == null)
+ throw new ApplicationException (
+ String.Format ("Handler for section '{0}' must implement the '{1}' interface",
+ section, typeof (Mono.MonoConfig.IDocumentNodeHandler)));
+
+ handlerStorageType = Type.GetType (handlerStorageTypeName, true);
+ this.section = section;
+ }
+ }
+
+ public class Configuration
+ {
+ string[] configs;
+ Dictionary <string, HandlerDescription> section_handlers;
+ List <HandlerDescription> section_handlers_ordered;
+ List <XPathDocument> config_documents;
+ bool loaded;
+
+ public Configuration () : this (null)
+ {}
+
+ public Configuration (string[] configs)
+ {
+ this.configs = configs;
+ section_handlers = new Dictionary <string, HandlerDescription> ();
+ section_handlers_ordered = new List <HandlerDescription> ();
+ config_documents = new List <XPathDocument> (configs != null ? configs.Length : 1);
+ }
+
+ public void WriteDefaultConfigFile (string name, string path, FeatureTarget target)
+ {
+ AssertLoaded ();
+
+ if (String.IsNullOrEmpty (name))
+ throw new ArgumentException ("name", "Must not be null or empty");
+
+ IDefaultConfigFileContainer[] containers = GetHandlersForInterface <IDefaultConfigFileContainer> ();
+ if (containers == null || containers.Length == 0)
+ throw new ApplicationException ("Cannot find any handler for writing default config files");
+
+ IDefaultContainer[] defaults = GetHandlersForInterface <IDefaultContainer> ();
+
+ bool written = false;
+ foreach (IDefaultConfigFileContainer container in containers) {
+ if (container.HasDefaultConfigFile (name, target)) {
+ container.WriteDefaultConfigFile (name, target, path, defaults);
+ written = true;
+ break;
+ }
+ }
+
+ if (!written)
+ throw new ApplicationException (
+ String.Format ("Definition of default config file '{0}' for target '{1}' not found.",
+ name, target));
+ }
+
+ public string[] DefaultConfigFiles {
+ get {
+ AssertLoaded ();
+
+ IDefaultConfigFileContainer[] containers = GetHandlersForInterface <IDefaultConfigFileContainer> ();
+ if (containers == null || containers.Length == 0)
+ return null;
+
+ List <string> defaults = new List <string> ();
+ foreach (IDefaultConfigFileContainer container in containers)
+ defaults.AddRange (container.DefaultConfigFiles);
+
+ defaults.Sort ();
+ return defaults.ToArray ();
+ }
+ }
+
+ public void AddFeature (string configFilePath, FeatureTarget target, string featureName)
+ {
+ AssertLoaded ();
+
+ if (String.IsNullOrEmpty (configFilePath))
+ throw new ArgumentException ("configFilePath", "Must not be null or empty");
+ if (String.IsNullOrEmpty (featureName))
+ throw new ArgumentException ("featureName", "Must not be null or empty");
+
+ IFeatureGenerator[] generators = GetHandlersForInterface <IFeatureGenerator> ();
+ if (generators == null || generators.Length == 0)
+ throw new ApplicationException ("Cannot find any feature generator");
+
+ IDefaultContainer[] defaults = GetHandlersForInterface <IDefaultContainer> ();
+ IConfigBlockContainer[] configBlocks = GetHandlersForInterface <IConfigBlockContainer> ();
+
+ bool added = false;
+ foreach (IFeatureGenerator generator in generators) {
+ if (generator.HasFeature (featureName)) {
+ generator.AddFeature (configFilePath, featureName, target, defaults, configBlocks);
+ added = true;
+ break;
+ }
+ }
+
+ if (!added)
+ throw new ApplicationException (
+ String.Format ("Definition of feature '{0}' for target '{1}' not found.",
+ featureName, target));
+ }
+
+ public string[] Features {
+ get {
+ AssertLoaded ();
+
+ IFeatureGenerator[] generators = GetHandlersForInterface <IFeatureGenerator> ();
+ if (generators == null || generators.Length == 0)
+ return null;
+
+ List <string> features = new List <string> ();
+ foreach (IFeatureGenerator generator in generators)
+ features.AddRange (generator.Features);
+
+ features.Sort ();
+ return features.ToArray ();
+ }
+ }
+
+ public void Load (string[] configs)
+ {
+ this.configs = configs;
+ Load ();
+ }
+
+ public void Load ()
+ {
+ if (configs == null || configs.Length == 0)
+ return;
+
+ if (loaded) {
+ section_handlers.Clear ();
+ section_handlers_ordered.Clear ();
+ config_documents.Clear ();
+ loaded = false;
+ }
+
+ XPathDocument doc;
+ foreach (string config in configs) {
+ if (String.IsNullOrEmpty (config))
+ continue;
+
+ try {
+ doc = new XPathDocument (config);
+ config_documents.Add (doc);
+ } catch (Exception) {
+ continue;
+ }
+ }
+
+ XPathNavigator nav;
+ XPathNodeIterator iter;
+
+ // First configure section handlers
+ List <HandlerDescription> handlers_from_file = new List <HandlerDescription> ();
+
+ foreach (XPathDocument xpdoc in config_documents) {
+ handlers_from_file.Clear ();
+
+ nav = xpdoc.CreateNavigator ();
+ iter = nav.Select ("//mconfig/configuration/handlers/handler[string-length (@section) > 0]");
+
+ while (iter.MoveNext ())
+ AddSectionHandler (iter.Current, handlers_from_file);
+ section_handlers_ordered.InsertRange (0, handlers_from_file);
+ }
+
+ // Process all configs looking for all sections with known handlers
+ foreach (XPathDocument xpdoc in config_documents) {
+ nav = xpdoc.CreateNavigator ();
+ iter = nav.Select ("//mconfig/*");
+
+ while (iter.MoveNext ())
+ HandleTopLevelNode (iter.Current);
+ }
+
+ loaded = true;
+ }
+
+ public T[] GetHandlersForInterface <T> ()
+ {
+ AssertLoaded ();
+
+ string typeName = typeof (T).ToString ();
+ object handler;
+
+ List <T> handlers = null;
+ foreach (HandlerDescription hd in section_handlers_ordered) {
+ if (hd.Implements (typeName)) {
+ if (handlers == null)
+ handlers = new List <T> (1);
+ handler = hd.Handler;
+ if (handler is IStorageConsumer)
+ ((IStorageConsumer) handler).SetStorage (hd.Storage);
+
+ handlers.Add ((T)handler);
+ }
+ }
+
+ if (handlers == null)
+ return null;
+
+ return handlers.ToArray ();
+ }
+
+ void HandleTopLevelNode (XPathNavigator nav)
+ {
+ string section = nav.LocalName;
+
+ if (!section_handlers.ContainsKey (section))
+ return;
+
+ HandlerDescription hd = section_handlers [section];
+ if (hd == null)
+ return;
+
+ IDocumentNodeHandler handler = hd.Handler as IDocumentNodeHandler;
+ object storage = hd.Storage;
+
+ if (handler == null || storage == null)
+ return;
+
+ if (handler is IStorageConsumer)
+ ((IStorageConsumer) handler).SetStorage (storage);
+
+ handler.ReadConfiguration (nav);
+ handler.StoreConfiguration ();
+ }
+
+ void AddSectionHandler (XPathNavigator nav, List <HandlerDescription> handlers)
+ {
+ string section = Helpers.GetRequiredNonEmptyAttribute (nav, "section");
+ HandlerDescription hd = new HandlerDescription (Helpers.GetRequiredNonEmptyAttribute (nav, "type"),
+ Helpers.GetRequiredNonEmptyAttribute (nav, "storageType"),
+ section);
+
+ if (section_handlers.ContainsKey (section)) {
+ HandlerDescription old = section_handlers [section];
+ section_handlers [section] = hd;
+
+ handlers.Remove (old);
+ handlers.Add (hd);
+ } else {
+ section_handlers.Add (section, hd);
+ handlers.Add (hd);
+ }
+ }
+
+ void AssertLoaded ()
+ {
+ if (!loaded)
+ throw new ApplicationException ("Configuration not loaded yet");
+ }
+ }
+}
+
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+using System.Xml;
+using System.Xml.XPath;
+
+namespace Mono.MonoConfig
+{
+ class DefaultConfigFile
+ {
+ string name;
+ string fileName;
+ FeatureTarget target;
+ Section sections;
+
+ public string Name {
+ get { return name; }
+ }
+
+ public string FileName {
+ get { return fileName; }
+ }
+
+ public FeatureTarget Target {
+ get { return target; }
+ }
+
+ public Section Sections {
+ get { return sections; }
+ }
+
+ public DefaultConfigFile (string name, string fileName, FeatureTarget target, Section sections)
+ {
+ this.name = name;
+ this.fileName = fileName;
+ this.target = target;
+ this.sections = sections;
+ }
+ }
+
+ public delegate void OverwriteFileEventHandler (object sender, OverwriteFileEventArgs e);
+
+ public sealed class OverwriteFileEventArgs : System.EventArgs
+ {
+ string name;
+ string path;
+ FeatureTarget target;
+ bool overwrite;
+
+ public string Name {
+ get { return name; }
+ }
+
+ public string Path {
+ get { return path; }
+ }
+
+ public FeatureTarget Target {
+ get { return target; }
+ }
+
+ public bool Overwrite {
+ get { return overwrite; }
+ set { overwrite = value; }
+ }
+
+ public OverwriteFileEventArgs (string name, string path, FeatureTarget target, bool overwrite)
+ {
+ this.name = name;
+ this.path = path;
+ this.target = target;
+ this.overwrite = overwrite;
+ }
+ }
+
+ public class DefaultConfigFileNodeHandler : IDocumentNodeHandler, IDefaultConfigFileContainer, IStorageConsumer
+ {
+ string name;
+ string fileName;
+ FeatureTarget target;
+ Section sections;
+ Dictionary <string, DefaultConfigFile> storage;
+
+ public event OverwriteFileEventHandler OverwriteFile;
+
+ public void ReadConfiguration (XPathNavigator nav)
+ {
+ name = Helpers.GetRequiredNonEmptyAttribute (nav, "name");
+ target = Helpers.ConvertTarget (Helpers.GetRequiredNonEmptyAttribute (nav, "target"));
+ fileName = Helpers.GetOptionalAttribute (nav, "fileName");
+
+ if (String.IsNullOrEmpty (fileName))
+ fileName = name;
+
+ sections = new Section ();
+ Helpers.BuildSectionTree (nav.Select ("./section[string-length (@name) > 0]"), sections);
+ }
+
+ public void StoreConfiguration ()
+ {
+ AssertStorage ();
+
+ DefaultConfigFile dcf = new DefaultConfigFile (name, fileName, target, sections);
+ if (storage.ContainsKey (name))
+ storage [name] = dcf;
+ else
+ storage.Add (name, dcf);
+
+ name = null;
+ fileName = null;
+ sections = null;
+ }
+
+ public void SetStorage (object storage)
+ {
+ this.storage = storage as Dictionary <string, DefaultConfigFile>;
+ if (this.storage == null)
+ throw new ApplicationException ("Invalid storage type");
+ }
+
+ public ICollection <string> DefaultConfigFiles {
+ get {
+ AssertStorage ();
+
+ if (storage.Count == 0)
+ return null;
+
+ List <string> ret = new List <string>(storage.Count);
+ DefaultConfigFile dcf;
+
+ foreach (KeyValuePair <string, DefaultConfigFile> kvp in storage) {
+ dcf = kvp.Value;
+ ret.Add (String.Format ("{0} (Target: {1}; Output file: {2})",
+ kvp.Key, dcf.Target, dcf.FileName));
+ }
+
+ return ret;
+ }
+ }
+
+ public bool HasDefaultConfigFile (string name, FeatureTarget target)
+ {
+ AssertStorage ();
+
+ if (storage.ContainsKey (name)) {
+ DefaultConfigFile dcf = storage [name];
+ if (dcf == null)
+ return false;
+
+ if (target != FeatureTarget.Any && dcf.Target != target)
+ return false;
+
+ return true;
+ }
+
+ return false;
+ }
+
+ public void WriteDefaultConfigFile (string name, FeatureTarget target, string path, IDefaultContainer[] defaults)
+ {
+ AssertStorage ();
+
+ DefaultConfigFile dcf;
+ if (!storage.ContainsKey (name) || (dcf = storage [name]) == null)
+ throw new ApplicationException (
+ String.Format ("Definition of the '{0}' default config file not found.", name));
+
+ if (target != FeatureTarget.Any && dcf.Target != target)
+ throw new ApplicationException (
+ String.Format ("Config file '{0}' can be generated only for the '{1}' target",
+ name, target));
+
+ string targetFile = Path.Combine (path, dcf.Name);
+ if (File.Exists (targetFile)) {
+ OverwriteFileEventArgs args = new OverwriteFileEventArgs (
+ name,
+ path,
+ target,
+ true
+ );
+
+ OnOverwriteFile (args);
+ if (!args.Overwrite)
+ return;
+ }
+
+ try {
+ if (!Directory.Exists (path))
+ Directory.CreateDirectory (path);
+ } catch (Exception ex) {
+ throw new ApplicationException (
+ String.Format ("Could not create directory '{0}'", path),
+ ex);
+ }
+
+ XmlDocument doc = new XmlDocument ();
+ PopulateDocument (name, target, doc, dcf, defaults);
+ Helpers.SaveXml (doc, targetFile);
+ }
+
+ void OnOverwriteFile (OverwriteFileEventArgs args)
+ {
+ if (OverwriteFile == null)
+ return;
+
+ OverwriteFile (this, args);
+ }
+
+ void PopulateDocument (string name, FeatureTarget target, XmlDocument doc, DefaultConfigFile dcf,
+ IDefaultContainer[] defaults)
+ {
+ List <Section> children = dcf.Sections != null ? dcf.Sections.Children : null;
+ if (children == null || children.Count == 0)
+ return;
+
+ PopulateDocument (name, target, doc, doc, defaults, children);
+ }
+
+ void PopulateDocument (string name, FeatureTarget target, XmlDocument doc, XmlNode parent,
+ IDefaultContainer[] defaults, List <Section> children)
+ {
+ if (defaults == null || defaults.Length == 0)
+ return;
+
+ XmlNode node;
+ XmlDocument tmp;
+
+ foreach (Section s in children) {
+ tmp = Helpers.FindDefault (defaults, s.Name, target);
+ if (tmp == null)
+ continue;
+
+ node = doc.ImportNode (tmp.DocumentElement.FirstChild, true);
+ try {
+ PopulateDocument (name, target, doc, node, defaults, s.Children);
+ } catch (Exception ex) {
+ throw new ApplicationException (
+ String.Format ("Error building default config file '{0}'", name),
+ ex);
+ }
+
+ parent.AppendChild (node);
+ }
+ }
+
+ void AssertStorage ()
+ {
+ if (storage == null)
+ throw new ApplicationException ("No storage attached");
+ }
+ }
+}
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Xml;
+using System.Xml.XPath;
+
+namespace Mono.MonoConfig
+{
+ class DefaultNode
+ {
+ string contents;
+ FeatureTarget target;
+
+ public string Contents {
+ get { return contents; }
+ }
+
+ public FeatureTarget Target {
+ get { return target; }
+ }
+
+ public DefaultNode (string contents, FeatureTarget target)
+ {
+ this.contents = contents;
+ this.target = target;
+ }
+ }
+
+ public class DefaultNodeHandler : IDocumentNodeHandler, IDefaultContainer, IStorageConsumer
+ {
+ string section;
+ string contents;
+ FeatureTarget target;
+
+ Dictionary <string, DefaultNode> storage;
+
+ public void ReadConfiguration (XPathNavigator nav)
+ {
+ section = Helpers.GetRequiredNonEmptyAttribute (nav, "section");
+ target = Helpers.ConvertTarget (Helpers.GetRequiredNonEmptyAttribute (nav, "target"));
+
+ XPathNodeIterator iter = nav.Select ("./text()");
+ StringBuilder sb = new StringBuilder ();
+
+ while (iter.MoveNext ())
+ sb.Append (iter.Current.Value);
+ if (sb.Length > 0)
+ contents = sb.ToString ();
+ }
+
+ public void StoreConfiguration ()
+ {
+ AssertStorage ();
+
+ DefaultNode dn = new DefaultNode (contents, target);
+
+ if (storage.ContainsKey (section))
+ storage [section] = dn;
+ else
+ storage.Add (section, dn);
+
+ section = null;
+ contents = null;
+ storage = null;
+ }
+
+ public string FindDefault (string sectionName, FeatureTarget target)
+ {
+ AssertStorage ();
+
+ if (storage.ContainsKey (sectionName)) {
+ DefaultNode dn = storage [sectionName];
+
+ if (target == FeatureTarget.Any || dn.Target == FeatureTarget.Any || dn.Target == target)
+ return dn.Contents;
+ }
+
+ return null;
+ }
+
+ public void SetStorage (object storage)
+ {
+ this.storage = storage as Dictionary <string, DefaultNode>;
+ if (this.storage == null)
+ throw new ApplicationException ("Invalid storage type");
+ }
+
+ void AssertStorage ()
+ {
+ if (storage == null)
+ throw new ApplicationException ("No storage attached");
+ }
+ }
+}
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Xml;
+using System.Xml.XPath;
+
+namespace Mono.MonoConfig
+{
+ public class FeatureBlock
+ {
+ string name;
+ FeatureTarget target;
+
+ public string Name {
+ get { return name; }
+ }
+
+ public FeatureTarget Target {
+ get { return target; }
+ }
+
+ public FeatureBlock (XPathNavigator node, FeatureTarget target)
+ {
+ this.name = Helpers.GetRequiredNonEmptyAttribute (node, "name");
+ this.target = target;
+ }
+ }
+}
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+using System.Xml;
+using System.Xml.XPath;
+
+namespace Mono.MonoConfig
+{
+ public class FeatureNodeHandler : IDocumentNodeHandler, IStorageConsumer, IFeatureGenerator
+ {
+ string name;
+ FeatureTarget target;
+ List <FeatureBlock> blocks;
+ Dictionary <string, List <FeatureBlock>> storage;
+
+ public FeatureNodeHandler ()
+ {
+ blocks = new List <FeatureBlock> ();
+ }
+
+ public void ReadConfiguration (XPathNavigator nav)
+ {
+ name = Helpers.GetRequiredNonEmptyAttribute (nav, "name");
+ target = Helpers.ConvertTarget (Helpers.GetRequiredNonEmptyAttribute (nav, "target"));
+
+ XPathNodeIterator iter = nav.Select ("blocks/block[string-length (@name) > 0]");
+ while (iter.MoveNext ())
+ blocks.Add (new FeatureBlock (iter.Current, target));
+ }
+
+ public void StoreConfiguration ()
+ {
+ AssertStorage ();
+
+ List <FeatureBlock> blocksClone = new List <FeatureBlock> (blocks.Count);
+ blocksClone.AddRange (blocks);
+
+ if (storage.ContainsKey (name))
+ storage [name] = blocksClone; // allow for silent override
+ else
+ storage.Add (name, blocksClone);
+
+ blocks.Clear ();
+ }
+
+ public void SetStorage (object storage)
+ {
+ this.storage = storage as Dictionary <string, List <FeatureBlock>>;
+ if (this.storage == null)
+ throw new ApplicationException ("Invalid storage type");
+ }
+
+ public ICollection <string> Features {
+ get {
+ AssertStorage ();
+
+ if (storage.Count == 0)
+ return null;
+
+ List <string> ret = new List <string> (storage.Count);
+ List <FeatureBlock> lfb;
+
+ foreach (KeyValuePair <string, List <FeatureBlock>> kvp in storage) {
+ lfb = kvp.Value;
+ if (lfb.Count == 0)
+ continue;
+
+ ret.Add (String.Format ("{0} (Target: {1})", kvp.Key, lfb [0].Target));
+ }
+
+ return ret;
+ }
+ }
+
+ public bool HasFeature (string featureName)
+ {
+ AssertStorage ();
+
+ if (!storage.ContainsKey (featureName))
+ return false;
+
+ List <FeatureBlock> blocks = storage [featureName];
+ if (blocks == null || blocks.Count == 0)
+ return false;
+
+ return true;
+ }
+
+ public void AddFeature (string configFilePath, string featureName, FeatureTarget target,
+ IDefaultContainer[] defaults, IConfigBlockContainer[] configBlocks)
+ {
+ AssertStorage ();
+
+ if (!storage.ContainsKey (featureName))
+ throw new ApplicationException (String.Format ("Missing definition of feature '{0}'", featureName));
+
+ List <FeatureBlock> blocks = storage [featureName];
+ if (blocks == null || blocks.Count == 0)
+ throw new ApplicationException (String.Format ("Definition of feature '{0}' is empty", featureName));
+
+ XmlDocument doc = new XmlDocument ();
+
+ if (File.Exists (configFilePath))
+ doc.Load (configFilePath);
+
+ foreach (FeatureBlock block in blocks)
+ AddFeatureBlock (doc, block, target, defaults, configBlocks);
+
+ Helpers.SaveXml (doc, configFilePath);
+ }
+
+ void AddFeatureBlock (XmlDocument doc, FeatureBlock block, FeatureTarget target, IDefaultContainer[] defaults,
+ IConfigBlockContainer[] configBlocks)
+ {
+ if (target != FeatureTarget.Any && block.Target != target)
+ return;
+
+ ConfigBlockBlock configBlock = Helpers.FindConfigBlock (configBlocks, block.Name);
+ if (configBlock == null)
+ throw new ApplicationException (String.Format ("Config block '{0}' cannot be found", block.Name));
+
+ XmlNode attachPoint = null;
+
+ ProcessSections (doc, doc, "/", configBlock.Requires, defaults, configBlock.Name, ref attachPoint);
+ if (attachPoint == null)
+ attachPoint = FindDefaultAttachPoint (doc, configBlock.Requires);
+ if (attachPoint == null)
+ throw new ApplicationException (
+ String.Format ("Missing attachment point for block '{0}'", configBlock.Name));
+
+ XmlDocument contents = new XmlDocument ();
+ contents.LoadXml (String.Format ("<{0}>{1}</{0}>", Helpers.FakeRootName, configBlock.Contents));
+ AddFeatureRecursively (doc, attachPoint, contents.DocumentElement);
+ }
+
+ // TODO: handle comment and text nodes to avoid their duplication
+ void AddFeatureRecursively (XmlDocument doc, XmlNode attachPoint, XmlNode top)
+ {
+ bool topIsFake = top.Name == Helpers.FakeRootName;
+ XmlNode parent = null;
+ string xpath;
+
+ if (top.NodeType == XmlNodeType.Element) {
+ xpath = BuildFeaturePath (attachPoint, topIsFake ? null : top);
+ parent = DocumentHasFeatureFragment (doc, top, xpath);
+ }
+
+ if (!topIsFake && parent == null) {
+ parent = doc.ImportNode (top, false);
+ attachPoint.AppendChild (parent);
+ if (parent.NodeType == XmlNodeType.Comment)
+ return;
+ }
+
+ if (top.HasChildNodes)
+ foreach (XmlNode node in top.ChildNodes)
+ AddFeatureRecursively (doc, topIsFake ? attachPoint : parent, node);
+ }
+
+ XmlNode FindDefaultAttachPoint (XmlDocument doc, Section req)
+ {
+ List <Section> children = req.Children;
+ if (children == null || children.Count == 0)
+ return null;
+
+ StringBuilder sb = new StringBuilder ("/");
+ BuildPathToLastRequirement (sb, children);
+
+ return doc.SelectSingleNode (sb.ToString ());
+ }
+
+ void BuildPathToLastRequirement (StringBuilder sb, List <Section> sections)
+ {
+ Section last = sections [sections.Count - 1];
+ sb.AppendFormat ("/{0}", last.Name);
+
+ List <Section> children = last.Children;
+ if (children == null || children.Count == 0)
+ return;
+
+ BuildPathToLastRequirement (sb, children);
+ }
+
+ XmlNode DocumentHasFeatureFragment (XmlDocument doc, XmlNode top, string xpath)
+ {
+ if (top.NodeType == XmlNodeType.Comment)
+ return null;
+
+ return doc.SelectSingleNode (xpath);
+ }
+
+ string BuildFeaturePath (XmlNode parent, XmlNode child)
+ {
+ if (parent == null)
+ return "/";
+
+ List <string> path = new List <string> ();
+
+ XmlNode cur = parent, last = null;
+ while (cur != null && cur.NodeType != XmlNodeType.Document) {
+ if (cur.NodeType == XmlNodeType.Element && cur.Name != Helpers.FakeRootName)
+ path.Insert (0, cur.Name);
+ last = cur;
+ cur = cur.ParentNode;
+ }
+
+ string attributes = null;
+ if (child != null && last.Name != child.Name) {
+ if (child.NodeType == XmlNodeType.Element)
+ path.Add (child.Name);
+
+ attributes = BuildXPathFromAttributes (child);
+ } else if (last != null)
+ attributes = BuildXPathFromAttributes (last);
+
+ path [path.Count - 1] += attributes;
+ path.Insert (0, "/");
+
+ return String.Join ("/", path.ToArray ());
+ }
+
+ string BuildXPathFromAttributes (XmlNode node)
+ {
+ XmlAttributeCollection attrs = node.Attributes;
+ StringBuilder sb = new StringBuilder ();
+ string and = String.Empty;
+ bool first = true;
+
+ foreach (XmlAttribute attr in attrs) {
+ sb.AppendFormat ("{0}@{1}=\"{2}\"",
+ and,
+ attr.Name,
+ attr.Value);
+ if (first) {
+ first = false;
+ and = " and ";
+ }
+ }
+
+ if (sb.Length == 0)
+ return String.Empty;
+
+ sb.Insert (0, "[");
+ sb.Append ("]");
+
+ return sb.ToString ();
+ }
+
+ void ProcessSections (XmlDocument doc, XmlNode parent, string topPath, Section top, IDefaultContainer[] defaults,
+ string blockName, ref XmlNode attachPoint)
+ {
+ List <Section> topChildren, children;
+ if (top == null || (topChildren = top.Children) == null)
+ return;
+
+ XmlNode node;
+ string curPath;
+
+ foreach (Section s in topChildren) {
+ curPath = String.Format ("{0}/{1}", topPath, s.Name);
+
+ node = FindNodeOrAddDefault (doc, s.Name, curPath, defaults);
+ if (node != null && s.AttachPoint) {
+ if (attachPoint != null)
+ throw new ApplicationException (
+ String.Format ("Config block '{0}' has more than one attachment point",
+ blockName));
+ attachPoint = node;
+ }
+ parent.AppendChild (node);
+
+ if ((children = s.Children) != null && children.Count > 0)
+ ProcessSections (doc, node, curPath, s, defaults, blockName, ref attachPoint);
+ }
+
+ return;
+ }
+
+ XmlNode FindNodeOrAddDefault (XmlDocument doc, string nodeName, string nodePath, IDefaultContainer[] defaults)
+ {
+ XmlNode ret = doc.SelectSingleNode (nodePath);
+
+ if (ret != null)
+ return ret;
+
+ XmlDocument defDoc = Helpers.FindDefault (defaults, nodeName, FeatureTarget.Any);
+ if (defDoc == null)
+ throw new ApplicationException (
+ String.Format ("Document doesn't contain node '{0}' and no default can be found",
+ nodePath));
+
+ return doc.ImportNode (defDoc.DocumentElement.FirstChild, true);
+ }
+
+ void AssertStorage ()
+ {
+ if (storage == null)
+ throw new ApplicationException ("No storage attached");
+ }
+ }
+}
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace Mono.MonoConfig
+{
+ public enum FeatureTarget
+ {
+ Any,
+ Web,
+ Application
+ };
+}
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Text;
+using System.Xml;
+using System.Xml.XPath;
+
+namespace Mono.MonoConfig
+{
+ public static class Helpers
+ {
+ public const string FakeRootName = "F_a_K_e_R_o_O_t_M_o_N_o_C_o_N_f_I_g_N_o_D_e";
+
+ public static FeatureTarget ConvertTarget (string value)
+ {
+ try {
+ EnumConverter cvt = new EnumConverter (typeof (FeatureTarget));
+ return (FeatureTarget) cvt.ConvertFromInvariantString (value);
+ } catch (Exception) {
+ throw new ApplicationException (
+ String.Format ("Failed to parse the 'target' attribute '{0}'", value));
+ }
+ }
+
+ public static string GetRequiredNonEmptyAttribute (XPathNavigator node, string name)
+ {
+ string val = GetOptionalAttribute (node, name);
+
+ if (String.IsNullOrEmpty (val))
+ ThrowMissingRequiredAttribute (node, name);
+ return val;
+ }
+
+ public static string GetOptionalAttribute (XPathNavigator node, string name)
+ {
+ return node.GetAttribute (name, String.Empty);
+ }
+
+ static void ThrowMissingRequiredAttribute (XPathNavigator node, string name)
+ {
+ throw new ApplicationException (String.Format ("Element '{0}' is missing required attribute '{1}'",
+ node.LocalName, name));
+ }
+
+ public static void BuildSectionTree (XPathNodeIterator iter, Section section)
+ {
+ XPathNavigator nav, tmp;
+ XPathNodeIterator children;
+ List <Section> sectionChildren = section.Children;
+ Section newSection, curSection;
+
+ while (iter.MoveNext ()) {
+ nav = iter.Current;
+ children = nav.Select ("section[string-length(@name) > 0]");
+ curSection = new Section (nav);
+
+ while (children.MoveNext ()) {
+ tmp = children.Current;
+ newSection = new Section (tmp);
+ BuildSectionTree (tmp.Select ("section[string-length(@name) > 0]"), newSection);
+ curSection.Children.Add (newSection);
+ }
+ sectionChildren.Add (curSection);
+ }
+ }
+
+ public static XmlDocument FindDefault (IDefaultContainer[] defaults, string name, FeatureTarget target)
+ {
+ int len;
+
+ if (defaults == null || (len = defaults.Length) == 0)
+ return null;
+
+ IDefaultContainer cur;
+ string text = null;
+
+ for (int i = 0; i < len; i++) {
+ cur = defaults [i];
+ text = cur.FindDefault (name, target);
+ if (text != null)
+ break;
+ }
+
+ if (text == null)
+ return null;
+
+ XmlDocument ret = new XmlDocument ();
+ ret.LoadXml (String.Format ("<{0}>{1}</{0}>", FakeRootName, text));
+
+ return ret;
+ }
+
+ public static ConfigBlockBlock FindConfigBlock (IConfigBlockContainer[] configBlocks, string name)
+ {
+ int len;
+
+ if (configBlocks == null || (len = configBlocks.Length) == 0)
+ return null;
+
+ IConfigBlockContainer cur;
+ ConfigBlockBlock ret = null;
+
+ for (int i = 0; i < len; i++) {
+ cur = configBlocks [i];
+ ret = cur.FindConfigBlock (name);
+ if (ret != null)
+ break;
+ }
+
+ return ret;
+ }
+
+ public static void SaveXml (XmlDocument doc, string targetFile)
+ {
+ XmlWriterSettings settings = new XmlWriterSettings ();
+ settings.CloseOutput = true;
+ settings.CheckCharacters = true;
+ settings.Indent = true;
+ settings.Encoding = Encoding.UTF8;
+ settings.IndentChars = "\t";
+ settings.NewLineHandling = NewLineHandling.Replace;
+
+ XmlWriter writer = null;
+ try {
+ writer = XmlWriter.Create (targetFile, settings);
+ doc.Save (writer);
+ writer.Flush ();
+ } catch (Exception ex) {
+ throw new ApplicationException (
+ String.Format ("Failed to write XML file {1}", targetFile), ex);
+ } finally {
+ if (writer != null)
+ writer.Close ();
+ }
+ }
+ }
+}
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace Mono.MonoConfig
+{
+ public interface IConfigBlockContainer
+ {
+ ConfigBlockBlock FindConfigBlock (string name);
+ }
+}
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace Mono.MonoConfig
+{
+ public interface IDefaultConfigFileContainer
+ {
+ event OverwriteFileEventHandler OverwriteFile;
+
+ bool HasDefaultConfigFile (string name, FeatureTarget target);
+ void WriteDefaultConfigFile (string name, FeatureTarget target, string path, IDefaultContainer[] defaults);
+ ICollection <string> DefaultConfigFiles {
+ get;
+ }
+ }
+}
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace Mono.MonoConfig
+{
+ public interface IDefaultContainer
+ {
+ string FindDefault (string sectionName, FeatureTarget target);
+ }
+}
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.ComponentModel;
+using System.Collections.Generic;
+using System.Xml;
+using System.Xml.XPath;
+
+namespace Mono.MonoConfig
+{
+ public interface IDocumentNodeHandler
+ {
+ void ReadConfiguration (XPathNavigator nav);
+ void StoreConfiguration ();
+ }
+}
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace Mono.MonoConfig
+{
+ public interface IFeatureGenerator
+ {
+ bool HasFeature (string featureName);
+ void AddFeature (string configFilePath, string featureName, FeatureTarget target,
+ IDefaultContainer[] defaults, IConfigBlockContainer[] configBlocks);
+ ICollection <string> Features {
+ get;
+ }
+ }
+}
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace Mono.MonoConfig
+{
+ public interface IStorageConsumer
+ {
+ void SetStorage (object storage);
+ }
+}
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Xml;
+using System.Xml.XPath;
+
+namespace Mono.MonoConfig
+{
+ public class Section
+ {
+ List <Section> children;
+ string name;
+ bool attachPoint;
+
+ public string Name {
+ get { return name; }
+ }
+
+ public List <Section> Children {
+ get {
+ if (children == null)
+ children = new List <Section> ();
+ return children;
+ }
+ }
+
+ public bool AttachPoint {
+ get { return attachPoint; }
+ }
+
+ public Section () : this (null)
+ {
+ }
+
+ public Section (XPathNavigator nav)
+ {
+ if (nav != null) {
+ name = Helpers.GetRequiredNonEmptyAttribute (nav, "name");
+
+ string val = Helpers.GetOptionalAttribute (nav, "attachPoint");
+ if (!String.IsNullOrEmpty (val))
+ attachPoint = true;
+ }
+ }
+ }
+}
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.IO;
+
+namespace Mono.MonoConfig
+{
+ public class Constants
+ {
+ public static readonly string GlobalConfigPath;
+
+ static Constants ()
+ {
+ GlobalConfigPath = String.Format ("@MONO_PREFIX@{0}etc{0}mono{0}mconfig{0}config.xml",
+ Path.DirectorySeparatorChar);
+ }
+ }
+}
--- /dev/null
+- Comments should not be inserted if they exist
+- Add support for feature removal (only if the feature hasn't been edited yet)
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<mconfig>
+ <configuration>
+ <handlers>
+ <handler section="feature"
+ type="Mono.MonoConfig.FeatureNodeHandler, mconfig, Version=0.1.0.0, Culture=neutral, PublicKeyToken=null"
+ storageType="System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.List`1[[Mono.MonoConfig.FeatureBlock, mconfig, Version=0.1.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
+ <handler section="configBlock"
+ type="Mono.MonoConfig.ConfigBlockNodeHandler, mconfig, Version=0.1.0.0, Culture=neutral, PublicKeyToken=null"
+ storageType="System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[Mono.MonoConfig.ConfigBlockBlock, mconfig, Version=0.1.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
+ <handler section="default"
+ type="Mono.MonoConfig.DefaultNodeHandler, mconfig, Version=0.1.0.0, Culture=neutral, PublicKeyToken=null"
+ storageType="System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[Mono.MonoConfig.DefaultNode, mconfig, Version=0.1.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
+ <handler section="defaultConfigFile"
+ type="Mono.MonoConfig.DefaultConfigFileNodeHandler, mconfig, Version=0.1.0.0, Culture=neutral, PublicKeyToken=null"
+ storageType="System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[Mono.MonoConfig.DefaultConfigFile, mconfig, Version=0.1.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
+ </handlers>
+ </configuration>
+
+ <feature name="AJAX" target="web">
+ <blocks>
+ <block name="AJAX config sections"/>
+ <block name="AJAX controls registration"/>
+ <block name="AJAX compilation"/>
+ <block name="AJAX HTTP handlers"/>
+ <block name="AJAX HTTP modules"/>
+ <block name="AJAX system.web.extensions"/>
+ <block name="AJAX system.webServer"/>
+ <block name="" />
+ </blocks>
+ </feature>
+
+ <!-- configuration blocks required by the features -->
+ <configBlock name="AJAX config sections">
+ <requires>
+ <section name="configuration">
+ <section name="configSections" attachPoint="true"/>
+ </section>
+ </requires>
+
+ <contents>
+ <![CDATA[
+<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
+ <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
+ <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
+ <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
+ <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere" />
+ <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" />
+ <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" />
+ </sectionGroup>
+ </sectionGroup>
+ </sectionGroup>
+ ]]>
+ </contents>
+ </configBlock>
+
+ <configBlock name="AJAX controls registration">
+ <requires>
+ <section name="configuration">
+ <section name="system.web">
+ <section name="pages">
+ <section name="controls"/>
+ </section>
+ </section>
+ </section>
+ </requires>
+
+ <contents>
+ <![CDATA[
+<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+]]>
+ </contents>
+ </configBlock>
+
+ <configBlock name="AJAX compilation">
+ <requires>
+ <section name="configuration">
+ <section name="system.web">
+ <section name="compilation">
+ <section name="assemblies"/>
+ </section>
+ </section>
+ </section>
+ </requires>
+
+ <contents>
+ <![CDATA[
+<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+]]>
+ </contents>
+ </configBlock>
+
+ <configBlock name="AJAX HTTP handlers">
+ <requires>
+ <section name="configuration">
+ <section name="system.web">
+ <section name="httpHandlers"/>
+ </section>
+ </section>
+ </requires>
+
+ <contents>
+ <![CDATA[
+<remove verb="*" path="*.asmx"/>
+ <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+ <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+ <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
+]]>
+ </contents>
+ </configBlock>
+
+ <configBlock name="AJAX HTTP modules">
+ <requires>
+ <section name="configuration">
+ <section name="system.web">
+ <section name="httpModules"/>
+ </section>
+ </section>
+ </requires>
+
+ <contents>
+ <![CDATA[
+<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+]]>
+ </contents>
+ </configBlock>
+
+ <configBlock name="AJAX system.web.extensions">
+ <requires>
+ <section name="configuration">
+ <section name="system.web.extensions"/>
+ </section>
+ </requires>
+
+ <contents>
+ <![CDATA[
+<scripting>
+ <webServices>
+ <!-- Uncomment this line to customize maxJsonLength and add a custom converter -->
+ <!--
+ <jsonSerialization maxJsonLength="500">
+ <converters>
+ <add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>
+ </converters>
+ </jsonSerialization>
+ -->
+ <!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. -->
+ <!--
+ <authenticationService enabled="true" requireSSL = "true|false"/>
+ -->
+
+ <!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved
+ and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and
+ writeAccessProperties attributes. -->
+ <!--
+ <profileService enabled="true"
+ readAccessProperties="propertyname1,propertyname2"
+ writeAccessProperties="propertyname1,propertyname2" />
+ -->
+ </webServices>
+ <!--
+ <scriptResourceHandler enableCompression="true" enableCaching="true" />
+ -->
+ </scripting>
+]]>
+ </contents>
+ </configBlock>
+
+ <configBlock name="AJAX system.webServer">
+ <requires>
+ <section name="configuration">
+ <section name="system.webServer"/>
+ </section>
+ </requires>
+
+ <contents>
+ <![CDATA[
+<validation validateIntegratedModeConfiguration="false"/>
+ <modules>
+ <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+ </modules>
+ <handlers>
+ <remove name="WebServiceHandlerFactory-Integrated" />
+ <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode"
+ type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+ <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode"
+ type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
+ <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
+ </handlers>
+]]>
+ </contents>
+ </configBlock>
+
+ <!-- default contents for missing sections -->
+ <default section="configuration" target="any">
+ <![CDATA[
+ <configuration>
+ </configuration>
+ ]]>
+ </default>
+
+ <default section="configSections" target="any">
+ <![CDATA[
+ <configSections>
+ </configSections>
+ ]]>
+ </default>
+
+ <default section="system.web" target="web">
+ <![CDATA[
+ <system.web>
+ </system.web>
+ ]]>
+ </default>
+
+ <default section="pages" target="web">
+ <![CDATA[
+<pages>
+</pages>
+]]>
+ </default>
+
+ <default section="controls" target="web">
+ <![CDATA[
+<controls>
+</controls>
+]]>
+ </default>
+
+ <default section="compilation" target="web">
+ <![CDATA[
+<compilation debug="true">
+</compilation>
+]]>
+ </default>
+
+ <default section="assemblies" target="web">
+ <![CDATA[
+<assemblies>
+</assemblies>
+]]>
+ </default>
+
+ <default section="httpHandlers" target="web">
+ <![CDATA[
+<httpHandlers>
+</httpHandlers>
+]]>
+ </default>
+
+ <default section="httpModules" target="web">
+ <![CDATA[
+<httpModules>
+</httpModules>
+]]>
+ </default>
+
+ <default section="system.web.extensions" target="web">
+ <![CDATA[
+<system.web.extensions>
+</system.web.extensions>
+]]>
+ </default>
+
+ <default section="system.webServer" target="web">
+ <![CDATA[
+<system.webServer>
+</system.webServer>
+]]>
+ </default>
+
+ <default section="customErrors" target="web">
+ <![CDATA[
+<customErrors mode="RemoteOnly"/>
+]]>
+ </default>
+
+ <!-- default config file definitions -->
+ <defaultConfigFile name="web.config" fileName="Web.config" target="web">
+ <section name="configuration">
+ <section name="system.web">
+ <section name="compilation"/>
+ <section name="customErrors"/>
+ </section>
+ </section>
+ </defaultConfigFile>
+</mconfig>
--- /dev/null
+//
+// Authors:
+// Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2007 Novell, Inc
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Reflection;
+
+namespace Mono.MonoConfig
+{
+ delegate int HandleCommand (MConfigOptions options, Configuration config);
+
+ struct CommandHandler {
+ public readonly HandleCommand Handler;
+ public readonly string[] Names;
+
+ public CommandHandler (string[] names, HandleCommand handler)
+ {
+ this.Names = names;
+ this.Handler = handler;
+ }
+ };
+
+ class MConfigOptions
+ {
+ string[] usage = {
+ "Usage: mconfig [options] command [command_parameters]",
+ "Options:",
+ "",
+ " -?,-h,--help Display this usage information",
+ " -v,--version Display version information",
+ " -c,--config=<filepath> Read the specified config file in addition to",
+ " the standard ones. Settings in this file override ones",
+ " in the other files.",
+ " -t,--target={any,web,application} Use this target when executing 'command'",
+ " -C,--list-configs List all the default config file names defined in the",
+ " configuration files.",
+ " -F,--list-features List all the features defined in the configuration files.",
+ "",
+ "Commands:",
+ " {addfeature,af} <feature_name> [config_file_path]",
+ " {defconfig,dc} [config_name] [target_directory]"
+ };
+
+ public delegate void ListDefaultConfigsHandler ();
+ public delegate void ListFeaturesHandler ();
+
+ public event ListDefaultConfigsHandler OnListDefaultConfigs;
+ public event ListFeaturesHandler OnListFeatures;
+
+ List <string> plain_arguments;
+ Dictionary <string, string> unknown_arguments;
+
+ public string ConfigFile;
+ public FeatureTarget Target = FeatureTarget.Any;
+ public bool ListDefaultConfigs;
+ public bool ListFeatures;
+
+ public Dictionary <string, string> UnknownArguments {
+ get {
+ if (unknown_arguments == null || unknown_arguments.Count == 0)
+ return null;
+
+ return unknown_arguments;
+ }
+ }
+
+ public string[] PlainArguments {
+ get {
+ if (plain_arguments == null || plain_arguments.Count == 0)
+ return null;
+
+ return plain_arguments.ToArray ();
+ }
+ }
+
+ public MConfigOptions ()
+ {
+ unknown_arguments = new Dictionary <string, string> ();
+ plain_arguments = new List <string> ();
+ }
+
+ public void Parse (string[] args)
+ {
+ if (args == null || args.Length == 0)
+ Usage ();
+
+ int len = args.Length;
+ string arg;
+
+ for (int i = 0; i < len; i++) {
+ arg = args [i];
+
+ switch (arg [0]) {
+ case '-':
+ case '/':
+ i += ProcessArgument (i, arg, args, len);
+ break;
+
+ default:
+ plain_arguments.Add (arg);
+ break;
+ }
+ }
+ }
+
+ static char[] paramStartChars = {':', '='};
+
+ int ProcessArgument (int idx, string argument, string[] args, int argsLen)
+ {
+ int argnameIdx = 1;
+ bool haveMoreDashes = false, badArg = false;
+ int argumentLen = argument.Length;
+
+ if (argumentLen < 2)
+ badArg = true;
+
+ haveMoreDashes = !badArg && (argument [1] == '-');
+
+ if (argumentLen == 2 && haveMoreDashes)
+ badArg = true;
+
+ if (badArg) {
+ Console.Error.WriteLine ("Invalid argument: {0}", argument);
+ Environment.Exit (1);
+ }
+
+ if (haveMoreDashes)
+ argnameIdx++;
+
+ int paramPos = argument.IndexOfAny (paramStartChars, argnameIdx);
+ bool haveParam = true;
+
+ if (paramPos == -1) {
+ haveParam = false;
+ paramPos = argumentLen;
+ }
+
+ string argName = argument.Substring (argnameIdx, paramPos - argnameIdx);
+ string argParam = haveParam ? argument.Substring (paramPos + 1) : null;
+
+ int ret = 0;
+
+ if (!haveParam && haveMoreDashes) {
+ idx++;
+ if (idx < argsLen) {
+ argParam = args [idx];
+ ret++;
+ haveParam = true;
+ }
+ }
+
+ switch (argName) {
+ case "?":
+ case "h":
+ case "help":
+ Usage ();
+ break;
+
+ case "v":
+ case "version":
+ ShowVersion ();
+ break;
+
+ case "t":
+ case "target":
+ if (!haveParam)
+ RequiredParameterMissing (argName);
+
+ try {
+ Target = Helpers.ConvertTarget (argParam);
+ } catch (Exception ex) {
+ OptionParameterError (argName, ex.Message);
+ }
+ break;
+
+ case "C":
+ case "list-configs":
+ ListDefaultConfigs = true;
+ break;
+
+ case "F":
+ case "list-features":
+ ListFeatures = true;
+ break;
+
+ default:
+ unknown_arguments.Add (argName, argParam);
+ break;
+ }
+
+ return ret;
+ }
+
+ void RequiredParameterMissing (string argName)
+ {
+ Console.Error.WriteLine ("Argument '{0}' requires a parameter", argName);
+ Environment.Exit (1);
+ }
+
+ void OptionParameterError (string argName, string message)
+ {
+ Console.Error.WriteLine ("Parameter value is invalid for argument '{0}'.",
+ argName);
+ Console.Error.WriteLine (message);
+ Environment.Exit (1);
+ }
+
+ public void Usage ()
+ {
+ foreach (string line in usage)
+ Console.WriteLine (line);
+ Environment.Exit (1);
+ }
+
+ void ShowVersion ()
+ {
+ Assembly asm = Assembly.GetExecutingAssembly () ?? Assembly.GetCallingAssembly ();
+ object[] attrs = asm != null ? asm.GetCustomAttributes (false) : null;
+ string product = "mconfig", version = "0.0.0.0", copyright = "", description = "";
+
+ if (asm != null) {
+ Version v = asm.GetName ().Version;
+ if (v != null)
+ version = v.ToString ();
+ }
+
+ if (attrs != null) {
+ foreach (object o in attrs) {
+ if (o is AssemblyProductAttribute)
+ product = ((AssemblyProductAttribute)o).Product;
+ else if (o is AssemblyCopyrightAttribute)
+ copyright = ((AssemblyCopyrightAttribute)o).Copyright;
+ else if (o is AssemblyDescriptionAttribute)
+ description = ((AssemblyDescriptionAttribute)o).Description;
+ }
+ } else
+ Console.WriteLine ("Missing version information");
+
+ Console.WriteLine ("{0} - {1} {2}", product, description, version);
+ Console.WriteLine (copyright);
+
+ Environment.Exit (1);
+ }
+ }
+
+ class MConfig
+ {
+ static string[] configPaths = {
+ Constants.GlobalConfigPath,
+ Path.Combine (ConfigPath, "config.xml"),
+ Path.Combine (".", "mconfig.xml"),
+ null
+ };
+
+ static CommandHandler[] commands = {
+ new CommandHandler (new string[] {"addfeature", "af"}, HandleAddFeature),
+ new CommandHandler (new string[] {"defconfig", "dc"}, HandleDefaultConfig)
+ };
+
+ static string ConfigPath {
+ get {
+ string configPath = Environment.GetEnvironmentVariable ("XDG_CONFIG_HOME");
+ if (String.IsNullOrEmpty (configPath))
+ configPath = Path.Combine (Environment.GetEnvironmentVariable ("HOME"), ".config");
+ return Path.Combine (configPath, "mconfig");
+ }
+ }
+
+ static HandleCommand FindCommandHandler (string command)
+ {
+ foreach (CommandHandler ch in commands) {
+ foreach (string name in ch.Names)
+ if (name == command)
+ return ch.Handler;
+ }
+
+ return null;
+ }
+
+ static void DisplayList (string banner, string[] list)
+ {
+ Console.WriteLine (banner);
+ if (list == null || list.Length == 0) {
+ Console.WriteLine ("No data found");
+ return;
+ }
+
+ foreach (string item in list)
+ Console.WriteLine (" {0}", item);
+ }
+
+ static int Main (string[] args)
+ {
+ MConfigOptions options = new MConfigOptions ();
+ options.Parse (args);
+
+ if (!String.IsNullOrEmpty (options.ConfigFile))
+ configPaths [3] = options.ConfigFile;
+
+ Configuration config = new Configuration ();
+ config.Load (configPaths);
+
+ bool doQuit = false;
+ if (options.ListDefaultConfigs) {
+ DisplayList ("Default config files", config.DefaultConfigFiles);
+ doQuit = true;
+ }
+
+ if (options.ListFeatures) {
+ DisplayList ("Available features", config.Features);
+ doQuit = true;
+ }
+
+ if (doQuit)
+ return 0;
+
+ string[] commandArguments = options.PlainArguments;
+ if (commandArguments == null || commandArguments.Length == 0) {
+ options.Usage ();
+ return 1;
+ }
+
+ HandleCommand commandHandler = FindCommandHandler (commandArguments [0]);
+ if (commandHandler == null) {
+ Console.Error.WriteLine ("Unknown command '{0}'", commandArguments [0]);
+ return 1;
+ }
+
+ IDefaultConfigFileContainer[] containers = config.GetHandlersForInterface <IDefaultConfigFileContainer> ();
+ if (containers != null && containers.Length > 0)
+ foreach (IDefaultConfigFileContainer c in containers)
+ c.OverwriteFile += new OverwriteFileEventHandler (OnOverwriteFile);
+
+ return commandHandler (options, config);
+ }
+
+ static void OnOverwriteFile (object sender, OverwriteFileEventArgs e)
+ {
+ Console.Write ("Do you want to overwrite existing file '{0}'? [{1}] ",
+ e.Name, e.Overwrite ? "Y/n" : "y/N");
+ ConsoleKeyInfo cki = Console.ReadKey (false);
+ switch (cki.Key) {
+ case ConsoleKey.N:
+ e.Overwrite = false;
+ break;
+
+ case ConsoleKey.Y:
+ e.Overwrite = true;
+ break;
+ }
+ Console.WriteLine ();
+ }
+
+ static int HandleAddFeature (MConfigOptions options, Configuration config)
+ {
+ string[] commandArguments = options.PlainArguments;
+ if (commandArguments.Length < 2) {
+ Console.Error.WriteLine ("Command requires at least one argument.");
+ return 1;
+ }
+
+ FeatureTarget target = options.Target;
+ string featureName = commandArguments [1], configPath;
+ if (commandArguments.Length > 2)
+ configPath = commandArguments [2];
+ else {
+ switch (target) {
+ case FeatureTarget.Any:
+ Console.Error.WriteLine ("No default config file for target 'Any'");
+ return 1;
+
+ case FeatureTarget.Web:
+ configPath = "Web.config";
+ break;
+
+ case FeatureTarget.Application:
+ configPath = "application.exe.config";
+ break;
+
+ default:
+ Console.Error.WriteLine ("Unknown target '{0}'", target);
+ return 1;
+ }
+ }
+
+ try {
+ config.AddFeature (configPath, target, featureName);
+ } catch (Exception ex) {
+ Console.Error.WriteLine ("Failed to add feature '{0}' to config file '{1}'.\n{2}",
+ featureName, configPath, ex.Message);
+ return 1;
+ }
+
+ return 0;
+ }
+
+ static int HandleDefaultConfig (MConfigOptions options, Configuration config)
+ {
+ FeatureTarget target = options.Target;
+ string[] commandArguments = options.PlainArguments;
+ string configName, targetPath;
+
+ if (commandArguments.Length < 2) {
+ switch (target) {
+ case FeatureTarget.Any:
+ Console.Error.WriteLine ("No default config file for target 'Any'");
+ return 1;
+
+ case FeatureTarget.Web:
+ configName = "Web.config";
+ break;
+
+ case FeatureTarget.Application:
+ configName = "application.exe.config";
+ break;
+
+ default:
+ Console.Error.WriteLine ("Unknown target '{0}'", target);
+ return 1;
+ }
+ } else
+ configName = commandArguments [1];
+
+ if (commandArguments.Length < 3)
+ targetPath = ".";
+ else
+ targetPath = commandArguments [2];
+
+ try {
+ config.WriteDefaultConfigFile (configName, targetPath, target);
+ } catch (Exception ex) {
+ Console.Error.WriteLine ("Failed to write default config file '{0}':\n{1}",
+ configName, ex.Message);
+ return 1;
+ }
+
+ return 0;
+ }
+ }
+}
--- /dev/null
+mconfig.cs
+Mono.MonoConfig/Assembly/AssemblyInfo.cs
+Mono.MonoConfig/ConfigBlockBlock.cs
+Mono.MonoConfig/ConfigBlockNodeHandler.cs
+Mono.MonoConfig/Configuration.cs
+Mono.MonoConfig/DefaultConfigFileNodeHandler.cs
+Mono.MonoConfig/DefaultNodeHandler.cs
+Mono.MonoConfig/FeatureBlock.cs
+Mono.MonoConfig/FeatureNodeHandler.cs
+Mono.MonoConfig/FeatureTarget.cs
+Mono.MonoConfig/Helpers.cs
+Mono.MonoConfig/IConfigBlockContainer.cs
+Mono.MonoConfig/IDefaultConfigFileContainer.cs
+Mono.MonoConfig/IDefaultContainer.cs
+Mono.MonoConfig/IDocumentNodeHandler.cs
+Mono.MonoConfig/IFeatureGenerator.cs
+Mono.MonoConfig/IStorageConsumer.cs
+Mono.MonoConfig/Section.cs
+2007-10-19 Robert Jordan <robertj@gmx.net>
+
+ * mkbundle.cs (Execute): [Windows] since recently (?) cygwin's bash
+ doesn't strip CRLFs from ``-style command interpolation anymore.
+ The superfluous CRLF was breaking the gcc command line.
+
+ * mkbundle.cs (Execute): [Windows] set UseShellExecute = false to
+ prevent the creation of a new console windows.
+
2007-01-03 Tor Lillqvist <tml@novell.com>
Add the possibility to bundle also the machine.config file, from
using System.Reflection;
using System.IO;
using System.Runtime.InteropServices;
+using System.Text;
using Mono.Unix;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
static int Execute (string cmdLine)
{
- Console.WriteLine (cmdLine);
if (IsUnix) {
+ Console.WriteLine (cmdLine);
return system (cmdLine);
- } else {
- Process p = Process.Start ("sh", String.Format ("-c \"{0}\"", cmdLine));
+ }
+
+ // on Windows, we have to pipe the output of a
+ // `cmd` interpolation to dos2unix, because the shell does not
+ // strip the CRLFs generated by the native pkg-config distributed
+ // with Mono.
+ StringBuilder b = new StringBuilder ();
+ int count = 0;
+ for (int i = 0; i < cmdLine.Length; i++) {
+ if (cmdLine [i] == '`') {
+ if (count % 2 != 0) {
+ b.Append ("|dos2unix");
+ }
+ count++;
+ }
+ b.Append (cmdLine [i]);
+ }
+ cmdLine = b.ToString ();
+ Console.WriteLine (cmdLine);
+
+ ProcessStartInfo psi = new ProcessStartInfo ();
+ psi.UseShellExecute = false;
+ psi.FileName = "sh";
+ psi.Arguments = String.Format ("-c \"{0}\"", cmdLine);
+
+ using (Process p = Process.Start (psi)) {
p.WaitForExit ();
return p.ExitCode;
}
+2007-10-17 Sebastien Pouliot <sebastien@ximian.com>
+
+ * sn.cs: Fix help for -T / -t as this shows the public key token
+ (and not the public key). Patch by Andy Hume. Fix bug #334507
+
2007-07-31 Sebastien Pouliot <sebastien@ximian.com>
* AssemblyInfo.cs: Update copyright notices.
Console.WriteLine (" -k keypair.snk{0}\tCreate a new keypair in the specified file", Environment.NewLine);
Console.WriteLine (" -R assembly keypair.snk{0}\tResign the assembly with the specified StrongName key file", Environment.NewLine);
Console.WriteLine (" -Rc assembly container{0}\tResign the assembly with the specified CSP container", Environment.NewLine);
- Console.WriteLine (" -t file{0}\tShow the public key from the specified file", Environment.NewLine);
+ Console.WriteLine (" -t file{0}\tShow the public key token from the specified file", Environment.NewLine);
Console.WriteLine (" -tp file{0}\tShow the public key and pk token from the specified file", Environment.NewLine);
- Console.WriteLine (" -T assembly{0}\tShow the public key from the specified assembly", Environment.NewLine);
+ Console.WriteLine (" -T assembly{0}\tShow the public key token from the specified assembly", Environment.NewLine);
Console.WriteLine (" -Tp assembly{0}\tShow the public key and pk token from the specified assembly", Environment.NewLine);
Console.WriteLine (" -v assembly{0}\tVerify the specified assembly signature", Environment.NewLine);
Console.WriteLine (" -vf assembly{0}\tVerify the specified assembly signature (even if disabled).", Environment.NewLine);
+2007-10-18 Zoltan Varga <vargaz@gmail.com>
+
+ * atomic.h (InterlockedCompareExchange): Fix the ia64 version so it works for
+ negative values too. Hopefully fixes #332700.
+
2007-09-26 Dick Porter <dick@ximian.com>
* io-portability.c (_wapi_io_scandir): Only update the error
gint32 exch, gint32 comp)
{
gint32 old;
+ guint64 real_comp;
#ifdef __INTEL_COMPILER
old = _InterlockedCompareExchange (dest, exch, comp);
#else
+ /* cmpxchg4 zero extends the value read from memory */
+ real_comp = (guint64)(guint32)comp;
asm volatile ("mov ar.ccv = %2 ;;\n\t"
"cmpxchg4.acq %0 = [%1], %3, ar.ccv\n\t"
- : "=r" (old) : "r" (dest), "r" (comp), "r" (exch));
+ : "=r" (old) : "r" (dest), "r" (real_comp), "r" (exch));
#endif
return(old);
+2007-10-21 Zoltan Varga <vargaz@gmail.com>
+
+ * class.c (mono_generic_class_get_class): Avoid setting klass->size_inited and
+ related fields for dynamic classes. Fixes #334493.
+
+2007-10-20 Zoltan Varga <vargaz@gmail.com>
+
+ * class.c (mono_generic_class_get_class): Set klass->field.count as well.
+
+ * class.c (mono_class_layout_fields): Use 1 instead of TRUE for consistency.
+
+ * class.c (mono_class_layout_fields): Set size_inited for generic classes as well.
+ (mono_class_setup_vtable): Obtain overrides for dynamic generic classes correctly.
+
+ * class.c (mono_class_setup_methods): Handle dynamic inflated classes correctly.
+
+ * reflection.c (create_generic_typespec): Initialize klass->generic_container
+ if needed.
+ (reflection_methodbuilder_to_mono_method): Set container->is_method to TRUE.
+
+2007-10-18 Jonathan Chambers <joncham@gmail.com>
+
+ * marshal.c: Use correct key when removing item
+ from ccw_hash.
+
+ Code is contributed under MIT/X11 license.
+
+2007-10-17 William Holmes <billholmes54@gmail.com>
+
+ *marshal.c: Adding a case to marshal booleans to U1
+
+ Code is contributed under MIT/X11 license.
+
+2007-10-18 Zoltan Varga <vargaz@gmail.com>
+
+ * class.c (mono_class_from_name): Search the modules compromising dynamic
+ assemblies. Fixes #331601.
+
+2007-10-16 Zoltan Varga <vargaz@gmail.com>
+
+ * icall.c (ves_icall_System_Reflection_Assembly_InternalGetType): Throw an
+ exception if the type name contains an assembly component. Fixes #334203.
+
+ * reflection.c (mono_reflection_get_type_with_rootimage): Search all the
+ modules inside dynamic assemblies. Fixes #334200.
+
+ * reflection.c: Set image->public_key and image->public_key_length;
+
+ * metadata-internals.h (MonoDynamicImage): Add public_key and public_key_len
+ fields.
+
+ * image.c (mono_image_get_public_key): Handle dynamic assemblies. Fixes #334173.
+
+2007-10-16 Mark Probst <mark.probst@gmail.com>
+
+ * metadata.c: Implemented correct comparing of generic classes.
+ An inflated generic class can be equal to a non-inflated one if it
+ is inflated with generic type variables as type arguments. Fixes
+ bug #333798.
+
+2007-10-15 Dick Porter <dick@ximian.com>
+
+ * monitor.c (mono_monitor_try_enter_internal): Set thread state to
+ WaitSleepJoin while it is waiting to acquire a lock. Fixes bug
+ 81646.
+
+ * threads.c: Turn the thread synch_lock into a CRITICAL_SECTION,
+ instead of a monitor lock. This means that monitor_try_enter and
+ co can set the thread state safely.
+ (ves_icall_System_Threading_Thread_Interrupt_internal): Always set
+ thread_interrupt_requested, so interrupt actually works.
+
+ * socket-io.c (ves_icall_System_Net_Sockets_Socket_Poll_internal,
+ ves_icall_System_Net_Sockets_Socket_Select_internal): Use thread
+ state accessor function
+
+2007-10-15 Martin Baulig <martin@ximian.com>
+
+ * mono-debug.h
+ (MONO_DEBUGGER_VERSION): Bump to 63 to make it impossible to use
+ the debugger with the current runtime.
+
+Mon Oct 15 10:20:56 CEST 2007 Paolo Molaro <lupus@ximian.com>
+
+ * object.c, object-internals.h: added the ability to set a single
+ trampoline for all the slots in a vtable.
Fri Oct 12 17:50:11 CEST 2007 Paolo Molaro <lupus@ximian.com>
MonoClassField *field;
if (class->generic_container ||
- (class->generic_class && class->generic_class->context.class_inst->is_open))
+ (class->generic_class && class->generic_class->context.class_inst->is_open)) {
+ class->size_inited = 1;
return;
+ }
/*
* Enable GC aware auto layout: in this mode, reference
return;
}
- if (class->generic_class && !class->generic_class->is_dynamic) {
+ if (class->generic_class) {
MonoClass *gklass = class->generic_class->container_class;
mono_class_init (gklass);
mono_class_setup_methods (gklass);
/* The + 1 makes this always non-NULL to pass the check in mono_class_setup_methods () */
+ class->method.count = gklass->method.count;
methods = g_new0 (MonoMethod *, class->method.count + 1);
for (i = 0; i < class->method.count; i++) {
{
MonoMethod **overrides;
MonoGenericContext *context;
+ MonoClass *overrides_class;
guint32 type_token;
int onum = 0;
gboolean ok = TRUE;
if (class->generic_class) {
context = mono_class_get_context (class);
type_token = class->generic_class->container_class->type_token;
+ overrides_class = class->generic_class->container_class;
} else {
context = (MonoGenericContext *) class->generic_container;
type_token = class->type_token;
+ overrides_class = class;
}
if (class->image->dynamic)
- mono_reflection_get_dynamic_overrides (class, &overrides, &onum);
+ mono_reflection_get_dynamic_overrides (overrides_class, &overrides, &onum);
else {
/* The following call fails if there are missing methods in the type */
ok = mono_class_get_overrides_full (class->image, type_token, &overrides, &onum, context);
klass->image = gklass->image;
klass->flags = gklass->flags;
klass->type_token = gklass->type_token;
+ klass->field.count = gklass->field.count;
klass->generic_class = gclass;
klass->this_arg.type = klass->byval_arg.type = MONO_TYPE_GENERICINST;
klass->this_arg.data.generic_class = klass->byval_arg.data.generic_class = gclass;
klass->this_arg.byref = TRUE;
+ klass->enumtype = gklass->enumtype;
+ klass->valuetype = gklass->valuetype;
klass->cast_class = klass->element_class = klass;
klass->cast_class = klass->element_class = mono_class_get_nullable_param (klass);
if (gclass->is_dynamic) {
- klass->instance_size = gklass->instance_size;
- klass->sizes.class_size = gklass->sizes.class_size;
- klass->size_inited = 1;
klass->inited = 1;
- klass->valuetype = gklass->valuetype;
-
mono_class_setup_supertypes (klass);
+
+ if (klass->enumtype) {
+ /*
+ * For enums, gklass->fields might not been set, but instance_size etc. is
+ * already set in mono_reflection_create_internal_class (). For non-enums,
+ * these will be computed normally in mono_class_layout_fields ().
+ */
+ klass->instance_size = gklass->instance_size;
+ klass->sizes.class_size = gklass->sizes.class_size;
+ klass->size_inited = 1;
+ }
}
klass->interface_count = gklass->interface_count;
GHashTable *nspace_table;
MonoImage *loaded_image;
guint32 token = 0;
+ int i;
MonoClass *class;
char *nested;
char buf [1024];
mono_loader_unlock ();
+ if (!token && image->dynamic && image->modules) {
+ /* Search modules as well */
+ for (i = 0; i < image->module_count; ++i) {
+ MonoImage *module = image->modules [i];
+
+ class = mono_class_from_name (module, name_space, name);
+ if (class)
+ return class;
+ }
+ }
+
if (!token)
return NULL;
ICALL(THREAD_54, "SpinWait_internal", ves_icall_System_Threading_Thread_SpinWait_internal)
ICALL(THREAD_23, "Suspend_internal", ves_icall_System_Threading_Thread_Suspend)
ICALL(THREAD_24, "Thread_free_internal", ves_icall_System_Threading_Thread_Thread_free_internal)
+ICALL(THREAD_24a, "Thread_init", ves_icall_System_Threading_Thread_Thread_init)
ICALL(THREAD_25, "Thread_internal", ves_icall_System_Threading_Thread_Thread_internal)
ICALL(THREAD_26, "VolatileRead(byte&)", ves_icall_System_Threading_Thread_VolatileRead1)
ICALL(THREAD_27, "VolatileRead(double&)", ves_icall_System_Threading_Thread_VolatileRead8)
return NULL;
}
+ if (info.assembly.name) {
+ if (throwOnError) {
+ /* 1.0 and 2.0 throw different exceptions */
+ if (mono_defaults.generic_ilist_class)
+ mono_raise_exception (mono_get_exception_argument (NULL, "Type names passed to Assembly.GetType() must not specify an assembly."));
+ else
+ mono_raise_exception (mono_get_exception_type_load (name, NULL));
+ }
+ return NULL;
+ }
+
if (module != NULL) {
if (module->image)
type = mono_reflection_get_type (module->image, &info, ignoreCase, &type_resolve);
{
const char *pubkey;
guint32 len, tok;
+
+ if (image->dynamic) {
+ if (size)
+ *size = ((MonoDynamicImage*)image)->public_key_len;
+ return ((MonoDynamicImage*)image)->public_key;
+ }
if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
return NULL;
tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
} else {
switch (spec->native) {
case MONO_NATIVE_I1:
+ case MONO_NATIVE_U1:
local_type = &mono_defaults.byte_class->byval_arg;
break;
case MONO_NATIVE_VARIANTBOOL:
/* if list is empty remove original address from hash */
if (g_list_length (ccw_list) == 0)
- g_hash_table_remove (ccw_hash, ccw_list_orig);
+ g_hash_table_remove (ccw_hash, GINT_TO_POINTER (mono_object_hash (object)));
return TRUE;
guint32 strong_name_size;
char *win32_res;
guint32 win32_res_size;
+ guint8 *public_key;
+ int public_key_len;
MonoDynamicStream sheap;
MonoDynamicStream code; /* used to store method headers and bytecode */
MonoDynamicStream resources; /* managed embedded resources */
}
static gboolean
-mono_generic_inst_equal (gconstpointer ka, gconstpointer kb)
+mono_generic_inst_equal_full (const MonoGenericInst *a, const MonoGenericInst *b, gboolean signature_only)
{
- const MonoGenericInst *a = (const MonoGenericInst *) ka;
- const MonoGenericInst *b = (const MonoGenericInst *) kb;
int i;
if (a->is_open != b->is_open || a->type_argc != b->type_argc)
return FALSE;
for (i = 0; i < a->type_argc; ++i) {
- if (!do_mono_metadata_type_equal (a->type_argv [i], b->type_argv [i], FALSE))
+ if (!do_mono_metadata_type_equal (a->type_argv [i], b->type_argv [i], signature_only))
return FALSE;
}
return TRUE;
}
+static gboolean
+mono_generic_inst_equal (gconstpointer ka, gconstpointer kb)
+{
+ const MonoGenericInst *a = (const MonoGenericInst *) ka;
+ const MonoGenericInst *b = (const MonoGenericInst *) kb;
+
+ return mono_generic_inst_equal_full (a, b, FALSE);
+}
+
static guint
mono_generic_class_hash (gconstpointer data)
{
static gboolean
_mono_metadata_generic_class_equal (const MonoGenericClass *g1, const MonoGenericClass *g2, gboolean signature_only)
{
- int i;
MonoGenericInst *i1 = g1->context.class_inst;
MonoGenericInst *i2 = g2->context.class_inst;
- if (i1->type_argc != i2->type_argc || g1->is_dynamic != g2->is_dynamic)
+ if (g1->is_dynamic != g2->is_dynamic)
return FALSE;
if (!mono_metadata_class_equal (g1->container_class, g2->container_class, signature_only))
return FALSE;
- for (i = 0; i < i1->type_argc; ++i) {
- if (!do_mono_metadata_type_equal (i1->type_argv [i], i2->type_argv [i], signature_only))
- return FALSE;
- }
+ if (!mono_generic_inst_equal_full (i1, i2, signature_only))
+ return FALSE;
return g1->is_tb_open == g2->is_tb_open;
}
+static gboolean
+_mono_metadata_generic_class_container_equal (const MonoGenericClass *g1, MonoClass *c2, gboolean signature_only)
+{
+ MonoGenericInst *i1 = g1->context.class_inst;
+ MonoGenericInst *i2 = c2->generic_container->context.class_inst;
+
+ if (!mono_metadata_class_equal (g1->container_class, c2, signature_only))
+ return FALSE;
+ if (!mono_generic_inst_equal_full (i1, i2, signature_only))
+ return FALSE;
+ return !g1->is_tb_open;
+}
+
guint
mono_metadata_generic_context_hash (const MonoGenericContext *context)
{
return TRUE;
if (c1->generic_class && c2->generic_class)
return _mono_metadata_generic_class_equal (c1->generic_class, c2->generic_class, signature_only);
+ if (c1->generic_class && c2->generic_container)
+ return _mono_metadata_generic_class_container_equal (c1->generic_class, c2, signature_only);
+ if (c1->generic_container && c2->generic_class)
+ return _mono_metadata_generic_class_container_equal (c2->generic_class, c1, signature_only);
if ((c1->byval_arg.type == MONO_TYPE_VAR) && (c2->byval_arg.type == MONO_TYPE_VAR))
return mono_metadata_generic_param_equal (
c1->byval_arg.data.generic_param, c2->byval_arg.data.generic_param, signature_only);
guint32 then = 0, now, delta;
guint32 waitms;
guint32 ret;
+ MonoThread *thread = mono_thread_current ();
LOCK_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
": (%d) Trying to lock object %p (%d ms)", id, obj, ms));
CloseHandle (sem);
}
}
-
+
/* If we need to time out, record a timestamp and adjust ms,
* because WaitForSingleObject doesn't tell us how long it
* waited for.
}
InterlockedIncrement (&mon->entry_count);
+
+ mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
+
ret = WaitForSingleObjectEx (mon->entry_sem, waitms, allow_interruption);
+
+ mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
+
InterlockedDecrement (&mon->entry_count);
if (ms != INFINITE) {
LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) queuing handle %p",
GetCurrentThreadId (), event));
- mono_monitor_enter (thread->synch_lock);
- thread->state |= ThreadState_WaitSleepJoin;
- mono_monitor_exit (thread->synch_lock);
+ mono_thread_current_check_pending_interrupt ();
+
+ mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
mon->wait_list = g_slist_append (mon->wait_list, event);
/* Reset the thread state fairly early, so we don't have to worry
* about the monitor error checking
*/
- mono_monitor_enter (thread->synch_lock);
- thread->state &= ~ThreadState_WaitSleepJoin;
- mono_monitor_exit (thread->synch_lock);
+ mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
if (mono_thread_interruption_requested ()) {
CloseHandle (event);
MonoType *type;
};
-#define MONO_DEBUGGER_VERSION 62
+#define MONO_DEBUGGER_VERSION 63
#define MONO_DEBUGGER_MAGIC 0x7aff65af4253d427ULL
extern MonoSymbolTable *mono_symbol_table;
gpointer suspend_event;
gpointer suspended_event;
gpointer resume_event;
- MonoObject *synch_lock;
+ CRITICAL_SECTION *synch_cs;
guint8* serialized_culture_info;
guint32 serialized_culture_info_len;
guint8* serialized_ui_culture_info;
void
mono_install_imt_trampoline (gpointer tramp) MONO_INTERNAL;
+void
+mono_install_vtable_trampoline (gpointer tramp) MONO_INTERNAL;
+
void
mono_vtable_build_imt_slot (MonoVTable* vtable, int imt_slot) MONO_INTERNAL;
imt_trampoline = tramp_code;
}
+static gpointer vtable_trampoline = NULL;
+
+void
+mono_install_vtable_trampoline (gpointer tramp_code)
+{
+ vtable_trampoline = tramp_code;
+}
+
/**
* mono_vtable_build_imt_slot:
* @vtable: virtual object table struct
if (mono_method_signature (cm)->generic_param_count)
vt->vtable [i] = cm;
else
- vt->vtable [i] = arch_create_jit_trampoline (cm);
+ vt->vtable [i] = vtable_trampoline? vtable_trampoline: arch_create_jit_trampoline (cm);
}
}
}
g_assert (tb->generic_params);
klass = mono_class_from_mono_type (tb->type.type);
+ if (tb->generic_container)
+ mono_reflection_create_generic_class (tb);
+
sigbuffer_add_value (&buf, MONO_TYPE_GENERICINST);
g_assert (klass->generic_container);
sigbuffer_add_value (&buf, klass->byval_arg.type);
token = mono_image_add_stream_data (&assembly->blob, blob_size, b - blob_size);
mono_image_add_stream_data (&assembly->blob, mono_array_addr (pkey, char, 0), len);
+ assembly->public_key = g_malloc (len);
+ memcpy (assembly->public_key, mono_array_addr (pkey, char, 0), len);
+ assembly->public_key_len = len;
+
/* Special case: check for ECMA key (16 bytes) */
if ((len == MONO_ECMA_KEY_LENGTH) && mono_is_ecma_key (mono_array_addr (pkey, char, 0), len)) {
/* In this case we must reserve 128 bytes (1024 bits) for the signature */
mono_reflection_get_type (MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve) {
return mono_reflection_get_type_with_rootimage(image, image, info, ignorecase, type_resolve);
}
+
+static MonoType*
+mono_reflection_get_type_internal_dynamic (MonoImage *rootimage, MonoAssembly *assembly, MonoTypeNameParse *info, gboolean ignorecase)
+{
+ MonoReflectionAssemblyBuilder *abuilder = (MonoReflectionAssemblyBuilder*)mono_assembly_get_object (mono_domain_get (), assembly);
+ MonoType *type;
+ int i;
+
+ g_assert (assembly->dynamic);
+
+ /* Enumerate all modules */
+
+ type = NULL;
+ if (abuilder->modules) {
+ for (i = 0; i < mono_array_length (abuilder->modules); ++i) {
+ MonoReflectionModuleBuilder *mb = mono_array_get (abuilder->modules, MonoReflectionModuleBuilder*, i);
+ type = mono_reflection_get_type_internal (rootimage, &mb->dynamic_image->image, info, ignorecase);
+ if (type)
+ break;
+ }
+ }
+
+ if (!type && abuilder->loaded_modules) {
+ for (i = 0; i < mono_array_length (abuilder->loaded_modules); ++i) {
+ MonoReflectionModule *mod = mono_array_get (abuilder->loaded_modules, MonoReflectionModule*, i);
+ type = mono_reflection_get_type_internal (rootimage, mod->image, info, ignorecase);
+ if (type)
+ break;
+ }
+ }
+
+ return type;
+}
MonoType*
mono_reflection_get_type_with_rootimage (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve)
GString *fullName;
GList *mod;
- type = mono_reflection_get_type_internal (rootimage, image, info, ignorecase);
+ if (image && image->dynamic)
+ type = mono_reflection_get_type_internal_dynamic (rootimage, image->assembly, info, ignorecase);
+ else
+ type = mono_reflection_get_type_internal (rootimage, image, info, ignorecase);
if (type)
return type;
if (!mono_domain_has_type_resolve (mono_domain_get ()))
assembly = mono_domain_try_type_resolve ( mono_domain_get (), fullName->str, NULL);
if (assembly) {
- if (assembly->assembly->dynamic) {
- /* Enumerate all modules */
- MonoReflectionAssemblyBuilder *abuilder = (MonoReflectionAssemblyBuilder*)assembly;
- int i;
-
- type = NULL;
- if (abuilder->modules) {
- for (i = 0; i < mono_array_length (abuilder->modules); ++i) {
- MonoReflectionModuleBuilder *mb = mono_array_get (abuilder->modules, MonoReflectionModuleBuilder*, i);
- type = mono_reflection_get_type_internal (rootimage, &mb->dynamic_image->image, info, ignorecase);
- if (type)
- break;
- }
- }
-
- if (!type && abuilder->loaded_modules) {
- for (i = 0; i < mono_array_length (abuilder->loaded_modules); ++i) {
- MonoReflectionModule *mod = mono_array_get (abuilder->loaded_modules, MonoReflectionModule*, i);
- type = mono_reflection_get_type_internal (rootimage, mod->image, info, ignorecase);
- if (type)
- break;
- }
- }
- }
+ if (assembly->assembly->dynamic)
+ type = mono_reflection_get_type_internal_dynamic (rootimage, assembly->assembly, info, ignorecase);
else
type = mono_reflection_get_type_internal (rootimage, assembly->assembly->image,
info, ignorecase);
m->generic_container = container = rmb->generic_container;
container->type_argc = count;
container->type_params = g_new0 (MonoGenericParam, count);
+ container->is_method = TRUE;
container->owner.method = m;
for (i = 0; i < count; i++) {
thread = mono_thread_current ();
}
- mono_monitor_enter (thread->synch_lock);
- leave = ((thread->state & ThreadState_AbortRequested) != 0 ||
- (thread->state & ThreadState_StopRequested) != 0);
- mono_monitor_exit (thread->synch_lock);
+ leave = mono_thread_test_state (thread, ThreadState_AbortRequested | ThreadState_StopRequested);
if (leave != 0) {
g_free (pfds);
if (thread == NULL)
thread = mono_thread_current ();
- mono_monitor_enter (thread->synch_lock);
- leave = ((thread->state & ThreadState_AbortRequested) != 0 ||
- (thread->state & ThreadState_StopRequested) != 0);
- mono_monitor_exit (thread->synch_lock);
+ leave = mono_thread_test_state (thread, ThreadState_AbortRequested | ThreadState_StopRequested);
+
if (leave != 0) {
g_free (pfds);
*sockets = NULL;
#define SPECIAL_STATIC_CONTEXT 2
extern HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this_obj, MonoObject *start) MONO_INTERNAL;
+extern void ves_icall_System_Threading_Thread_Thread_init(MonoThread *this_obj) MONO_INTERNAL;
extern void ves_icall_System_Threading_Thread_Thread_free_internal(MonoThread *this_obj, HANDLE thread) MONO_INTERNAL;
extern void ves_icall_System_Threading_Thread_Sleep_internal(int ms) MONO_INTERNAL;
extern gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this_obj, int ms, HANDLE thread) MONO_INTERNAL;
return;
mono_release_type_locks (thread);
- if (!mono_monitor_enter (thread->synch_lock))
- return;
+ EnterCriticalSection (thread->synch_cs);
thread->state |= ThreadState_Stopped;
thread->state &= ~ThreadState_Background;
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
+
mono_profiler_thread_end (thread->tid);
if (thread == mono_thread_current ())
thread->apartment_state=ThreadApartmentState_Unknown;
small_id_alloc (thread);
- MONO_OBJECT_SETREF (thread, synch_lock, mono_object_new (domain, mono_defaults.object_class));
+ thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
+ InitializeCriticalSection (thread->synch_cs);
handle_store(thread);
thread->apartment_state=ThreadApartmentState_Unknown;
small_id_alloc (thread);
thread->stack_ptr = &tid;
- MONO_OBJECT_SETREF (thread, synch_lock, mono_object_new (domain, mono_defaults.object_class));
+
+ thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
+ InitializeCriticalSection (thread->synch_cs);
THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
struct StartInfo *start_info;
HANDLE thread;
gsize tid;
+ CRITICAL_SECTION *synch_cs;
MONO_ARCH_SAVE_REGS;
THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
- mono_monitor_enter (this->synch_lock);
+ synch_cs = g_new0 (CRITICAL_SECTION, 1);
+ InitializeCriticalSection (synch_cs);
+
+ if (InterlockedCompareExchangePointer ((gpointer *)&this->synch_cs,
+ synch_cs, NULL) != NULL) {
+ /* This thread must have already been started! */
+ DeleteCriticalSection (synch_cs);
+ g_free (synch_cs);
+ }
+
+ EnterCriticalSection (this->synch_cs);
if ((this->state & ThreadState_Unstarted) == 0) {
- mono_monitor_exit (this->synch_lock);
+ LeaveCriticalSection (this->synch_cs);
mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
return NULL;
}
this->small_id = -1;
if ((this->state & ThreadState_Aborted) != 0) {
- mono_monitor_exit (this->synch_lock);
+ LeaveCriticalSection (this->synch_cs);
return this;
}
start_func = NULL;
this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
if(this->start_notify==NULL) {
- mono_monitor_exit (this->synch_lock);
+ LeaveCriticalSection (this->synch_cs);
g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
return(NULL);
}
thread=CreateThread(NULL, default_stacksize_for_thread (this), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
CREATE_SUSPENDED, &tid);
if(thread==NULL) {
- mono_monitor_exit (this->synch_lock);
+ LeaveCriticalSection (this->synch_cs);
g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
return(NULL);
}
THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
- mono_monitor_exit (this->synch_lock);
+ LeaveCriticalSection (this->synch_cs);
return(thread);
}
}
+void ves_icall_System_Threading_Thread_Thread_init (MonoThread *this)
+{
+ MONO_ARCH_SAVE_REGS;
+
+ this->synch_cs = g_new0 (CRITICAL_SECTION, 1);
+ InitializeCriticalSection (this->synch_cs);
+}
+
void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
HANDLE thread)
{
THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
CloseHandle (thread);
+
+ DeleteCriticalSection (this->synch_cs);
+ g_free (this->synch_cs);
}
static void mono_thread_start (MonoThread *thread)
mono_thread_current_check_pending_interrupt ();
- mono_monitor_enter (thread->synch_lock);
- thread->state |= ThreadState_WaitSleepJoin;
- mono_monitor_exit (thread->synch_lock);
+ mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
SleepEx(ms,TRUE);
- mono_monitor_enter (thread->synch_lock);
- thread->state &= ~ThreadState_WaitSleepJoin;
- mono_monitor_exit (thread->synch_lock);
+ mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
}
void ves_icall_System_Threading_Thread_SpinWait_internal (gint32 iterations)
ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
{
MonoString* str;
- mono_monitor_enter (this_obj->synch_lock);
+
+ EnterCriticalSection (this_obj->synch_cs);
if (!this_obj->name)
str = NULL;
else
str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
- mono_monitor_exit (this_obj->synch_lock);
+ LeaveCriticalSection (this_obj->synch_cs);
+
return str;
}
void
ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
{
- mono_monitor_enter (this_obj->synch_lock);
+ EnterCriticalSection (this_obj->synch_cs);
if (this_obj->name) {
- mono_monitor_exit (this_obj->synch_lock);
+ LeaveCriticalSection (this_obj->synch_cs);
+
mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
return;
}
else
this_obj->name = NULL;
- mono_monitor_exit (this_obj->synch_lock);
+ LeaveCriticalSection (this_obj->synch_cs);
}
static MonoObject*
{
MonoArray *res;
- mono_monitor_enter (this->synch_lock);
+ EnterCriticalSection (this->synch_cs);
+
if (this->serialized_culture_info) {
res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
} else {
res = NULL;
}
- mono_monitor_exit (this->synch_lock);
+
+ LeaveCriticalSection (this->synch_cs);
return res;
}
int free_slot = -1;
int same_domain_slot = -1;
- mono_monitor_enter (this->synch_lock);
+ EnterCriticalSection (this->synch_cs);
+
if (!this->cached_culture_info)
this->cached_culture_info = mono_array_new (mono_object_domain (this), mono_defaults.object_class, NUM_CACHED_CULTURES * 2);
else if (free_slot >= 0)
mono_array_setref (this->cached_culture_info, free_slot, culture);
/* we may want to replace an existing entry here, even when no suitable slot is found */
- mono_monitor_exit (this->synch_lock);
+
+ LeaveCriticalSection (this->synch_cs);
}
void
void
ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
{
- mono_monitor_enter (this->synch_lock);
+ EnterCriticalSection (this->synch_cs);
+
if (this->serialized_culture_info)
g_free (this->serialized_culture_info);
this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
this->serialized_culture_info_len = mono_array_length (arr);
memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
- mono_monitor_exit (this->synch_lock);
+
+ LeaveCriticalSection (this->synch_cs);
}
{
MonoArray *res;
- mono_monitor_enter (this->synch_lock);
+ EnterCriticalSection (this->synch_cs);
+
if (this->serialized_ui_culture_info) {
res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
} else {
res = NULL;
}
- mono_monitor_exit (this->synch_lock);
+
+ LeaveCriticalSection (this->synch_cs);
return res;
}
void
ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *this, MonoArray *arr)
{
- mono_monitor_enter (this->synch_lock);
+ EnterCriticalSection (this->synch_cs);
+
if (this->serialized_ui_culture_info)
g_free (this->serialized_ui_culture_info);
this->serialized_ui_culture_info = g_new0 (guint8, mono_array_length (arr));
this->serialized_ui_culture_info_len = mono_array_length (arr);
memcpy (this->serialized_ui_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
- mono_monitor_exit (this->synch_lock);
+
+ LeaveCriticalSection (this->synch_cs);
}
/* the jit may read the compiled code of this function */
gboolean ret;
MONO_ARCH_SAVE_REGS;
+
+ mono_thread_current_check_pending_interrupt ();
- mono_monitor_enter (this->synch_lock);
+ EnterCriticalSection (this->synch_cs);
if ((this->state & ThreadState_Unstarted) != 0) {
- mono_monitor_exit (this->synch_lock);
+ LeaveCriticalSection (this->synch_cs);
+
mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
return FALSE;
}
- mono_thread_current_check_pending_interrupt ();
-
this->state |= ThreadState_WaitSleepJoin;
- mono_monitor_exit (this->synch_lock);
+
+ LeaveCriticalSection (this->synch_cs);
if(ms== -1) {
ms=INFINITE;
ret=WaitForSingleObjectEx (thread, ms, TRUE);
- mono_monitor_enter (this->synch_lock);
- this->state &= ~ThreadState_WaitSleepJoin;
- mono_monitor_exit (this->synch_lock);
+ mono_thread_clr_state (this, ThreadState_WaitSleepJoin);
if(ret==WAIT_OBJECT_0) {
THREAD_DEBUG (g_message ("%s: join successful", __func__));
ms=INFINITE;
}
- mono_monitor_enter (thread->synch_lock);
- thread->state |= ThreadState_WaitSleepJoin;
- mono_monitor_exit (thread->synch_lock);
+ mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
- mono_monitor_enter (thread->synch_lock);
- thread->state &= ~ThreadState_WaitSleepJoin;
- mono_monitor_exit (thread->synch_lock);
+ mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
g_free(handles);
ms=INFINITE;
}
- mono_monitor_enter (thread->synch_lock);
- thread->state |= ThreadState_WaitSleepJoin;
- mono_monitor_exit (thread->synch_lock);
-
+ mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
+
ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
- mono_monitor_enter (thread->synch_lock);
- thread->state &= ~ThreadState_WaitSleepJoin;
- mono_monitor_exit (thread->synch_lock);
-
+ mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
+
g_free(handles);
THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
mono_thread_current_check_pending_interrupt ();
- mono_monitor_enter (thread->synch_lock);
- thread->state |= ThreadState_WaitSleepJoin;
- mono_monitor_exit (thread->synch_lock);
-
+ mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
+
ret=WaitForSingleObjectEx (handle, ms, TRUE);
- mono_monitor_enter (thread->synch_lock);
- thread->state &= ~ThreadState_WaitSleepJoin;
- mono_monitor_exit (thread->synch_lock);
-
+ mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
+
if(ret==WAIT_FAILED) {
THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
return(FALSE);
void
ves_icall_System_Threading_Thread_ClrState (MonoThread* this, guint32 state)
{
- mono_monitor_enter (this->synch_lock);
- this->state &= ~state;
+ mono_thread_clr_state (this, state);
+
if (state & ThreadState_Background) {
/* If the thread changes the background mode, the main thread has to
* be notified, since it has to rebuild the list of threads to
*/
SetEvent (background_change_event);
}
- mono_monitor_exit (this->synch_lock);
}
void
ves_icall_System_Threading_Thread_SetState (MonoThread* this, guint32 state)
{
- mono_monitor_enter (this->synch_lock);
- this->state |= state;
+ mono_thread_set_state (this, state);
+
if (state & ThreadState_Background) {
/* If the thread changes the background mode, the main thread has to
* be notified, since it has to rebuild the list of threads to
*/
SetEvent (background_change_event);
}
- mono_monitor_exit (this->synch_lock);
}
guint32
ves_icall_System_Threading_Thread_GetState (MonoThread* this)
{
guint32 state;
- mono_monitor_enter (this->synch_lock);
+
+ EnterCriticalSection (this->synch_cs);
+
state = this->state;
- mono_monitor_exit (this->synch_lock);
+
+ LeaveCriticalSection (this->synch_cs);
+
return state;
}
{
gboolean throw = FALSE;
- mono_monitor_enter (this->synch_lock);
+ EnterCriticalSection (this->synch_cs);
- /* Clear out any previous request */
- this->thread_interrupt_requested = FALSE;
+ this->thread_interrupt_requested = TRUE;
if (this->state & ThreadState_WaitSleepJoin) {
throw = TRUE;
- } else {
- this->thread_interrupt_requested = TRUE;
}
- mono_monitor_exit (this->synch_lock);
-
+ LeaveCriticalSection (this->synch_cs);
+
if (throw) {
signal_thread_state_change (this);
}
MonoThread *thread = mono_thread_current ();
gboolean throw = FALSE;
- mono_monitor_enter (thread->synch_lock);
-
+ EnterCriticalSection (thread->synch_cs);
+
if (thread->thread_interrupt_requested) {
throw = TRUE;
thread->thread_interrupt_requested = FALSE;
}
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
if (throw) {
mono_raise_exception (mono_get_exception_thread_interrupted ());
{
MONO_ARCH_SAVE_REGS;
- mono_monitor_enter (thread->synch_lock);
-
+ EnterCriticalSection (thread->synch_cs);
+
if ((thread->state & ThreadState_AbortRequested) != 0 ||
(thread->state & ThreadState_StopRequested) != 0 ||
(thread->state & ThreadState_Stopped) != 0)
{
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
return;
}
if ((thread->state & ThreadState_Unstarted) != 0) {
thread->state |= ThreadState_Aborted;
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
return;
}
MONO_OBJECT_SETREF (thread, abort_state, state);
thread->abort_exc = NULL;
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
MONO_ARCH_SAVE_REGS;
- mono_monitor_enter (thread->synch_lock);
+ EnterCriticalSection (thread->synch_cs);
thread->state &= ~ThreadState_AbortRequested;
if (!thread->abort_exc) {
const char *msg = "Unable to reset abort because no abort was requested";
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
mono_raise_exception (mono_get_exception_thread_state (msg));
} else {
thread->abort_exc = NULL;
thread->abort_state = NULL;
}
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
}
static gboolean
{
MONO_ARCH_SAVE_REGS;
- mono_monitor_enter (thread->synch_lock);
+ EnterCriticalSection (thread->synch_cs);
if ((thread->state & ThreadState_Unstarted) != 0 ||
(thread->state & ThreadState_Aborted) != 0 ||
(thread->state & ThreadState_Stopped) != 0)
{
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
return FALSE;
}
(thread->state & ThreadState_SuspendRequested) != 0 ||
(thread->state & ThreadState_StopRequested) != 0)
{
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
return TRUE;
}
thread->state |= ThreadState_SuspendRequested;
- mono_monitor_exit (thread->synch_lock);
+
+ LeaveCriticalSection (thread->synch_cs);
signal_thread_state_change (thread);
return TRUE;
{
MONO_ARCH_SAVE_REGS;
- mono_monitor_enter (thread->synch_lock);
+ EnterCriticalSection (thread->synch_cs);
if ((thread->state & ThreadState_SuspendRequested) != 0) {
thread->state &= ~ThreadState_SuspendRequested;
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
return TRUE;
}
(thread->state & ThreadState_Aborted) != 0 ||
(thread->state & ThreadState_Stopped) != 0)
{
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
return FALSE;
}
thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
if (thread->resume_event == NULL) {
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
return(FALSE);
}
/* Awake the thread */
SetEvent (thread->suspend_event);
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
/* Wait for the thread to awake */
WaitForSingleObject (thread->resume_event, INFINITE);
void mono_thread_stop (MonoThread *thread)
{
- mono_monitor_enter (thread->synch_lock);
+ EnterCriticalSection (thread->synch_cs);
if ((thread->state & ThreadState_StopRequested) != 0 ||
(thread->state & ThreadState_Stopped) != 0)
{
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
return;
}
thread->state |= ThreadState_StopRequested;
thread->state &= ~ThreadState_AbortRequested;
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
signal_thread_state_change (thread);
}
InitializeCriticalSection(&contexts_mutex);
InitializeCriticalSection(&delayed_free_table_mutex);
InitializeCriticalSection(&small_id_mutex);
+
background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
g_assert(background_change_event != NULL);
continue;
}
- mono_monitor_enter (thread->synch_lock);
+ EnterCriticalSection (thread->synch_cs);
if ((thread->state & ThreadState_Suspended) != 0 ||
(thread->state & ThreadState_SuspendRequested) != 0 ||
(thread->state & ThreadState_StopRequested) != 0 ||
(thread->state & ThreadState_Stopped) != 0) {
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
CloseHandle (wait->handles [i]);
wait->threads [i] = NULL; /* ignore this thread in next loop */
continue;
thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
if (thread->suspended_event == NULL) {
/* Forget this one and go on to the next */
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
continue;
}
}
events [eventidx++] = thread->suspended_event;
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
/* Signal the thread to suspend */
signal_thread_state_change (thread);
if (thread == NULL)
continue;
- mono_monitor_enter (thread->synch_lock);
+ EnterCriticalSection (thread->synch_cs);
CloseHandle (thread->suspended_event);
thread->suspended_event = NULL;
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
}
g_free (events);
int i;
/* No locking needed here */
- /* FIXME: why no locking? writes to the cache are protected with synch_lock above */
+ /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
if (thread->cached_culture_info) {
for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
*/
static MonoException* mono_thread_execute_interruption (MonoThread *thread)
{
- mono_monitor_enter (thread->synch_lock);
+ EnterCriticalSection (thread->synch_cs);
if (thread->interruption_requested) {
/* this will consume pending APC calls */
if ((thread->state & ThreadState_AbortRequested) != 0) {
if (thread->abort_exc == NULL)
MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
return thread->abort_exc;
}
else if ((thread->state & ThreadState_SuspendRequested) != 0) {
thread->state |= ThreadState_Suspended;
thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
if (thread->suspend_event == NULL) {
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
return(NULL);
}
if (thread->suspended_event)
SetEvent (thread->suspended_event);
- mono_monitor_exit (thread->synch_lock);
+
+ LeaveCriticalSection (thread->synch_cs);
WaitForSingleObject (thread->suspend_event, INFINITE);
- mono_monitor_enter (thread->synch_lock);
+ EnterCriticalSection (thread->synch_cs);
+
CloseHandle (thread->suspend_event);
thread->suspend_event = NULL;
thread->state &= ~ThreadState_Suspended;
* and will be waiting for it
*/
SetEvent (thread->resume_event);
- mono_monitor_exit (thread->synch_lock);
+
+ LeaveCriticalSection (thread->synch_cs);
+
return NULL;
}
else if ((thread->state & ThreadState_StopRequested) != 0) {
/* FIXME: do this through the JIT? */
- mono_monitor_exit (thread->synch_lock);
+
+ LeaveCriticalSection (thread->synch_cs);
+
mono_thread_exit ();
return NULL;
} else if (thread->thread_interrupt_requested) {
- mono_monitor_exit (thread->synch_lock);
+
+ LeaveCriticalSection (thread->synch_cs);
+
return(mono_get_exception_thread_interrupted ());
}
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
+
return NULL;
}
if (thread == NULL)
return NULL;
- mono_monitor_enter (thread->synch_lock);
+ EnterCriticalSection (thread->synch_cs);
if (thread->interruption_requested) {
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
+
return NULL;
}
InterlockedIncrement (&thread_interruption_requested);
thread->interruption_requested = TRUE;
- mono_monitor_exit (thread->synch_lock);
+
+ LeaveCriticalSection (thread->synch_cs);
/* this will awake the thread if it is in WaitForSingleObject
or similar */
return NULL;
}
else {
- mono_monitor_exit (thread->synch_lock);
+ LeaveCriticalSection (thread->synch_cs);
+
return mono_thread_execute_interruption (thread);
}
}
}
#endif
}
+
+void
+mono_thread_set_state (MonoThread *thread, MonoThreadState state)
+{
+ EnterCriticalSection (thread->synch_cs);
+ thread->state |= state;
+ LeaveCriticalSection (thread->synch_cs);
+}
+
+void
+mono_thread_clr_state (MonoThread *thread, MonoThreadState state)
+{
+ EnterCriticalSection (thread->synch_cs);
+ thread->state &= ~state;
+ LeaveCriticalSection (thread->synch_cs);
+}
+
+gboolean
+mono_thread_test_state (MonoThread *thread, MonoThreadState test)
+{
+ gboolean ret = FALSE;
+
+ EnterCriticalSection (thread->synch_cs);
+
+ if ((thread->state & test) != 0) {
+ ret = TRUE;
+ }
+
+ LeaveCriticalSection (thread->synch_cs);
+
+ return ret;
+}
#include <mono/utils/mono-membar.h>
#include <mono/metadata/object.h>
#include <mono/metadata/appdomain.h>
+#include <mono/metadata/threads-types.h>
G_BEGIN_DECLS
extern void mono_thread_force_interruption_checkpoint (void);
extern gint32* mono_thread_interruption_request_flag (void);
+extern void mono_thread_set_state (MonoThread *thread, MonoThreadState state);
+extern void mono_thread_clr_state (MonoThread *thread, MonoThreadState state);
+extern gboolean mono_thread_test_state (MonoThread *thread, MonoThreadState test);
+
G_END_DECLS
#endif /* _MONO_METADATA_THREADS_H_ */
+2007-10-17 Zoltan Varga <vargaz@gmail.com>
+
+ * mini-ia64.h mini-amd64.c: Add support for the common vtable trampoline.
+
+ * inssel.brg (mini_emit_virtual_call): Fix the computation of ins->inst_offset on
+ 64 bit platforms.
+
+ * mini-ia64.h mini-ia64.c: Add support for IMT.
+
+ * mini-x86.c (mono_arch_emit_prolog): Increase the size allocated for the
+ prolog. Fixes #331958.
+
+2007-10-15 Zoltan Varga <vargaz@gmail.com>
+
+ * mini-sparc.h mini-sparc.c: Add support for the common vtable trampoline.
+
+Mon Oct 15 11:18:52 CEST 2007 Paolo Molaro <lupus@ximian.com>
+
+ * mini-ppc.c, mini-ppc.h: ppc support for the common vtable
+ trampoline.
+
+Mon Oct 15 10:41:27 CEST 2007 Paolo Molaro <lupus@ximian.com>
+
+ * mini-amd64.c, mini-amd64.h: amd64 support for the common vtable
+ trampoline.
+
+Mon Oct 15 10:39:26 CEST 2007 Paolo Molaro <lupus@ximian.com>
+
+ * mini-x86.c, mini-x86.h: x86 support for the common vtable
+ trampoline.
+
+Mon Oct 15 10:37:15 CEST 2007 Paolo Molaro <lupus@ximian.com>
+
+ * mini-trampolines.c: changed the magic rampoline to understand
+ the common vtable trampoline method: the method to invoke is
+ determined by the vtable displacement of the call.
+
+Mon Oct 15 10:35:12 CEST 2007 Paolo Molaro <lupus@ximian.com>
+
+ * mini.c, mini.h: register the common vtable trampoline if the
+ architecture supports it.
+
+Mon Oct 15 09:50:52 CEST 2007 Paolo Molaro <lupus@ximian.com>
+
+ * cpu-amd64.md: use the correct max length for tls_get.
+
+2007-10-14 Zoltan Varga <vargaz@gmail.com>
+
+ * mini.c (mono_method_to_ir): Use mini_get_class in CEE_LDELEM_ANY and
+ CEE_STELEM_ANY. Fixes #333696.
Thu Oct 11 18:04:29 CEST 2007 Paolo Molaro <lupus@ximian.com>
x86_add_membase: dest:i src1:i src2:b clob:1 len:13
x86_sub_membase: dest:i src1:i src2:b clob:1 len:13
x86_mul_membase: dest:i src1:i src2:b clob:1 len:14
-tls_get: dest:i len:13
+tls_get: dest:i len:16
amd64_test_null: src1:i len:5
amd64_icompare_membase_reg: src1:b src2:i len:8
amd64_icompare_membase_imm: src1:b len:13
guint32 imt_slot = mono_method_get_imt_slot (method);
emit_imt_argument (cfg, (MonoCallInst*)tree);
slot_reg = vtable_reg;
- tree->inst_offset = (imt_slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
+ tree->inst_offset = ((gint32)imt_slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
#else
slot_reg = mono_regstate_next_int (cfg->rs);
mini_emit_load_intf_reg_vtable (cfg, slot_reg, vtable_reg, method->klass);
return 3;
}
-gpointer*
-mono_arch_get_vcall_slot_addr (guint8* code, gpointer *regs)
+gpointer
+mono_arch_get_vcall_slot (guint8 *code, gpointer *regs, int *displacement)
{
guint32 reg;
gint32 disp;
guint8 rex = 0;
+ *displacement = 0;
+
/* go to the start of the call instruction
*
* address_byte = (m << 6) | (o << 3) | reg
/* R11 is clobbered by the trampoline code */
g_assert (reg != AMD64_R11);
- return (gpointer)(((guint64)(regs [reg])) + disp);
+ *displacement = disp;
+ return regs [reg];
+}
+
+gpointer*
+mono_arch_get_vcall_slot_addr (guint8* code, gpointer *regs)
+{
+ gpointer vt;
+ int displacement;
+ vt = mono_arch_get_vcall_slot (code, regs, &displacement);
+ if (!vt)
+ return NULL;
+ return (gpointer*)((char*)vt + displacement);
}
gpointer
#define MONO_ARCH_HAVE_CREATE_VARS 1
#define MONO_ARCH_HAVE_IMT 1
#define MONO_ARCH_IMT_REG AMD64_R11
+#define MONO_ARCH_COMMON_VTABLE_TRAMPOLINE 1
#define MONO_ARCH_AOT_SUPPORTED 1
case OP_LCALL_MEMBASE:
case OP_VCALL_MEMBASE:
case OP_VOIDCALL_MEMBASE:
- case OP_CALL_MEMBASE:
+ case OP_CALL_MEMBASE: {
+ MonoCallInst *call = (MonoCallInst*)ins;
+ CallInfo *cinfo;
+ int out_reg;
+
/*
* There are no membase instructions on ia64, but we can't
* lower this since get_vcall_slot_addr () needs to decode it.
*/
/* Keep this in synch with get_vcall_slot_addr */
+ ia64_mov (code, IA64_R11, ins->sreg1);
if (ia64_is_imm14 (ins->inst_offset))
ia64_adds_imm (code, IA64_R8, ins->inst_offset, ins->sreg1);
else {
ia64_add (code, IA64_R8, GP_SCRATCH_REG, ins->sreg1);
}
+ if (call->method && ins->inst_offset < 0) {
+ /*
+ * This is a possible IMT call so save the IMT method in a global
+ * register where mono_arch_find_imt_method () and its friends can access
+ * it.
+ */
+ ia64_movl (code, IA64_R9, call->method);
+ }
+
+ /*
+ * mono_arch_find_this_arg () needs to find the this argument in a global
+ * register.
+ */
+ cinfo = get_call_info (NULL, call->signature, FALSE);
+ out_reg = cfg->arch.reg_out0;
+ if (cinfo->ret.storage == ArgValuetypeAddrInIReg)
+ out_reg ++;
+ g_free (cinfo);
+ ia64_mov (code, IA64_R10, out_reg);
+
ia64_begin_bundle (code);
ia64_codegen_set_one_ins_per_bundle (code, TRUE);
code = emit_move_return_value (cfg, ins, code);
break;
+ }
case OP_JMP: {
/*
* Keep in sync with the code in emit_epilog.
}
if (alloc_size) {
+#if defined(MONO_ARCH_SIGSEGV_ON_ALTSTACK)
int pagesize = getpagesize ();
-#if defined(MONO_ARCH_SIGSEGV_ON_ALTSTACK)
if (alloc_size >= pagesize) {
gint32 remaining_size = alloc_size;
return 0;
}
-gpointer*
-mono_arch_get_vcall_slot_addr (guint8* code, gpointer *regs)
+gpointer
+mono_arch_get_vcall_slot (guint8* code, gpointer *regs, int *displacement)
{
guint8 *bundle2 = code - 48;
guint8 *bundle3 = code - 32;
guint64 ins41 = ia64_bundle_ins1 (bundle4);
guint64 ins42 = ia64_bundle_ins2 (bundle4);
guint64 ins43 = ia64_bundle_ins3 (bundle4);
- int reg;
/*
* Virtual calls are made with:
g_assert (ia64_ins_x (ins22) == 0);
g_assert (ia64_ins_b1 (ins22) == IA64_B6);
- reg = IA64_R8;
-
- /*
- * Must be a scratch register, since only those are saved by the trampoline
- */
- g_assert ((1 << reg) & MONO_ARCH_CALLEE_REGS);
+ *displacement = (gssize)regs [IA64_R8] - (gssize)regs [IA64_R11];
- g_assert (regs [reg]);
-
- return regs [reg];
+ return regs [IA64_R11];
}
return NULL;
}
+gpointer*
+mono_arch_get_vcall_slot_addr (guint8* code, gpointer *regs)
+{
+ gpointer vt;
+ int displacement;
+ vt = mono_arch_get_vcall_slot (code, regs, &displacement);
+ if (!vt)
+ return NULL;
+ return (gpointer*)(gpointer)((char*)vt + displacement);
+}
+
gpointer*
mono_arch_get_delegate_method_ptr_addr (guint8* code, gpointer *regs)
{
}
}
+
+#ifdef MONO_ARCH_HAVE_IMT
+
+/*
+ * LOCKING: called with the domain lock held
+ */
+gpointer
+mono_arch_build_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count)
+{
+ int i;
+ int size = 0;
+ guint8 *start, *buf;
+ Ia64CodegenState code;
+
+ size = count * 256;
+ buf = g_malloc0 (size);
+ ia64_codegen_init (code, buf);
+
+ /* IA64_R9 contains the IMT method */
+
+ for (i = 0; i < count; ++i) {
+ MonoIMTCheckItem *item = imt_entries [i];
+ ia64_begin_bundle (code);
+ item->code_target = (guint8*)code.buf + code.nins;
+ if (item->is_equals) {
+ if (item->check_target_idx) {
+ if (!item->compare_done) {
+ ia64_movl (code, GP_SCRATCH_REG, item->method);
+ ia64_cmp_eq (code, 6, 7, IA64_R9, GP_SCRATCH_REG);
+ }
+ item->jmp_code = (guint8*)code.buf + code.nins;
+ ia64_br_cond_pred (code, 7, 0);
+
+ ia64_movl (code, GP_SCRATCH_REG, &(vtable->vtable [item->vtable_slot]));
+ ia64_ld8 (code, GP_SCRATCH_REG, GP_SCRATCH_REG);
+ ia64_mov_to_br (code, IA64_B6, GP_SCRATCH_REG);
+ ia64_br_cond_reg (code, IA64_B6);
+ } else {
+ /* enable the commented code to assert on wrong method */
+#if ENABLE_WRONG_METHOD_CHECK
+ g_assert_not_reached ();
+#endif
+ ia64_movl (code, GP_SCRATCH_REG, &(vtable->vtable [item->vtable_slot]));
+ ia64_ld8 (code, GP_SCRATCH_REG, GP_SCRATCH_REG);
+ ia64_mov_to_br (code, IA64_B6, GP_SCRATCH_REG);
+ ia64_br_cond_reg (code, IA64_B6);
+#if ENABLE_WRONG_METHOD_CHECK
+ g_assert_not_reached ();
+#endif
+ }
+ } else {
+ ia64_movl (code, GP_SCRATCH_REG, item->method);
+ ia64_cmp_geu (code, 6, 7, IA64_R9, GP_SCRATCH_REG);
+ item->jmp_code = (guint8*)code.buf + code.nins;
+ ia64_br_cond_pred (code, 6, 0);
+ }
+ }
+ /* patch the branches to get to the target items */
+ for (i = 0; i < count; ++i) {
+ MonoIMTCheckItem *item = imt_entries [i];
+ if (item->jmp_code) {
+ if (item->check_target_idx) {
+ ia64_patch (item->jmp_code, imt_entries [item->check_target_idx]->code_target);
+ }
+ }
+ }
+
+ ia64_codegen_close (code);
+ g_assert (code.buf - buf <= size);
+
+ size = code.buf - buf;
+ start = mono_code_manager_reserve (domain->code_mp, size);
+ memcpy (start, buf, size);
+
+ mono_arch_flush_icache (start, size);
+
+ mono_stats.imt_thunks_size += size;
+
+ return start;
+}
+
+MonoMethod*
+mono_arch_find_imt_method (gpointer *regs, guint8 *code)
+{
+ return regs [IA64_R9];
+}
+
+MonoObject*
+mono_arch_find_this_argument (gpointer *regs, MonoMethod *method)
+{
+ return regs [IA64_R10];
+}
+
+void
+mono_arch_emit_imt_argument (MonoCompile *cfg, MonoCallInst *call)
+{
+ /* Done by the implementation of the CALL_MEMBASE opcodes */
+}
+#endif
+
MonoInst*
mono_arch_get_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
{
/* Parameters used by the register allocator */
/* r8..r11, r14..r29 */
-#define MONO_ARCH_CALLEE_REGS ((regmask_t)(0x700UL) | (regmask_t)(0x3fffc000UL))
+#define MONO_ARCH_CALLEE_REGS ((regmask_t)(0xf00UL) | (regmask_t)(0x3fffc000UL))
/* f6..f15, f34..f127 */
/* FIXME: Use the upper 64 bits as well */
#define MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE 1
#define MONO_ARCH_HAVE_SAVE_UNWIND_INFO 1
#define MONO_ARCH_HAVE_CREATE_VARS 1
+#define MONO_ARCH_HAVE_IMT 1
+#define MONO_ARCH_COMMON_VTABLE_TRAMPOLINE 1
#endif /* __MONO_MINI_IA64_H__ */
return frame_size;
}
-gpointer*
-mono_arch_get_vcall_slot_addr (guint8 *code_ptr, gpointer *regs)
+gpointer
+mono_arch_get_vcall_slot (guint8 *code_ptr, gpointer *regs, int *displacement)
{
char *o = NULL;
int reg, offset = 0;
guint32* code = (guint32*)code_ptr;
+ *displacement = 0;
+
/* This is the 'blrl' instruction */
--code;
break;
}
}
- o += offset;
- return (gpointer*)o;
+ *displacement = offset;
+ return o;
+}
+
+gpointer*
+mono_arch_get_vcall_slot_addr (guint8 *code, gpointer *regs)
+{
+ gpointer vt;
+ int displacement;
+ vt = mono_arch_get_vcall_slot (code, regs, &displacement);
+ if (!vt)
+ return NULL;
+ return (gpointer*)((char*)vt + displacement);
}
#define MAX_ARCH_DELEGATE_PARAMS 7
#define MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
#define MONO_ARCH_HAVE_IMT 1
#define MONO_ARCH_IMT_REG ppc_r12
+#define MONO_ARCH_COMMON_VTABLE_TRAMPOLINE 1
#define MONO_ARCH_USE_SIGACTION 1
#define MONO_ARCH_NEED_DIV_CHECK 1
}
/*
- * mono_arch_get_vcall_slot_addr:
+ * mono_arch_get_vcall_slot:
*
* Determine the vtable slot used by a virtual call.
*/
-gpointer*
-mono_arch_get_vcall_slot_addr (guint8 *code8, gpointer *regs)
+gpointer
+mono_arch_get_vcall_slot (guint8 *code8, gpointer *regs, int *displacement)
{
guint32 *code = (guint32*)(gpointer)code8;
guint32 ins = code [0];
mono_sparc_flushw ();
+ *displacement = 0;
+
if (!mono_sparc_is_virtual_call (code))
return NULL;
base_val = regs [base];
- return (gpointer)((guint8*)base_val + disp);
+ *displacement = disp;
+
+ return (gpointer)base_val;
}
else if ((sparc_inst_op (prev_ins) == 0x3) && (sparc_inst_i (prev_ins) == 0) && (sparc_inst_op3 (prev_ins) == 0)) {
/* set r1, ICONST; ld [r1 + r2], r2; call r2 */
base_val = regs [base];
- return (gpointer)((guint8*)base_val + disp);
+ *displacement = disp;
+
+ return (gpointer)base_val;
} else
g_assert_not_reached ();
}
return NULL;
}
+gpointer*
+mono_arch_get_vcall_slot_addr (guint8 *code, gpointer *regs)
+{
+ gpointer vt;
+ int displacement;
+ vt = mono_arch_get_vcall_slot (code, regs, &displacement);
+ if (!vt)
+ return NULL;
+ return (gpointer*)((char*)vt + displacement);
+}
+
#define CMP_SIZE 3
#define BR_SMALL_SIZE 2
#define BR_LARGE_SIZE 2
#define MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE 1
#define MONO_ARCH_HAVE_IMT 1
#define MONO_ARCH_IMT_REG sparc_g1
+#define MONO_ARCH_COMMON_VTABLE_TRAMPOLINE 1
#ifdef SPARCV9
#define MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
gpointer addr;
gpointer *vtable_slot;
+#if MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
+ if (m == MONO_FAKE_VTABLE_METHOD) {
+ int displacement;
+ MonoVTable *vt = mono_arch_get_vcall_slot (code, (gpointer*)regs, &displacement);
+ g_assert (vt);
+ if (displacement > 0) {
+ displacement -= G_STRUCT_OFFSET (MonoVTable, vtable);
+ g_assert (displacement >= 0);
+ displacement /= sizeof (gpointer);
+ mono_class_setup_vtable (vt->klass);
+ m = vt->klass->vtable [displacement];
+ /*g_print ("%s with disp %d: %s at %p\n", vt->klass->name, displacement, m->name, code);*/
+ } else {
+ /* We got here from an interface method: redirect to IMT handling */
+ m = MONO_FAKE_IMT_METHOD;
+ /*g_print ("vtable with disp %d at %p\n", displacement, code);*/
+ }
+ }
+#endif
/* this is the IMT trampoline */
#ifdef MONO_ARCH_HAVE_IMT
if (m == MONO_FAKE_IMT_METHOD) {
/* mono_convert_imt_slot_to_vtable_slot () also gives us the method that is supposed
* to be called, so we compile it and go ahead as usual.
*/
+ /*g_print ("imt found method %p (%s) at %p\n", impl_method, impl_method->name, code);*/
m = impl_method;
}
#endif
+
addr = mono_compile_method (m);
g_assert (addr);
int alloc_size, pos, max_offset, i;
guint8 *code;
- cfg->code_size = MAX (mono_method_get_header (method)->code_size * 4, 256);
+ cfg->code_size = MAX (mono_method_get_header (method)->code_size * 4, 1024);
if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
cfg->code_size += 512;
}
}
-gpointer*
-mono_arch_get_vcall_slot_addr (guint8 *code, gpointer *regs)
+gpointer
+mono_arch_get_vcall_slot (guint8 *code, gpointer *regs, int *displacement)
{
guint8 reg = 0;
gint32 disp = 0;
+ *displacement = 0;
+
/* go to the start of the call instruction
*
* address_byte = (m << 6) | (o << 3) | reg
return NULL;
}
- return (gpointer*)(((gint32)(regs [reg])) + disp);
+ *displacement = disp;
+ return regs [reg];
+}
+
+gpointer*
+mono_arch_get_vcall_slot_addr (guint8 *code, gpointer *regs)
+{
+ gpointer vt;
+ int displacement;
+ vt = mono_arch_get_vcall_slot (code, regs, &displacement);
+ if (!vt)
+ return NULL;
+ return (gpointer*)((char*)vt + displacement);
}
gpointer
#define MONO_ARCH_HAVE_CREATE_VARS 1
#define MONO_ARCH_HAVE_IMT 1
#define MONO_ARCH_IMT_REG X86_EDX
+#define MONO_ARCH_COMMON_VTABLE_TRAMPOLINE 1
#define MONO_ARCH_AOT_SUPPORTED 1
UNVERIFIED;
CHECK_OPSIZE (5);
token = read32 (ip + 1);
- klass = mono_class_get_full (image, token, generic_context);
+ klass = mini_get_class (method, token, generic_context);
CHECK_TYPELOAD (klass);
mono_class_init (klass);
NEW_LDELEMA (cfg, load, sp, klass);
UNVERIFIED;
CHECK_OPSIZE (5);
token = read32 (ip + 1);
- klass = mono_class_get_full (image, token, generic_context);
+ klass = mini_get_class (method, token, generic_context);
CHECK_TYPELOAD (klass);
mono_class_init (klass);
if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
}
#endif
+#ifdef MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
+static gpointer
+mini_get_vtable_trampoline (void)
+{
+ static gpointer tramp = NULL;
+ if (!tramp)
+ tramp = mono_arch_create_specific_trampoline (MONO_FAKE_VTABLE_METHOD, MONO_TRAMPOLINE_GENERIC, mono_get_root_domain (), NULL);
+ return tramp;
+}
+#endif
+
static void
mini_parse_debug_options (void)
{
#ifdef MONO_ARCH_HAVE_IMT
mono_install_imt_thunk_builder (mono_arch_build_imt_thunk);
mono_install_imt_trampoline (mini_get_imt_trampoline ());
+#if MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
+ mono_install_vtable_trampoline (mini_get_vtable_trampoline ());
+#endif
#endif
mono_icall_init ();
#define inst_ms_word data.op[MINI_MS_WORD_IDX].const_val
#define MONO_FAKE_IMT_METHOD ((MonoMethod*)GINT_TO_POINTER(-1))
+#define MONO_FAKE_VTABLE_METHOD ((MonoMethod*)GINT_TO_POINTER(-2))
/* Version number of the AOT file format */
#define MONO_AOT_FILE_VERSION "32"
void mono_arch_invalidate_method (MonoJitInfo *ji, void *func, gpointer func_arg) MONO_INTERNAL;
guint32 mono_arch_get_patch_offset (guint8 *code) MONO_INTERNAL;
gpointer*mono_arch_get_vcall_slot_addr (guint8* code, gpointer *regs) MONO_INTERNAL;
+gpointer mono_arch_get_vcall_slot (guint8 *code, gpointer *regs, int *displacement) MONO_INTERNAL;
gpointer*mono_arch_get_delegate_method_ptr_addr (guint8* code, gpointer *regs) MONO_INTERNAL;
void mono_arch_create_vars (MonoCompile *cfg) MONO_INTERNAL;
void mono_arch_save_unwind_info (MonoCompile *cfg) MONO_INTERNAL;
+2007-10-20 William Holmes <billholmes54@gmail.com>
+
+ * pinvoke2.cs, libtest.c Adding test cases for marshaling
+ booleans as I1 and U1. Tests commit r87725.
+
+ Code is contributed under MIT/X11 license.
+
+2007-10-18 Zoltan Varga <vargaz@gmail.com>
+
+ * interlocked.cs: Add a test for CompareExchange and negative values.
+
+2007-10-17 Mark Probst <mark.probst@gmail.com>
+
+ * bug-331798-tb.2.cs: added for Rodrigo
+
+ * Makefile.am: added bug-331798-tb.2.cs
+
+2007-10-17 Gert Driesen <drieseng@users.sourceforge.net>
+
+ * bug-331958.cs: added.
+ * Makefile.am: added bug-331958.cs.
+
+2007-10-16 Mark Probst <mark.probst@gmail.com>
+
+ * bug-333798.2.cs: added
+
+ * Makefile.am: added bug-333798.2.cs
+
2007-10-05 Rodrigo Kumpera <rkumpera@novell.com>
* generic_type_definition_encoding.2.cs: added, this tests
bug-78653.cs \
bug-78656.cs \
bug-77127.cs \
+ bug-331958.cs \
interlocked.cs \
cross-domain.cs \
appdomain-exit.cs \
anonarray.2.cs \
ienumerator-interfaces.2.cs \
generic_type_definition_encoding.2.cs \
- generic_type_definition.2.cs
+ generic_type_definition.2.cs \
+ bug-333798.2.cs \
+ bug-333798-tb.2.cs
TEST_IL2_SRC = find-method.2.il \
bug-79215.2.il \
--- /dev/null
+class Program
+{
+ static int Main ()
+ {
+ X18 x18 = new X18 ();
+ x18.x1 = new X17 ();
+ x18.x2 = new X17 ();
+ if (x18.GetType () != typeof (X18))
+ return 1;
+
+ return 0;
+ }
+}
+
+
+struct X0 { public byte b; }
+struct X1 { public X0 x1; public X0 x2; }
+struct X2 { public X1 x1; public X1 x2; }
+struct X3 { public X2 x1; public X2 x2; }
+struct X4 { public X3 x1; public X3 x2; }
+struct X5 { public X4 x1; public X4 x2; }
+struct X6 { public X5 x1; public X5 x2; }
+struct X7 { public X6 x1; public X6 x2; }
+struct X8 { public X7 x1; public X7 x2; }
+struct X9 { public X8 x1; public X8 x2; }
+struct X10 { public X9 x1; public X9 x2; }
+struct X11 { public X10 x1; public X10 x2; }
+struct X12 { public X11 x1; public X11 x2; }
+struct X13 { public X12 x1; public X12 x2; }
+struct X14 { public X13 x1; public X13 x2; }
+struct X15 { public X14 x1; public X14 x2; }
+struct X16 { public X15 x1; public X15 x2; }
+struct X17 { public X16 x1; public X16 x2; }
+struct X18 { public X17 x1; public X17 x2; }
--- /dev/null
+using System;
+using System.Threading;
+using System.Reflection;
+using System.Reflection.Emit;
+using System.IO;
+using System.Security;
+using System.Security.Permissions;
+using System.Runtime.InteropServices;
+using System.Collections.Generic;
+
+public class Gen<T> {
+ public static Gen<T>[] newSelfArr () {
+ return null;
+ }
+}
+
+public class Driver {
+ public static void Test () {
+ Gen<int>.newSelfArr ();
+ }
+}
+
+public class GenericsTests
+{
+ static AssemblyBuilder assembly;
+ static ModuleBuilder module;
+
+ static void SetUp ()
+ {
+ AssemblyName assemblyName = new AssemblyName ();
+ assemblyName.Name = "TestAssembly";
+ assembly =
+ Thread.GetDomain ().DefineDynamicAssembly (
+ assemblyName, AssemblyBuilderAccess.RunAndSave, ".");
+ module = assembly.DefineDynamicModule ("module1", "TestModuleSS.dll");
+ }
+
+ public static int Main () {
+ SetUp ();
+ TypeBuilder tb = module.DefineType ("Gen", TypeAttributes.Public);
+ Type[] args = tb.DefineGenericParameters ("T");
+ Type oi = tb.MakeGenericType (args);
+
+ MethodBuilder mb = tb.DefineMethod ("Test", MethodAttributes.Public | MethodAttributes.Static, oi.MakeArrayType (), new Type [0]);
+
+ ILGenerator il = mb.GetILGenerator();
+ il.Emit (OpCodes.Ldnull);
+ il.Emit (OpCodes.Ret);
+ tb.CreateType ();
+
+ TypeBuilder main = module.DefineType ("Driver", TypeAttributes.Public);
+ MethodBuilder mb2 = main.DefineMethod ("Test", MethodAttributes.Public | MethodAttributes.Static);
+
+ il = mb2.GetILGenerator();
+ il.Emit (OpCodes.Call, TypeBuilder.GetMethod (tb.MakeGenericType (typeof (int)), mb));
+ il.Emit (OpCodes.Pop);
+ il.Emit (OpCodes.Ret);
+ Type tt = main.CreateType ();
+
+ tt.GetMethod ("Test").Invoke (null, null);
+ //typeof (Driver).GetMethod ("Test").Invoke (null, null);
+ return 0;
+ }
+}
--- /dev/null
+public class Gen<T> {
+ public static Gen<T>[] newSelfArr () {
+ return null;
+ }
+}
+
+public class main {
+ public static void Main () {
+ Gen<int>.newSelfArr ();
+ }
+}
if (it.test != 1)
return 2;
+ it.test = -2;
+ c = Interlocked.CompareExchange (ref it.test, 1, -2);
+ if (c != -2)
+ return 3;
+
+ if (it.test != 1)
+ return 4;
+
a = 1;
b = Interlocked.Increment (ref a);
if (a != 2)
- return 3;
+ return 5;
if (b != 2)
- return 4;
+ return 6;
a = 2;
b = Interlocked.Decrement (ref a);
if (b != 1)
- return 3;
+ return 7;
if (a != 1)
- return 4;
+ return 8;
string s = IncTest ();
if (s != "A1")
- return 5;
+ return 9;
s = IncTest ();
if (s != "A2")
- return 6;
+ return 10;
Thread.MemoryBarrier ();
return res;
}
+STDCALL int
+mono_test_marshal_bool_in_as_I1_U1 (char bTrue, char bFalse)
+{
+ if (!bTrue)
+ return 1;
+ if (bFalse)
+ return 2;
+ return 0;
+}
+
+STDCALL int
+mono_test_marshal_bool_out_as_I1_U1 (char* bTrue, char* bFalse)
+{
+ if (!bTrue || !bFalse)
+ return 3;
+
+ *bTrue = 1;
+ *bFalse = 0;
+
+ return 0;
+}
+
+STDCALL int
+mono_test_marshal_bool_ref_as_I1_U1 (char* bTrue, char* bFalse)
+{
+ if (!bTrue || !bFalse)
+ return 4;
+
+ if (!(*bTrue))
+ return 5;
+ if (*bFalse)
+ return 6;
+
+ *bFalse = 1;
+ *bTrue = 0;
+
+ return 0;
+}
+
STDCALL int
mono_test_marshal_array (int *a1)
{
[DllImport ("libtest", EntryPoint="mono_test_marshal_bool_byref")]
public static extern int mono_test_marshal_bool_byref (int a, ref bool b, int c);
+ [DllImport ("libtest", EntryPoint="mono_test_marshal_bool_in_as_I1_U1")]
+ public static extern int mono_test_marshal_bool_in_as_I1 ([MarshalAs (UnmanagedType.I1)] bool bTrue, [MarshalAs (UnmanagedType.I1)] bool bFalse);
+
+ [DllImport ("libtest", EntryPoint="mono_test_marshal_bool_in_as_I1_U1")]
+ public static extern int mono_test_marshal_bool_in_as_U1 ([MarshalAs (UnmanagedType.U1)] bool bTrue, [MarshalAs (UnmanagedType.U1)] bool bFalse);
+
+ [DllImport ("libtest", EntryPoint="mono_test_marshal_bool_out_as_I1_U1")]
+ public static extern int mono_test_marshal_bool_out_as_I1 ([MarshalAs (UnmanagedType.I1)] out bool bTrue, [MarshalAs (UnmanagedType.I1)] out bool bFalse);
+
+ [DllImport ("libtest", EntryPoint="mono_test_marshal_bool_out_as_I1_U1")]
+ public static extern int mono_test_marshal_bool_out_as_U1 ([MarshalAs (UnmanagedType.U1)] out bool bTrue, [MarshalAs (UnmanagedType.U1)] out bool bFalse);
+
+ [DllImport ("libtest", EntryPoint="mono_test_marshal_bool_ref_as_I1_U1")]
+ public static extern int mono_test_marshal_bool_ref_as_I1 ([MarshalAs (UnmanagedType.I1)] ref bool bTrue, [MarshalAs (UnmanagedType.I1)] ref bool bFalse);
+
+ [DllImport ("libtest", EntryPoint="mono_test_marshal_bool_ref_as_I1_U1")]
+ public static extern int mono_test_marshal_bool_ref_as_U1 ([MarshalAs (UnmanagedType.U1)] ref bool bTrue, [MarshalAs (UnmanagedType.U1)] ref bool bFalse);
+
[DllImport ("libtest", EntryPoint="mono_test_marshal_array")]
public static extern int mono_test_marshal_array (int [] a1);
return 0;
}
+ public static int test_0_marshal_bool_as_I1 () {
+
+ int ret;
+ bool bTrue, bFalse;
+ if ((ret = mono_test_marshal_bool_in_as_I1 (true, false)) != 0)
+ return ret;
+
+ if ((ret = mono_test_marshal_bool_out_as_I1 (out bTrue, out bFalse)) != 0)
+ return ret;
+
+ if(!bTrue)
+ return 10;
+
+ if(bFalse)
+ return 11;
+
+ if ((ret = mono_test_marshal_bool_ref_as_I1 (ref bTrue, ref bFalse)) != 0)
+ return ret;
+
+ if(bTrue)
+ return 12;
+
+ if(!bFalse)
+ return 13;
+
+ return 0;
+ }
+
+ public static int test_0_marshal_bool_as_U1 () {
+
+ int ret;
+ bool bTrue, bFalse;
+ if ((ret = mono_test_marshal_bool_in_as_U1 (true, false)) != 0)
+ return ret;
+
+ if ((ret = mono_test_marshal_bool_out_as_U1 (out bTrue, out bFalse)) != 0)
+ return ret;
+
+ if(!bTrue)
+ return 10;
+
+ if(bFalse)
+ return 11;
+
+ if ((ret = mono_test_marshal_bool_ref_as_U1 (ref bTrue, ref bFalse)) != 0)
+ return ret;
+
+ if(bTrue)
+ return 12;
+
+ if(!bFalse)
+ return 13;
+
+ return 0;
+ }
+
public static int test_0_return_vtype () {
SimpleStruct ss = mono_test_return_vtype (new IntPtr (5));
gmcs \
httpcfg \
ilasm2 \
+ mconfig \
mkbundle2 \
mono-api-info2 \
monop2 \
return 1;
}
+void
+breakprop (int fd)
+{
+ tcsendbreak (fd, 0);
+}
+
gboolean
poll_serial (int fd, gint32 *error, int timeout)
{