Compare commits

..
93 Commits
Author SHA1 Message Date
Alex Corrado 378032bf64 Fix prepending $(CURDIR) to paths failing under cygwin 2011-09-15 13:07:57 -04:00
Alex Corrado a19eb0760b 2.10.6 2011-09-13 23:37:20 -04:00
Gonzalo Paniagua Javier 5cfc62f415 Stop lying in the comments 2011-09-13 20:24:11 -04:00
Gonzalo Paniagua Javier 1ed1c4bed1 Report compilation errors when the type named in 'class' can't be loaded. 2011-09-13 20:24:01 -04:00
Rodrigo Kumpera 616f648f0d Avoid duplicates in the SSC xrefs.
* sgen-brige.c (scc_add_xref): Make sure that the xref
	array is kept sorted by doing sorted insertion for single elements
	and merging for a pair of lists.

	This avoids degenerated cases where performance of the dfs2 step
	goes unbound and slows us down significantly.

	Fixes bxc #496
2011-09-13 15:35:31 -03:00
Rodrigo Kumpera 4fccd4d599 Add logging to sgen-bridge. Log times and sizes. 2011-09-13 15:35:30 -03:00
Rolf Bjarne Kvinge bd4f80e803 [System.Data] Delay column expression evaluation after all the columns have been cloned when cloning a table. Fixes #666.
When cloning a table we loop over all the columns and clone them, but if a column
contains an expression with a reference to a later column, we'll throw an exception
unless we delay the expression compilation until all the columns have been added
to the new table clone.

So I've split out the expression compilation logic from the Expression property setter,
and now the column Clone method only sets the field. The Clone caller is responsible
for calling CompileExpression on the cloned column after adding all the cloned columns to
the cloned table.
2011-09-13 14:15:11 +02:00
Rolf Bjarne Kvinge 9e9b3f913d [System.Data] Properly clone a column's extended properties when cloning a table. Fixes #668. 2011-09-13 13:01:57 +02:00
Jérémie Laval a2a168e5f3 Add missing files. 2011-09-13 12:20:07 +02:00
Jérémie Laval 5f982b1908 Backport System.Threading.Tasks from master to mono-2-10 2011-09-13 12:18:39 +02:00
Gonzalo Paniagua Javier f00202d3e3 Delay initialization of the stream until first read
This way uri-based resources are not fetched before they are supposed
	to.

	Fixes Xamarin bug #762.
2011-09-13 01:24:14 -04:00
Gonzalo Paniagua Javier b4d4033040 Internal worker is kept while there is an ongoing operation
When there is an ongoing operation we can't dispose the internal
	worker because it might be used by the IO threadpool.

	Fixes Novell bug #691076 and Xamarin bug #766.
2011-09-13 00:06:12 -04:00
Sebastien Pouliot 68deb6335e More fixes for running unit tests under NET_2_1 profile 2011-09-12 12:53:17 -04:00
Miguel de Icaza cb965a9d3a Various fixes to the Expression parser, the fixes include:
* Fixes to the SUBSTRING and TRIM function to allow
	  a wider range of functions to be passed as
	  parameters.   This fixes xamarin #665

	* Fix to the Parser.jay grammar to eliminate the
	  reduce/reduce conflicts.

	* Dropping the string concatenation code and instead
	  use the existing arithmetic addition operator which
	  also fixes the concatenation operation in the presence
	  of null values

	* Adds the null literal

With the associated test cases.
2011-09-09 22:04:18 -04:00
Marek Habersack 86262ef424 Support colors on 256-color terminals 2011-09-09 22:04:02 -04:00
Sebastien Pouliot acfa4856b9 Adjust corlib unit tests to reduce failures when executed on the NET_2_1 profile 2011-09-09 13:48:15 -04:00
Sebastien Pouliot be8711a7e6 fix FileStream test failures under Mac OSX 2011-09-09 13:48:01 -04:00
Sebastien Pouliot 7e6a0ff51e Throwing IsolatedStorageException is a Moonlight-behavior and should not have been exposed to other 2.1 profiles 2011-09-09 13:47:48 -04:00
Sebastien Pouliot c989e10293 Ensure we can roundtrip 'Local' (special case) timezone. Fix bug #326 2011-09-09 13:29:40 -04:00
Sebastien Pouliot b04d809478 Return null instead of catching Activator exception (and return null). What was a corner case before is now very common when the linker is used (e.g. monotouch, m4a). Reported in assistly #1741 2011-09-09 13:29:26 -04:00
Miguel de Icaza 219276c182 Fallback: load profiler from the Mono default path. This in particular allows users to run mono --profiler=log foo.exe without having to set anuy environment variables 2011-09-07 18:44:22 -04:00
Sebastien Pouliot 64ff652330 Add null-check on 'partDesc'. Fix bug #612 (WCF regression) 2011-09-07 11:17:55 -04:00
Rodrigo Kumpera 75e3ca80bc Let the system figure our permissions instead of doing a poor job at it.
io.c (DeleteFile): We can't forbit a file to be deleted just before
	it's mask is not u+w. We should just call unlink and let the kernel
	figure out permissions.

	We are not SAMBA.

	We're not in the job of trying to mingle windows and unix permissions
	models so we just let the kernel figure it out and translate the appropriate
	errno value to UnauthorizedAccessException.
2011-09-06 19:36:00 -03:00
Jérémie Laval aa48b6f714 Use a TaskCompletionSource in non-generic ContinueWhenAny case. Fix #647. 2011-09-06 23:55:01 +02:00
Rodrigo Kumpera 2603a2e4fd Improve exception message. 2011-09-06 14:53:00 -03:00
Rodrigo Kumpera 05550e7c66 Add collection logging to sgen. 2011-09-06 14:52:59 -03:00
Gonzalo Paniagua Javier 99349445b1 Display more debugging info when epoll fails 2011-09-05 21:13:07 -04:00
Gonzalo Paniagua Javier d768dd0125 Fallback to poll() if epoll_create() fails
From a patch by Zoltan in bug #705190.
2011-09-05 20:51:10 -04:00
Zoltan Varga e376d9156b Handle threads which die without detaching. 2011-09-06 04:24:21 +02:00
Zoltan Varga 85349b801f Implement AppDomain.ResourceResolve. Fixes #579. 2011-09-04 03:20:22 +02:00
Mark Probst 41d1be9f34 [sgen] Break tracking weak references as early as possible.
Our tracking references code aimed to transform tracking references
into normal weak references the first time their targets became
unreachable.  It was implemented incorrectly though, and is not the
right thing to do in the first place anyway, because tracking
references have to keep tracking if the target is re-registered for
finalization.  The incorrect implementation inadvertently handled
re-registration correctly, but it kept the reference intact for one
garbage collection cycle too many.
2011-09-02 11:14:27 -03:00
Rodrigo Kumpera ac19d5bfaf Handle finalizable objects pointed by bridge objects. (cont...)
* sgen-fin-weak-hash.c:
	* sgen-gc.c: Bridge objects are used to represent objects
	that have references outside of sgen's control. They are
	kept around until the embedder figures out it's ok to
	collect them.
	Until those bridge objects turn externally unreachable,
	they must be kept around. Up to now, the expected pattern
	was to resurrect them during finalization.
	The problem with this approach is that if they hold references
	to other finalizable, non-bridge objects those will be finalized
	and we will resurrect objects that point to dead ones.

	Think of this:

	class BridgeObject {
 		FileStream stream;
	}

	The bridge object is resurrected on the finalizer and so will
	stream, disposing its native handle and been permanently unusable.

	The solution is to process brige objects before we do ordinary
	finalization. We record all dead bridges and copy/mark them.
	We drain the gray queue on the end, which makes sure all other
	finalizable objects that transitively reachable are too.

	Finally, we introduce a breaking change to the bridge API.
	The bridge must set to NULL the first object of all SCC
	entries that remain alive. Other entries will be considered
	dead and will be subject to regular finalization.

	This way, sgen knows when a given bridge object is completely
	unreachable and provides adequate finalization semantics to
	them and referenced objects.

	This fixes bxc #375
2011-09-01 20:13:06 -03:00
Atsushi Eno ae7d005dfc DiffLoader didn't handle encoded name and caused mismatch between .NET. 2011-08-31 17:53:04 -07:00
Atsushi Eno 04427d962d Fix invalid path check for Windows regarding ':'. 2011-08-31 14:12:51 -07:00
Atsushi Eno 57bc2f6ffb Add test for bug #545. 2011-08-31 14:12:42 -07:00
Atsushi Eno 059a6a685b EncoderReplacementFallbackBuffer.Reset() did not really reset its internals. 2011-08-31 14:03:10 -07:00
Chris Toshok 4ac77ca819 prepend $(CURDIR) to jay input files so that the debugging info references the right .jay 2011-08-30 17:06:50 -07:00
Jonathan Pryor d703e86b4b Don't use vasprintf on PLATFORM_ANDROID.
This allows sanely using g_log() within signal handlers.
2011-08-30 15:44:17 -04:00
Atsushi Eno 6870a59952 Implement IXmlLineInfo on XLinq node reader. 2011-08-30 23:13:36 +09:00
Atsushi Eno 721dadd34b LineInfo on namespace nodes were missing. 2011-08-30 20:22:01 +09:00
Sebastien Pouliot b7061d3e57 Fix build. Adding #if MOBILE is just not enough ;-) 2011-08-29 09:53:23 -04:00
Sebastien Pouliot 2f4099863e Fix bug #380. Patch from bnc#605795 were not committed to master but part of MonoTouch 3.x (ended up missing in MT4) 2011-08-29 08:57:30 -04:00
Hin-Tak Leung 96e0c59371 Fix mingw32 cross-build on a git no-branch checkout. Fixes #698446. 2011-08-29 01:25:19 +02:00
Zoltan Varga 1e910229a8 Allow pointers to structures to be passed in pinvoke, MS seems to allow this at least in some cases. Fixes bxc #158.
This partially reverts c4d9097c57.
2011-08-28 17:52:05 +02:00
Jérémie Laval c74031105a Check that CancellationToken coming from OperationCanceledException isn't None. Fix #472. 2011-08-28 14:50:12 +02:00
Atsushi Eno 279678d726 Revert GET switch for serializing requests. BodyWriter handles it better. 2011-08-24 18:13:04 -07:00
Atsushi Eno 46db32524d for GET request, just skip the member. It does not contain xml for null. 2011-08-24 16:48:46 -07:00
Atsushi Eno 0563034987 Skip serialization when the return type is void.
This batch should fix bug #206.
2011-08-24 12:20:23 -07:00
Atsushi Eno 0baf32151f Do not try to output empty message body to logs. 2011-08-24 12:20:13 -07:00
Atsushi Eno 8bd9eebf1f When there is void return, the common message formatter should ignore it.
This case occurs when MessageContract is used and there is no member for
the return value.
2011-08-24 12:20:02 -07:00
Atsushi Eno b9a5b85c16 ReturnValue in MessageDescription was missing when there was MessageContract. 2011-08-24 12:19:52 -07:00
Atsushi Eno c98be1ad12 Differentiate GET query parameter binding from another request binding.
This is one core of the bugfix for #206.
2011-08-24 12:19:42 -07:00
Atsushi Eno 67b1fcec06 When there was no path parameter, it ignored the whole path part. 2011-08-24 12:19:31 -07:00
Atsushi Eno 4643f66d1a This filter should ignore port, and should not filter out anonymous URIs. 2011-08-24 12:19:21 -07:00
Atsushi Eno e3aa857b74 UriTemplate should not be mandatory, make it optional. Fix unit test. 2011-08-23 11:43:56 -07:00
Alex Corrado 350fcbd003 2.10.5 2011-08-22 19:58:07 -04:00
Jérémie Laval c6799b1f41 Throw when a non-finished task is started 2011-08-20 15:00:24 +02:00
Jérémie Laval f260ff4299 Make TaskCompletionSource methods thread-safe
Conflicts:

	mcs/class/corlib/System.Threading.Tasks/TaskCompletionSource.cs
2011-08-20 14:54:28 +02:00
Rodrigo Kumpera 7122b78d60 Fix sgen-arm-mach. It requires some #define juggling.
.
2011-08-19 20:36:39 -03:00
Rodrigo Kumpera 52971cce4c Fix variance test involving nullable types.
* class.c (mono_class_is_variant_compatible): Reject valuetypes
	if not the same straight away. This fixes testing IEnumerable<int?>
	with IEnumerable<int>.

	Fixes bxc #185
2011-08-19 19:32:48 -03:00
Rodrigo Kumpera 5dc77749e7 Correctly calculate the size of the freed array buffer.
* sgen-bridge.c (dyn_array_ensure_capacity): We must correctly
	calculate the size as our allocator asserts when we do it with
	very large allocs.
2011-08-19 02:06:24 -03:00
Rodrigo Kumpera 472b3e6fca Fix android's broken pthread_kill under sgen. 2011-08-18 14:02:26 -03:00
Alan McGovern 59b4c5bc3d [LinkedList] Optimise Clear slightly. 2011-08-18 16:06:27 +01:00
Alan McGovern f105c6d4e7 Merge pull request #161 from LogosBible/master
Fix bug #311: On LinkedList.Clear, detach each node instead of dropping them en masse.
2011-08-18 16:06:10 +01:00
Zoltan Varga 2e637c4cba Disable some failing LLVM passes. Should fix bxc #280. 2011-08-18 17:00:34 +02:00
Jérémie Laval 8d44e61042 Fix coding style 2011-08-17 20:02:02 +02:00
Sebastien Pouliot eac9866b2c Provide an error message if an instance method is decorated with [MonoPInvokeCallback]. Ease finding issues like bug #296 2011-08-17 10:49:30 -04:00
Alan McGovern 7ada4aec7b [System.IO.Packaging] Fix calling convention related issues
The P/Invokes should be Cdecl as the library is compiled with that
calling convention. The delegates passed to native code must also
be marshalled as Cdecl. Fixes BXC #223.
2011-08-17 12:50:23 +01:00
Miguel de Icaza dacb11a24c updated copyrights 2011-08-17 01:26:05 -04:00
Miguel de Icaza 5c44041365 More updates 2011-08-17 01:21:40 -04:00
Rodrigo Kumpera 56b901df8f Fix g_log redirection under android. 2011-08-16 16:30:06 -03:00
Jérémie Laval 582bd35450 Backport TaskCreationOptions check from master 2011-08-16 19:06:45 +02:00
Jeffrey Stedfast 6057352d91 Merge pull request #158 from nickers/mono-2-10
remove debug CWL's
2011-08-16 04:35:11 -07:00
Tomasz Wsuł 3b450189bb Remove writing statement on standard output 2011-08-16 12:56:08 +02:00
Jeffrey Stedfast 7878c22bbf Fixed a typo in zoltan's last commit 2011-08-15 18:05:13 -04:00
Jeffrey Stedfast 674372dd15 Fix for bug #445855
In this day and age of mobile personal computing devices,
we need to periodically check the underlying system
timezone because the device may have crossed a timezone
boundary.
2011-08-15 15:19:20 -04:00
Zoltan Varga af804a9305 Escape characters in LLVM symbol names 2011-08-15 17:47:56 +01:00
Zoltan Varga 7e2eff0be7 Don't pass MONO_UNWIND_ACTUAL_METHOD to the stack walker in a signal handler, its not signal safe. Fixes bxc #263. 2011-08-14 22:35:55 +02:00
Gonzalo Paniagua Javier 7de999655d [threadpool] Exit on unhandled exceptions only
Unhandled exceptions will only set the exitcode if there is no
	AppDomain unhandled exception handler. When the exitcode is set,
	the TP will exit for unhandled exceptions.

	Fixes bug #227.
2011-08-13 00:34:13 -04:00
Gonzalo Paniagua Javier 1b84abfcab [threadpool] Work around for a race-condition
Under some circumstances new_job was not signaled and the threadpool
	threads didn't realized there was a workitem in the queue.

	Fixes Xamarin bug #12 and Novell bug #690357.
2011-08-12 23:17:05 -04:00
Sebastien Pouliot 8286cbf198 Use 'as' for casting certificate extensions since we already deal with null and malformed extensions will throw, hard to debug, ICE when we just want to ignore them 2011-08-12 14:59:12 -04:00
Gonzalo Paniagua Javier db7d7c47cb Fix the range for rnd.Next() 2011-08-11 14:17:23 -04:00
Rodrigo Kumpera 9445d6e22c Add IObserver/IObservable to MOBILE profile. 2011-08-11 13:19:47 -03:00
Marek Habersack 209c253e3f Compilation fix for e449d41158 2011-08-11 02:29:07 +02:00
Marek Habersack e449d41158 [runtime] Fix for Xamarin bug #99. Don't fail to parse assembly names with spaces surrounding = in key=value pairs 2011-08-11 02:20:11 +02:00
Zoltan Varga 9b4a07a69e Fix the newly added test_0_llvm_regress_171 (). 2011-08-10 18:10:58 +02:00
Jérémie Laval 28766cfe96 Avoid creating a delegate instance in general case when setting up continuations
Conflicts:

	mcs/class/corlib/System.Threading.Tasks/Task.cs
2011-08-10 17:16:23 +02:00
Jonathan Pryor a95adaf53d [System,MOBILE] Add System.Text.RegularExpressions.RegexOptions.Compiled.
Add the RegexOptions.Compiled enumeration value to the MOBILE profile.

Fixes: http://bugzilla.xamarin.com/show_bug.cgi?id=149

MonoTouch and Mono for Android still use `PatternCompiler`, which is
interpreted. Thus RegexOptions.Compiled is ignored, and is present only for
compatibility with Windows Phone 7, which states [0]:

	Present only in Silverlight for Windows Phone, but not supported.

[0] http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regexoptions(VS.96).aspx
2011-08-09 21:33:56 -04:00
Zoltan Varga 7ae2112edc LLVM requires two PHI entries if a previous bblock branches to the current bblock using a conditional branch whose two targets are the same. Fixes #171. 2011-08-09 21:41:54 +02:00
Zoltan Varga 79b99d358b Add support for reference instances of Interlocked.Exchange<T> to full-aot, similarly to Interlocked.CompareExchange<T>. 2011-08-09 19:16:15 +02:00
Zoltan Varga 12fedc8ee6 Merge pull request #154 from mdsol/fix-mono-tarball-tests
Fix mono tarball tests
2011-08-09 10:03:00 -07:00
Jeffrey Stedfast 27589a4031 If #CONFIGURATION_DEP isn't defined, we still want to get a default proxy 2011-08-09 12:30:32 -04:00
Harry Wilkinson 049efb2da8 Include mono/tests/delegate2.exe.config to the source tarball so that the tests pass 2011-08-08 18:16:03 +01:00
164 changed files with 4097 additions and 1042 deletions

No files matched your search

+2 -2
View File
@@ -57,11 +57,11 @@ function setup ()
CROSS_DLL_DIR="$CROSS_DIR/bin"
PATH=$CROSS_BIN_DIR:$PATH
MONO_VERSION=`grep AM_INIT_AUTOMAKE configure.in | cut -d ',' -f 2|tr -d '\)'`
MONO_VERSION=`grep AM_INIT_AUTOMAKE configure.in | cut -d ',' -f 2|tr -d '\)'|tr -d '\('`
if [ -d ./.git ]; then
MONO_GIT_COMMIT="`git log -1 --format=format:%t`"
MONO_GIT_BRANCH="`git branch|grep '\*'|cut -d ' ' -f 2`"
MONO_GIT_BRANCH="`git branch|grep '\*'|cut -d ' ' -f 2|tr -d '\)'|tr -d '\('`"
MONO_RELEASE="$MONO_VERSION-$MONO_GIT_BRANCH-$MONO_GIT_COMMIT"
else
MONO_RELEASE="$MONO_VERSION"
+1 -1
View File
@@ -6,7 +6,7 @@ AC_CANONICAL_SYSTEM
m4_ifdef([_A][M_PROG_TAR],[_A][M_SET_OPTION([tar-ustar])])
AM_CONFIG_HEADER(config.h)
AM_INIT_AUTOMAKE(mono,2.10.4)
AM_INIT_AUTOMAKE(mono,2.10.6)
AM_MAINTAINER_MODE
API_VER=2.0
+1
View File
@@ -58,6 +58,7 @@ case $host in
;;
*-*-linux-android*)
platform_android=yes
AC_DEFINE(PLATFORM_ANDROID,1,[Targeting the Android platform])
PATHSEP='/'
SEARCHSEP=':'
OS="UNIX"
+8 -9
View File
@@ -24,6 +24,7 @@
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
@@ -111,28 +112,26 @@ g_log_set_fatal_mask (const gchar *log_domain, GLogLevelFlags fatal_mask)
void
g_logv (const gchar *log_domain, GLogLevelFlags log_level, const gchar *format, va_list args)
{
#if PLATFORM_ANDROID
__android_log_vprint (to_android_priority (log_level), log_domain, format, args);
#else
char *msg;
vasprintf (&msg, format, args);
#if PLATFORM_ANDROID
__android_log_print (to_android_priority (log_level),
/* TODO: provide a proper app name */
"mono", "%s%s%s",
log_domain != NULL ? log_domain : "",
log_domain != NULL ? ": " : "",
msg);
#else
printf ("%s%s%s\n",
log_domain != NULL ? log_domain : "",
log_domain != NULL ? ": " : "",
msg);
#endif
free (msg);
if (log_level & fatal){
fflush (stdout);
fflush (stderr);
abort ();
}
#endif
if (log_level & fatal){
abort ();
}
}
void
+2
View File
@@ -26,6 +26,8 @@ PLATFORM_MAKE_CORLIB_CMP = yes
PLATFORM_CHANGE_SEPARATOR_CMD=tr '/' '\\\\'
PLATFORM_PATH_SEPARATOR = ;
override CURDIR:=$(shell cygpath -m $(CURDIR))
## not so simple :-)
#PLATFORM_AOT_SUFFIX = .dll
+1 -1
View File
@@ -22,7 +22,7 @@ EXTRA_DISTFILES = \
$(RESOURCE_FILES)
Commons.Xml.Relaxng.Rnc/RncParser.cs: Commons.Xml.Relaxng.Rnc/RncParser.jay $(topdir)/jay/skeleton.cs
$(topdir)/jay/jay -ctv < $(topdir)/jay/skeleton.cs Commons.Xml.Relaxng.Rnc/RncParser.jay > Commons.Xml.Relaxng.Rnc/RncParser.cs
$(topdir)/jay/jay -ctv < $(topdir)/jay/skeleton.cs $(CURDIR)/Commons.Xml.Relaxng.Rnc/RncParser.jay > Commons.Xml.Relaxng.Rnc/RncParser.cs
BUILT_SOURCES = Commons.Xml.Relaxng.Rnc/RncParser.cs
+2 -2
View File
@@ -28,13 +28,13 @@ Mono.Xml.XPath2/XQueryParser.jay: Mono.Xml.XPath2/ParserBase.jay $(SKELETON)
Mono.Xml.XPath2/XPath2Parser.cs: Mono.Xml.XPath2/XPath2Parser.jay
echo "#define XPATH2_PARSER" > $@
echo "#if NET_2_0" >> $@
$(topdir)/jay/jay -ct < $(SKELETON) $< >>$@
$(topdir)/jay/jay -ct < $(SKELETON) $(CURDIR)/$< >>$@
echo "#endif" >> $@
Mono.Xml.XPath2/XQueryParser.cs: Mono.Xml.XPath2/XQueryParser.jay $(SKELETON)
echo "#define XQUERY_PARSER" > $@
echo "#if NET_2_0" >> $@
$(topdir)/jay/jay -ct < $(SKELETON) $< >>$@
$(topdir)/jay/jay -ct < $(SKELETON) $(CURDIR)/$< >>$@
echo "#endif" >> $@
Mono.Xml.XPath2/XPath2Tokenizer.cs: Mono.Xml.XPath2/TokenizerBase.cs
@@ -329,6 +329,9 @@ namespace System
#if MONODROID
return ZoneInfoDB.GetTimeZone (id);
#elif LIBC
// Local requires special logic that already exists in the Local property (bug #326)
if (id == "Local")
return Local;
string filepath = Path.Combine (TimeZoneDirectory, id);
return FindSystemTimeZoneByFileName (id, filepath);
#else
@@ -540,6 +540,20 @@ namespace MonoTests.System
TimeZoneInfo vatican = TimeZoneInfo.FindSystemTimeZoneById ("Europe/Vatican");
Assert.IsTrue (rome.HasSameRules (vatican));
}
[Test]
public void FindSystemTimeZoneById_Local_Roundtrip ()
{
Assert.AreEqual (TimeZoneInfo.Local.Id, TimeZoneInfo.FindSystemTimeZoneById (TimeZoneInfo.Local.Id).Id);
}
[Test]
public void Test326 ()
{
DateTime utc = DateTime.UtcNow;
DateTime local = TimeZoneInfo.ConvertTime (utc, TimeZoneInfo.Utc, TimeZoneInfo.FindSystemTimeZoneById (TimeZoneInfo.Local.Id));
Assert.AreEqual (local, utc + TimeZoneInfo.Local.GetUtcOffset (utc), "ConvertTime/Local");
}
#if SLOW_TESTS
[Test]
@@ -263,15 +263,10 @@ namespace System.Data.OracleClient.Oci {
rsize = rsizep.ToUInt64 ();
//rsize = Encoding.UTF8.GetMaxByteCount (commandText.Length+1);
Console.WriteLine ("OCIStatementHandle:Prepare: CmdText:{0}, rsize:{1} ",
commandText, rsize);
// Fill buffer
buffer = new byte[rsize];
Console.WriteLine ("OCIStatementHandle:Prepare: buffer.Length:{0}, this.columnCount:{1}",
buffer.Length, this.ColumnCount);
OciCalls.OCIUnicodeToCharSet (Parent, buffer, commandText, ref rsizep);
// Execute statement
+1 -1
View File
@@ -63,7 +63,7 @@ EXTRA_DISTFILES = \
BUILT_SOURCES = Mono.Data.SqlExpressions/Parser.cs
Mono.Data.SqlExpressions/Parser.cs: Mono.Data.SqlExpressions/Parser.jay $(topdir)/jay/skeleton.cs
$(topdir)/jay/jay -ct < $(topdir)/jay/skeleton.cs $< >$@
$(topdir)/jay/jay -vct < $(topdir)/jay/skeleton.cs $(CURDIR)/$< >$@
include ../../build/library.make
@@ -6,6 +6,7 @@
// Juraj Skripsky ([email protected])
//
// (C) 2004 HotFeet GmbH (http://www.hotfeet.ch)
// Copyright 2011 Xamarin Inc (http://www.xamarin.com)
//
using System;
@@ -190,6 +191,7 @@ LiteralValue
| NumberLiteral { $$ = new Literal ($1); }
| DateLiteral { $$ = new Literal ($1); }
| BoolLiteral
| NULL { $$ = new Literal (null); }
;
BoolLiteral
@@ -271,28 +273,20 @@ AggFunctionName
;
StringExpr
: PAROPEN StringExpr PARCLOSE
{
$$ = (IExpression)$2;
}
| SingleColumnValue
: SingleColumnValue
| StringLiteral { $$ = new Literal ($1); }
| StringFunction
| Function
;
StringFunction
: TRIM PAROPEN StringExpr PARCLOSE
: TRIM PAROPEN ArithExpr PARCLOSE
{
$$ = new TrimFunction ((IExpression)$3);
}
| SUBSTRING PAROPEN StringExpr COMMA ArithExpr COMMA ArithExpr PARCLOSE
| SUBSTRING PAROPEN ArithExpr COMMA ArithExpr COMMA ArithExpr PARCLOSE
{
$$ = new SubstringFunction ((IExpression)$3, (IExpression)$5, (IExpression)$7);
}
| StringExpr PLUS StringExpr
{
$$ = new ConcatFunction ((IExpression)$1, (IExpression)$3);
}
;
CalcFunction
@@ -55,42 +55,6 @@ namespace Mono.Data.SqlExpressions {
}
}
internal class ConcatFunction : StringFunction
{
readonly IExpression _add;
public ConcatFunction (IExpression e, IExpression add)
: base (e)
{
_add = add;
}
public override bool Equals(object obj)
{
if (!base.Equals (obj))
return false;
if (!(obj is ConcatFunction))
return false;
ConcatFunction other = (ConcatFunction) obj;
return _add.Equals (other._add);
}
public override int GetHashCode()
{
int hashCode = base.GetHashCode ();
hashCode ^= _add.GetHashCode ();
return hashCode;
}
override public object Eval (DataRow row) {
string str = (string) base.Eval (row);
string x = (string) _add.Eval (row);
return str + x;
}
}
internal class SubstringFunction : StringFunction {
IExpression start;
IExpression len;
+48 -41
View File
@@ -17,6 +17,7 @@
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
// Copyright (C) 2011 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -475,43 +476,53 @@ namespace System.Data {
if (value == null)
value = String.Empty;
if (value != String.Empty) {
if (AutoIncrement || Unique)
throw new ArgumentException ("Cannot create an expression on a column that has AutoIncrement or Unique.");
CompileExpression (value);
_expression = value;
}
}
if (Table != null) {
for (int i = 0; i < Table.Constraints.Count; i++) {
if (Table.Constraints [i].IsColumnContained (this))
throw new ArgumentException (
String.Format (
"Cannot set Expression property on column {0}, because it is a part of a constraint.",
ColumnName));
}
}
internal void CompileExpression ()
{
CompileExpression (_expression);
}
Parser parser = new Parser ();
IExpression compiledExpression = parser.Compile (value);
internal void CompileExpression (string expression)
{
if (expression != String.Empty) {
if (AutoIncrement || Unique)
throw new ArgumentException ("Cannot create an expression on a column that has AutoIncrement or Unique.");
if (Table != null) {
if (compiledExpression.DependsOn (this))
throw new ArgumentException ("Cannot set Expression property due to circular reference in the expression.");
// Check if expression is ok
if (Table.Rows.Count == 0)
compiledExpression.Eval (Table.NewRow ());
else
compiledExpression.Eval (Table.Rows [0]);
}
ReadOnly = true;
_compiledExpression = compiledExpression;
} else {
_compiledExpression = null;
if (Table != null) {
int defaultValuesRowIndex = Table.DefaultValuesRowIndex;
if (defaultValuesRowIndex != -1)
DataContainer.FillValues (defaultValuesRowIndex);
if (Table != null) {
for (int i = 0; i < Table.Constraints.Count; i++) {
if (Table.Constraints [i].IsColumnContained (this))
throw new ArgumentException (
String.Format (
"Cannot set Expression property on column {0}, because it is a part of a constraint.",
ColumnName));
}
}
_expression = value;
Parser parser = new Parser ();
IExpression compiledExpression = parser.Compile (expression);
if (Table != null) {
if (compiledExpression.DependsOn (this))
throw new ArgumentException ("Cannot set Expression property due to circular reference in the expression.");
// Check if expression is ok
if (Table.Rows.Count == 0)
compiledExpression.Eval (Table.NewRow ());
else
compiledExpression.Eval (Table.Rows [0]);
}
ReadOnly = true;
_compiledExpression = compiledExpression;
} else {
_compiledExpression = null;
if (Table != null) {
int defaultValuesRowIndex = Table.DefaultValuesRowIndex;
if (defaultValuesRowIndex != -1)
DataContainer.FillValues (defaultValuesRowIndex);
}
}
}
@@ -701,16 +712,12 @@ namespace System.Data {
//Copy.Container
copy.DataType = DataType;
copy._defaultValue = _defaultValue;
// Use the property to set the expression as it updates compiledExpression, if any.
copy.Expression = _expression;
// Do not use the Expression property to set the expression, the caller of Clone
// must explicitly call CompileExpression on the returned DataColumn to update compiledExpression (if any).
copy._expression = _expression;
//Copy.ExtendedProperties
if (_extendedProperties.Count > 0) {
Array extPropArray = Array.CreateInstance (typeof (object), _extendedProperties.Count);
_extendedProperties.CopyTo (extPropArray, 0);
for (var i = 0; i < _extendedProperties.Count; i++)
copy.ExtendedProperties.Add (extPropArray.GetValue(i),
ExtendedProperties[extPropArray.GetValue(i)]);
}
foreach (object key in _extendedProperties.Keys)
copy.ExtendedProperties.Add (key, ExtendedProperties[key]);
copy._maxLength = _maxLength;
copy._nameSpace = _nameSpace;
copy._prefix = _prefix;
@@ -880,6 +880,8 @@ namespace System.Data {
if (isEmpty || !Copy.Columns.Contains (column.ColumnName))
Copy.Columns.Add (column.Clone ());
}
foreach (DataColumn column in Copy.Columns)
column.CompileExpression ();
CopyConstraints (Copy);
// add primary key to the copy
@@ -351,6 +351,7 @@ namespace System.Data {
DataTable GetTable (string name)
{
name = XmlConvert.DecodeName (name);
if (DSet != null)
return DSet.Tables [name];
else if (name == table.TableName)
@@ -10,9 +10,10 @@
// (C) Copyright 2002 Rodrigo Moya
// (C) Copyright 2003 Daniel Morgan
// (C) Copyright 2003 Martin Willemoes Hansen
//
// (C) Copyright 2011 Xamarin Inc
//
// Copyright 2011 Xamarin Inc (http://www.xamarin.com)
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
@@ -913,5 +914,46 @@ namespace MonoTests.System.Data
Assert.Fail ("SetOrdinalTest failed");
}
}
[Test]
public void Xamarin665 ()
{
var t = new DataTable() ;
var c1 = t.Columns.Add ("c1");
var c2 = t.Columns.Add ("c2");
c2.Expression = "TRIM(ISNULL(c1,' '))";
c2.Expression = "SUBSTRING(ISNULL(c1,' '), 1, 10)";
}
DataColumn MakeColumn (string col, string test)
{
return new DataColumn () {
ColumnName = col,
Expression = test
};
}
#if false
// Check Windows output for the row [0] value
[Test]
public void NullStrings ()
{
var a = MakeColumn ("nullbar", "null+'bar'");
var b = MakeColumn ("barnull", "'bar'+null");
var c = MakeColumn ("foobar", "'foo'+'bar'");
var table = new DataTable();
table.Columns.Add(a);
table.Columns.Add(b);
table.Columns.Add(c);
var row = table.NewRow();
table.Rows.Add(row);
Assert.AreEqual (row [0], DBNull.Value, "#1");
Assert.AreEqual (row [1], DBNull.Value, "#2");
Assert.AreEqual (row [2], "foobar", "#3");
}
#endif
}
}
@@ -2563,6 +2563,30 @@ namespace MonoTests.System.Data
Assert.AreEqual (2, dsLoad.Tables[2].Columns.Count, "T3-Columns");
}
[Test]
public void ReadDiff ()
{
DataSet dsTest = new DataSet ("MonoTouchTest");
var dt = new DataTable ("123");
dt.Columns.Add (new DataColumn ("Value1"));
dt.Columns.Add (new DataColumn ("Value2"));
dsTest.Tables.Add (dt);
dsTest.ReadXml (new StringReader (@"
<diffgr:diffgram
xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'
xmlns:diffgr='urn:schemas-microsoft-com:xml-diffgram-v1'>
<MonoTouchTest>
<_x0031_23 diffgr:id='1231' msdata:rowOrder='0'>
<Value1>Row1Value1</Value1>
<Value2>Row1Value2</Value2>
</_x0031_23>
</MonoTouchTest>
</diffgr:diffgram>
"));
Assert.AreEqual ("123", dsTest.Tables [0].TableName, "#1");
Assert.AreEqual (1, dsTest.Tables [0].Rows.Count, "#2");
}
private void CompareTables (DataSet dsLoad) {
Assert.AreEqual (ds.Tables.Count, dsLoad.Tables.Count, "NumTables");
for (int tc = 0; tc < dsLoad.Tables.Count; tc++) {
@@ -11,6 +11,7 @@
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
// Copyright (C) 2011 Xamarin Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -1043,6 +1044,43 @@ namespace MonoTests.System.Data
Assert.AreEqual ("Table#1", copyTable.TableName, "#A30");
}
[Test]
public void CloneExtendedProperties ()
{
// bug 668
DataTable t1 = new DataTable ("t1");
DataColumn c1 = t1.Columns.Add ("c1");
c1.ExtendedProperties.Add ("Company", "Xamarin");
DataTable t2 = t1.Clone ();
Assert.AreEqual ("Xamarin", t1.Columns["c1"].ExtendedProperties["Company"], "CEP1");
Assert.AreEqual ("Xamarin", t2.Columns["c1"].ExtendedProperties["Company"], "CEP2");
}
[Test]
[ExpectedException (typeof (EvaluateException))]
public void CloneExtendedProperties1 ()
{
// Xamarin bug 666
DataTable table1 = new DataTable("Table1") ;
DataColumn c1 = table1.Columns.Add("c1", typeof(string), "'hello ' + c2") ; /* Should cause an exception */
}
[Test]
public void CloneExtendedProperties2 ()
{
// Xamarin bug 666
DataTable table1 = new DataTable("Table1") ;
DataColumn c1 = table1.Columns.Add("c1") ;
DataColumn c2 = table1.Columns.Add("c2") ;
c1.Expression = "'hello ' + c2";
DataTable t2 = table1.Clone(); // this should not cause an exception
}
[Test]
public void LoadDataException ()
{
@@ -3,8 +3,10 @@
//
// Author:
// Atsushi Enomoto <[email protected]>
// Atsushi Enomoto <[email protected]>
//
// Copyright (C) 2008,2009 Novell, Inc (http://www.novell.com)
// Copyright (C) 2011 Xamarin, Inc (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -45,6 +47,24 @@ using XmlObjectSerializer = System.Object;
namespace System.ServiceModel.Dispatcher
{
// This set of classes is to work as message formatters for
// WebHttpBehavior. There are couple of aspects to differentiate
// implementations:
// - request/reply and client/server
// by WebMessageFormatter hierarchy
// - WebClientMessageFormatter - for client
// - RequestClientFormatter - for request
// - ReplyClientFormatter - for response
// - WebDispatchMessageFormatter - for server
// - RequestDispatchFormatter - for request
// - ReplyDispatchFormatter - for response
//
// FIXME: below items need more work
// - HTTP method differences
// - GET (WebGet)
// - POST (other way)
// - output format: Stream, JSON, XML ...
internal abstract class WebMessageFormatter
{
OperationDescription operation;
@@ -182,6 +202,9 @@ namespace System.ServiceModel.Dispatcher
protected XmlObjectSerializer GetSerializer (WebContentFormat msgfmt, bool isWrapped, MessagePartDescription part)
{
if (part.Type == typeof (void))
return null; // no serialization should be done.
switch (msgfmt) {
case WebContentFormat.Xml:
if (xml_serializer == null)
@@ -208,6 +231,9 @@ namespace System.ServiceModel.Dispatcher
// FIXME: handle ref/out parameters
var reader = message.GetReaderAtBodyContents ();
reader.MoveToContent ();
bool wasEmptyElement = reader.IsEmptyElement;
if (isWrapped) {
if (fmt == WebContentFormat.Json)
@@ -216,9 +242,9 @@ namespace System.ServiceModel.Dispatcher
reader.ReadStartElement (md.Body.WrapperName, md.Body.WrapperNamespace);
}
var ret = ReadObjectBody (serializer, reader);
var ret = (serializer == null) ? null : ReadObjectBody (serializer, reader);
if (isWrapped)
if (isWrapped && !wasEmptyElement)
reader.ReadEndElement ();
return ret;
@@ -291,6 +317,8 @@ namespace System.ServiceModel.Dispatcher
internal abstract class WebClientMessageFormatter : WebMessageFormatter, IClientMessageFormatter
{
IClientMessageFormatter default_formatter;
protected WebClientMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
: base (operation, endpoint, converter, behavior)
{
@@ -306,11 +334,11 @@ namespace System.ServiceModel.Dispatcher
MessageDescription md = GetMessageDescription (MessageDirection.Input);
if (parameters.Length != md.Body.Parts.Count)
throw new ArgumentException ("Parameter array length does not match the number of message body parts");
Message ret;
Uri to;
object msgpart = null;
for (int i = 0; i < parameters.Length; i++) {
var p = md.Body.Parts [i];
string name = p.Name.ToUpper (CultureInfo.InvariantCulture);
@@ -325,10 +353,9 @@ namespace System.ServiceModel.Dispatcher
throw new NotImplementedException (String.Format ("More than one parameters including {0} that are not contained in the URI template {1} was found.", p.Name, UriTemplate));
}
}
ret = Message.CreateMessage (messageVersion, (string) null, msgpart);
Uri to = UriTemplate.BindByName (Endpoint.Address.Uri, c);
Message ret = Message.CreateMessage (messageVersion, (string) null, msgpart);
to = UriTemplate.BindByName (Endpoint.Address.Uri, c);
ret.Headers.To = to;
var hp = new HttpRequestMessageProperty ();
@@ -546,11 +573,8 @@ namespace System.ServiceModel.Dispatcher
var fmt = wp != null ? wp.Format : WebContentFormat.Xml;
Uri to = message.Headers.To;
UriTemplateMatch match = UriTemplate.Match (Endpoint.Address.Uri, to);
if (match == null)
// not sure if it could happen
throw new SystemException (String.Format ("INTERNAL ERROR: UriTemplate does not match with the request: {0} / {1}", UriTemplate, to));
if (iwc != null)
UriTemplateMatch match = to == null ? null : UriTemplate.Match (Endpoint.Address.Uri, to);
if (match != null && iwc != null)
iwc.UriTemplateMatch = match;
MessageDescription md = GetMessageDescription (MessageDirection.Input);
@@ -558,15 +582,20 @@ namespace System.ServiceModel.Dispatcher
for (int i = 0; i < parameters.Length; i++) {
var p = md.Body.Parts [i];
string name = p.Name.ToUpperInvariant ();
var str = match.BoundVariables [name];
if (str != null)
parameters [i] = Converter.ConvertStringToValue (str, p.Type);
else if (fmt == WebContentFormat.Raw && p.Type == typeof (Stream)) {
if (fmt == WebContentFormat.Raw && p.Type == typeof (Stream)) {
var rmsg = (RawMessage) message;
parameters [i] = rmsg.Stream;
} else {
var serializer = GetSerializer (fmt, IsRequestBodyWrapped, p);
parameters [i] = DeserializeObject (serializer, message, md, IsRequestBodyWrapped, fmt);
var str = match.BoundVariables [name];
if (str != null)
parameters [i] = Converter.ConvertStringToValue (str, p.Type);
else {
if (info.Method != "GET") {
var serializer = GetSerializer (fmt, IsRequestBodyWrapped, p);
parameters [i] = DeserializeObject (serializer, message, md, IsRequestBodyWrapped, fmt);
}
// for GET Uri template parameters, there is no <anyType xsi:nil='true' />. So just skip the member.
}
}
}
}
@@ -163,6 +163,15 @@ namespace System
void BindByName (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults, bool query)
{
if (query) {
int idx = template.IndexOf ('?', src);
if (idx > 0) {
sb.Append (template.Substring (src, idx - src));
src = idx;
// note that it doesn't append '?'. It is added only when there is actual parameter binding.
}
}
foreach (string name in names) {
int s = template.IndexOf ('{', src);
int e = template.IndexOf ('}', s + 1);
@@ -173,18 +182,19 @@ namespace System
#endif
if (dic != null)
dic.TryGetValue (name, out value);
if (query) {
if (value != null || (!omitDefaults && Defaults.TryGetValue (name, out value))) {
sb.Append (template.Substring (src, s - src));
sb.Append (value);
}
} else
if (value == null && (omitDefaults || !Defaults.TryGetValue(name, out value)))
throw new ArgumentException(string.Format("The argument name value collection does not contain non-nul vaalue for '{0}'", name), "parameters");
else {
sb.Append (template.Substring (src, s - src));
sb.Append (value);
}
} else {
if (value == null && (omitDefaults || !Defaults.TryGetValue (name, out value)))
throw new ArgumentException (string.Format("The argument name value collection does not contain non-null value for '{0}'", name), "parameters");
sb.Append (template.Substring (src, s - src));
sb.Append (value);
}
src = e + 1;
}
}
@@ -0,0 +1,321 @@
//
// This code was partly auto-generated by slsvcutil, version 4.0.60310.0
//
namespace DHIWebService
{
using System.Runtime.Serialization;
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="ClientLoginData", Namespace="http://schemas.datacontract.org/2004/07/Domain.Models")]
public partial class ClientLoginData : object
{
private int CompanyNumberField;
private string InstitutionIdField;
private string PasswordField;
private string UserNameField;
[System.Runtime.Serialization.DataMemberAttribute()]
public int CompanyNumber
{
get
{
return this.CompanyNumberField;
}
set
{
this.CompanyNumberField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string InstitutionId
{
get
{
return this.InstitutionIdField;
}
set
{
this.InstitutionIdField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public string Password
{
get
{
return this.PasswordField;
}
set
{
this.PasswordField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public string UserName
{
get
{
return this.UserNameField;
}
set
{
this.UserNameField = value;
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="Login", Namespace="http://schemas.datacontract.org/2004/07/Domain.Models")]
public partial class Login : object
{
private int CompanyNumberField;
private string InstitutionIdField;
private string PasswordField;
private string UserNameField;
[System.Runtime.Serialization.DataMemberAttribute()]
public int CompanyNumber
{
get
{
return this.CompanyNumberField;
}
set
{
this.CompanyNumberField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string InstitutionId
{
get
{
return this.InstitutionIdField;
}
set
{
this.InstitutionIdField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public string Password
{
get
{
return this.PasswordField;
}
set
{
this.PasswordField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public string UserName
{
get
{
return this.UserNameField;
}
set
{
this.UserNameField = value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(Namespace="IBEWebSvc", ConfigurationName="DHIWebService.IDHIService")]
public interface IDHIService
{
[System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="IBEWebSvc/IDHIService/Login", ReplyAction="IBEWebSvc/IDHIService/LoginResponse")]
// FIXME: uncommenting this results in cryptic error message. We should tell what could be wrong here.
// [System.ServiceModel.Web.WebInvoke(BodyStyle=System.ServiceModel.Web.WebMessageBodyStyle.Wrapped)]
System.IAsyncResult BeginLogin(DHIWebService.LoginRequest request, System.AsyncCallback callback, object asyncState);
DHIWebService.LoginResponse EndLogin(System.IAsyncResult result);
[System.ServiceModel.OperationContractAttribute(Action="IBEWebSvc/IDHIService/Login", ReplyAction="IBEWebSvc/IDHIService/LoginResponse")]
[System.ServiceModel.Web.WebInvoke(BodyStyle=System.ServiceModel.Web.WebMessageBodyStyle.Wrapped)]
DHIWebService.LoginResponse Login(DHIWebService.LoginRequest request);
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.MessageContractAttribute(WrapperName="Login", WrapperNamespace="IBEWebSvc", IsWrapped=true)]
public partial class LoginRequest
{
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="IBEWebSvc", Order=0)]
public DHIWebService.ClientLoginData clientLoginData;
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="IBEWebSvc", Order=1)]
public DHIWebService.Login credentials;
public LoginRequest()
{
}
public LoginRequest(DHIWebService.ClientLoginData clientLoginData, DHIWebService.Login credentials)
{
this.clientLoginData = clientLoginData;
this.credentials = credentials;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.MessageContractAttribute(WrapperName="LoginResponse", WrapperNamespace="IBEWebSvc", IsWrapped=true)]
public partial class LoginResponse
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface IDHIServiceChannel : DHIWebService.IDHIService, System.ServiceModel.IClientChannel
{
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class LoginCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
public LoginCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState)
{
this.results = results;
}
public DHIWebService.LoginResponse Result
{
get
{
base.RaiseExceptionIfNecessary();
return ((DHIWebService.LoginResponse)(this.results[0]));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class DHIServiceClient : System.ServiceModel.ClientBase<DHIWebService.IDHIService>, DHIWebService.IDHIService
{
private BeginOperationDelegate onBeginLoginDelegate;
private EndOperationDelegate onEndLoginDelegate;
private System.Threading.SendOrPostCallback onLoginCompletedDelegate;
public DHIServiceClient()
{
}
public DHIServiceClient(string endpointConfigurationName) :
base(endpointConfigurationName)
{
}
public DHIServiceClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress)
{
}
public DHIServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress)
{
}
public DHIServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress)
{
}
public event System.EventHandler<LoginCompletedEventArgs> LoginCompleted;
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
System.IAsyncResult DHIWebService.IDHIService.BeginLogin(DHIWebService.LoginRequest request, System.AsyncCallback callback, object asyncState)
{
return base.Channel.BeginLogin(request, callback, asyncState);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
DHIWebService.LoginResponse DHIWebService.IDHIService.EndLogin(System.IAsyncResult result)
{
return base.Channel.EndLogin(result);
}
private System.IAsyncResult OnBeginLogin(object[] inValues, System.AsyncCallback callback, object asyncState)
{
DHIWebService.LoginRequest request = ((DHIWebService.LoginRequest)(inValues[0]));
return ((DHIWebService.IDHIService)(this)).BeginLogin(request, callback, asyncState);
}
private object[] OnEndLogin(System.IAsyncResult result)
{
DHIWebService.LoginResponse retVal = ((DHIWebService.IDHIService)(this)).EndLogin(result);
return new object[] {
retVal};
}
private void OnLoginCompleted(object state)
{
if ((this.LoginCompleted != null))
{
InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
this.LoginCompleted(this, new LoginCompletedEventArgs(e.Results, e.Error, e.Cancelled, e.UserState));
}
}
public void LoginAsync(DHIWebService.LoginRequest request)
{
this.LoginAsync(request, null);
}
public void LoginAsync(DHIWebService.LoginRequest request, object userState)
{
if ((this.onBeginLoginDelegate == null))
{
this.onBeginLoginDelegate = new BeginOperationDelegate(this.OnBeginLogin);
}
if ((this.onEndLoginDelegate == null))
{
this.onEndLoginDelegate = new EndOperationDelegate(this.OnEndLogin);
}
if ((this.onLoginCompletedDelegate == null))
{
this.onLoginCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnLoginCompleted);
}
base.InvokeAsync(this.onBeginLoginDelegate, new object[] {
request}, this.onEndLoginDelegate, this.onLoginCompletedDelegate, userState);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
DHIWebService.LoginResponse DHIWebService.IDHIService.Login (DHIWebService.LoginRequest request)
{
return base.Channel.Login(request);
}
}
}
@@ -241,7 +241,6 @@ namespace MonoTests.System.ServiceModel.Description
var se = new ServiceEndpoint (cd, new WebHttpBinding (), new EndpointAddress ("http://localhost:8080/"));
var wmebe = new WebMessageEncodingBindingElement ();
var wme = wmebe.CreateMessageEncoderFactory ().Encoder;
Console.WriteLine (wme.MediaType);
var msg = wme.ReadMessage (ms, 100, null); // "application/xml" causes error.
var formatter = new WebHttpBehaviorExt ().DoGetRequestDispatchFormatter (od, se);
object [] pars = new object [1];
@@ -256,6 +256,7 @@ namespace MonoTests.System.ServiceModel.Dispatcher
{
var host = new WebServiceHost (typeof (Hello));
host.AddServiceEndpoint (typeof (IHello), new WebHttpBinding (), "http://localhost:37564/");
host.Description.Behaviors.Find<ServiceDebugBehavior> ().IncludeExceptionDetailInFaults = true;
host.Open ();
try {
// run client
@@ -228,6 +228,15 @@ namespace MonoTests.System
Assert.AreEqual ("http://localhost/x/value2/value1", u.ToString ());
}
[Test]
public void BindByName3 ()
{
var t = new UriTemplate ("Login?clientLoginData={clientLoginData}&credentials={credentials}");
var n = new NameValueCollection ();
var u = t.BindByName (new Uri ("http://localhost"), n);
Assert.AreEqual ("http://localhost/Login", u.ToString (), "#1");
}
[Test]
public void BindByNameManySlashes ()
{
@@ -3,8 +3,10 @@
//
// Author:
// Atsushi Enomoto <[email protected]>
// Atsushi Enomoto <[email protected]>
//
// Copyright (C) 2005-2007 Novell, Inc. http://www.novell.com
// Copyright (C) 2011 Xamarin, Inc. http://xamarin.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -413,9 +415,21 @@ namespace System.ServiceModel.Description
cd.Namespace.Length == 0 ? "urn:" : cd.Namespace.EndsWith ("/") ? "" : "/", cd.Name, "/",
od.Name, isRequest ? String.Empty : "Response");
MessageDescription md;
if (mca != null)
return CreateMessageDescription (messageType, cd.Namespace, action, isRequest, isCallback, mca);
return CreateMessageDescription (oca, plist, od.Name, cd.Namespace, action, isRequest, isCallback, retType, mi.ReturnTypeCustomAttributes);
md = CreateMessageDescription (messageType, cd.Namespace, action, isRequest, isCallback, mca);
else
md = CreateMessageDescription (oca, plist, od.Name, cd.Namespace, action, isRequest, isCallback, retType);
// ReturnValue
if (!isRequest) {
MessagePartDescription mp = CreatePartCore (GetMessageParameterAttribute (mi.ReturnTypeCustomAttributes), od.Name + "Result", md.Body.WrapperNamespace);
mp.Index = 0;
mp.Type = mca != null ? typeof (void) : retType;
md.Body.ReturnValue = mp;
}
return md;
}
public static MessageDescription CreateMessageDescription (
@@ -456,6 +470,13 @@ namespace System.ServiceModel.Description
pd.MemberInfo = bmi;
md.Headers.Add (pd);
}
var mpa = bmi.GetCustomAttribute<MessagePropertyAttribute> (false);
if (mpa != null) {
var pd = new MessagePropertyDescription (mpa.Name ?? mname);
pd.Type = MessageFilterOutByRef (mtype);
pd.MemberInfo = bmi;
md.Properties.Add (pd);
}
var mba = GetMessageBodyMemberAttribute (bmi);
if (mba != null) {
var pd = CreatePartCore (mba, mname, defaultNamespace);
@@ -467,12 +488,11 @@ namespace System.ServiceModel.Description
}
}
// FIXME: fill headers and properties.
return md;
}
public static MessageDescription CreateMessageDescription (
OperationContractAttribute oca, ParameterInfo[] plist, string name, string defaultNamespace, string action, bool isRequest, bool isCallback, Type retType, ICustomAttributeProvider retTypeAttributes)
OperationContractAttribute oca, ParameterInfo[] plist, string name, string defaultNamespace, string action, bool isRequest, bool isCallback, Type retType)
{
var dir = isRequest ^ isCallback ? MessageDirection.Input : MessageDirection.Output;
MessageDescription md = new MessageDescription (action, dir) { IsRequest = isRequest };
@@ -505,16 +525,6 @@ namespace System.ServiceModel.Description
mb.Parts.Add (pd);
}
// ReturnValue
if (!isRequest) {
MessagePartDescription mp = CreatePartCore (GetMessageParameterAttribute (retTypeAttributes), name + "Result", mb.WrapperNamespace);
mp.Index = 0;
mp.Type = retType;
mb.ReturnValue = mp;
}
// FIXME: fill properties.
return md;
}
@@ -306,8 +306,9 @@ namespace System.ServiceModel.Dispatcher
foreach (MessagePartDescription partDesc in l)
if (partDesc.MemberInfo is FieldInfo)
((FieldInfo) partDesc.MemberInfo).SetValue (msgObject, parts [partDesc.Index]);
else
else if (partDesc.MemberInfo is PropertyInfo)
((PropertyInfo) partDesc.MemberInfo).SetValue (msgObject, parts [partDesc.Index], null);
// otherwise, it could be null (in case of undefined return value in MessageContract)
}
void MessageObjectToParts (MessageDescription md, object msgObject, Dictionary<MessageHeaderDescription,object> headers, object [] parts)
@@ -68,8 +68,12 @@ namespace System.ServiceModel.Dispatcher
public override bool Match (Message message)
{
Uri to = message.Headers.To;
bool path = ((CultureInfo.InvariantCulture.CompareInfo.IsPrefix (to.AbsolutePath, address.Uri.AbsolutePath, CompareOptions.Ordinal)) &&
(to.Port == address.Uri.Port));
if (to == null)
return false;
if (to.ToString () == Constants.WsaAnonymousUri || to.Equals (EndpointAddress.AnonymousUri) || to.Equals (EndpointAddress.NoneUri))
return true;
bool path = CultureInfo.InvariantCulture.CompareInfo.IsPrefix (to.AbsolutePath, address.Uri.AbsolutePath, CompareOptions.Ordinal);
bool host = IncludeHostNameInComparison
? (String.CompareOrdinal (to.Host, address.Uri.Host) == 0)
: true;
@@ -7,6 +7,7 @@
//
// Copyright (C) 2005-2010 Novell, Inc. http://www.novell.com
// Copyright (C) 2008 Mainsoft Co. http://www.mainsoft.com
// Copyright (C) 2011 Xamarin Inc. http://www.xamarin.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -65,7 +66,7 @@ namespace System.ServiceModel.Dispatcher
m.IsReturnValue = isReturnValue;
m.MemberName = partDesc.Name;
m.MemberType = partDesc.Type;
m.XmlAttributes = new XmlAttributes(partDesc.MemberInfo);
m.XmlAttributes = partDesc.MemberInfo == null ? new XmlAttributes () : new XmlAttributes (partDesc.MemberInfo);
return m;
}
@@ -273,43 +273,26 @@ namespace System.ServiceModel
h.ExtendedProtectionPolicy = Security.Transport.ExtendedProtectionPolicy;
#endif
#if !NET_2_1
switch (Security.Mode) {
case BasicHttpSecurityMode.Transport:
switch (Security.Transport.ClientCredentialType) {
case HttpClientCredentialType.Basic:
h.AuthenticationScheme = AuthenticationSchemes.Basic;
break;
case HttpClientCredentialType.Ntlm:
h.AuthenticationScheme = AuthenticationSchemes.Ntlm;
break;
case HttpClientCredentialType.Windows:
h.AuthenticationScheme = AuthenticationSchemes.Negotiate;
break;
case HttpClientCredentialType.Digest:
h.AuthenticationScheme = AuthenticationSchemes.Digest;
break;
case HttpClientCredentialType.Certificate:
var https = (HttpsTransportBindingElement) h;
https.RequireClientCertificate = true;
break;
}
#if !NET_2_1 || MOBILE
switch (Security.Transport.ClientCredentialType) {
case HttpClientCredentialType.Basic:
h.AuthenticationScheme = AuthenticationSchemes.Basic;
break;
case BasicHttpSecurityMode.TransportCredentialOnly:
switch (Security.Transport.ClientCredentialType) {
case HttpClientCredentialType.Basic:
h.AuthenticationScheme = AuthenticationSchemes.Basic;
case HttpClientCredentialType.Ntlm:
h.AuthenticationScheme = AuthenticationSchemes.Ntlm;
break;
case HttpClientCredentialType.Windows:
h.AuthenticationScheme = AuthenticationSchemes.Negotiate;
break;
case HttpClientCredentialType.Digest:
h.AuthenticationScheme = AuthenticationSchemes.Digest;
break;
case HttpClientCredentialType.Certificate:
switch (Security.Mode) {
case BasicHttpSecurityMode.Transport:
(h as HttpsTransportBindingElement).RequireClientCertificate = true;
break;
case HttpClientCredentialType.Ntlm:
h.AuthenticationScheme = AuthenticationSchemes.Ntlm;
break;
case HttpClientCredentialType.Windows:
h.AuthenticationScheme = AuthenticationSchemes.Negotiate;
break;
case HttpClientCredentialType.Digest:
h.AuthenticationScheme = AuthenticationSchemes.Digest;
break;
case HttpClientCredentialType.Certificate:
case BasicHttpSecurityMode.TransportCredentialOnly:
throw new InvalidOperationException ("Certificate-based client authentication is not supported by 'TransportCredentialOnly' mode.");
}
break;
@@ -25,6 +25,9 @@
// 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 !MOONLIGHT
using System;
using System.Net.Security;
using System.ServiceModel.Security;
@@ -37,14 +40,16 @@ namespace System.ServiceModel
internal BasicHttpMessageSecurity ()
{
}
#if !MOBILE
SecurityAlgorithmSuite alg = SecurityAlgorithmSuite.Default;
BasicHttpMessageCredentialType ctype;
public SecurityAlgorithmSuite AlgorithmSuite {
get { return alg; }
set { alg = value; }
}
#endif
BasicHttpMessageCredentialType ctype;
public BasicHttpMessageCredentialType ClientCredentialType {
get { return ctype; }
@@ -52,3 +57,5 @@ namespace System.ServiceModel
}
}
}
#endif
@@ -183,7 +183,9 @@ namespace System.ServiceModel
xw.WriteEndAttribute ();
xw.WriteAttributeString ("Source", log.Source.ToString ());
xw.WriteAttributeString ("Type", log.Type.FullName);
log.Message.CreateMessage ().WriteMessage (xw);
var msg = log.Message.CreateMessage ();
if (!msg.IsEmpty)
msg.WriteMessage (xw);
xw.WriteEndElement ();
xw.Close ();
@@ -5,6 +5,7 @@
// Atsushi Enomoto <[email protected]>
//
// Copyright (C) 2005 Novell, Inc. http://www.novell.com
// Copyright (C) 2011 Xamarin, Inc. http://xamarin.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -555,6 +556,24 @@ namespace MonoTests.System.ServiceModel.Description
Assert.IsNotNull (md.Body.ReturnValue, od.Name);
}
[Test]
public void BugX206Contract ()
{
var cd = ContractDescription.GetContract (typeof (BugX206Service));
bool examined = false;
foreach (var md in cd.Operations.First ().Messages) {
if (md.Direction == MessageDirection.Input)
continue;
var pd = md.Body.ReturnValue;
Assert.IsNotNull (pd, "#1");
Assert.AreEqual ("DoWorkResult", pd.Name, "#2");
Assert.IsNull (pd.MemberInfo, "#3");
Assert.AreEqual (typeof (void), pd.Type, "#4");
examined = true;
}
Assert.IsTrue (examined, "end");
}
// It is for testing attribute search in interfaces.
public class Foo : IFoo
{
@@ -916,5 +935,18 @@ namespace MonoTests.System.ServiceModel.Description
[XmlSerializerFormat]
string Echo (string input);
}
[ServiceContract]
public interface BugX206Service
{
[OperationContract]
BugX206Response DoWork ();
}
[MessageContract (IsWrapped = true)]
public partial class BugX206Response
{
}
}
}
@@ -54,7 +54,6 @@ namespace MonoTests.System.ServiceModel.Dispatcher
}
[Test]
[Category ("NotWorking")]
public void Match ()
{
PrefixEndpointAddressMessageFilter f =
@@ -173,7 +173,8 @@ System.ServiceModel.Security/UserNamePasswordClientCredential.cs
System.ServiceModel/ActionNotSupportedException.cs
System.ServiceModel/AllEnums.cs
System.ServiceModel/BasicHttpBinding.cs
System.ServiceModel/BasicHttpSecurity_2_1.cs
System.ServiceModel/BasicHttpSecurity.cs
System.ServiceModel/BasicHttpMessageSecurity.cs
System.ServiceModel/ChannelFactory.cs
System.ServiceModel/ChannelFactory_1.cs
System.ServiceModel/ClientBase.cs
@@ -200,6 +201,7 @@ System.ServiceModel/FaultException.cs
System.ServiceModel/FaultException_1.cs
System.ServiceModel/FaultReason.cs
System.ServiceModel/FaultReasonText.cs
System.ServiceModel/HttpTransportSecurity.cs
System.ServiceModel/IClientChannel.cs
System.ServiceModel/ICommunicationObject.cs
System.ServiceModel/IContextChannel.cs
@@ -146,13 +146,15 @@ namespace System.Web.Compilation
if (NeedsLoadFromBin && _compiler != null)
return LoadTypeFromBin (_compiler, Parser);
// This is not called if compilation failed.
// Returning null makes the caller throw an InvalidCastException
Type type = null;
Assembly assembly = results != null ? results.CompiledAssembly : null;
if (assembly == null)
return null;
return assembly.GetType (GetClassType (_compiler, Parser));
if (assembly != null) {
type = assembly.GetType (GetClassType (_compiler, Parser));
}
if (type == null) {
throw new HttpException (500, String.Format ("Type {0} could not be loaded", GetClassType (_compiler, Parser)));
}
return type;
}
// This is intended to be used by builders which may need to do special processing
+2 -2
View File
@@ -77,14 +77,14 @@ EXTRA_DISTFILES = \
$(nist_dom_files:%=Test/System.Xml/nist_dom/%)
System.Xml.XPath/Parser.cs: System.Xml.XPath/Parser.jay $(topdir)/jay/skeleton.cs
$(topdir)/jay/jay -ct < $(topdir)/jay/skeleton.cs $< >$@
$(topdir)/jay/jay -ct < $(topdir)/jay/skeleton.cs $(CURDIR)/$< >$@
Mono.Xml.Xsl/PatternParser.jay: System.Xml.XPath/Parser.jay $(topdir)/jay/skeleton.cs
sed "s/\%start Expr/\%start Pattern/" $< >$@
Mono.Xml.Xsl/PatternParser.cs: Mono.Xml.Xsl/PatternParser.jay $(topdir)/jay/skeleton.cs
echo "#define XSLT_PATTERN" > $@
$(topdir)/jay/jay -ct $< < $(topdir)/jay/skeleton.cs >>$@
$(topdir)/jay/jay -ct $(CURDIR)/$< < $(topdir)/jay/skeleton.cs >>$@
Mono.Xml.Xsl/PatternTokenizer.cs: System.Xml.XPath/Tokenizer.cs
echo "#define XSLT_PATTERN" > $@
@@ -578,6 +578,10 @@ namespace Mono.Xml.XPath
namespaces [nsIndex].Name = name;
namespaces [nsIndex].Namespace = ns;
namespaces [nsIndex].NextNamespace = nextNs;
if (lineInfo != null && lineInfo.HasLineInfo ()) {
namespaces [nsIndex].LineNumber = lineInfo.LineNumber;
namespaces [nsIndex].LinePosition = lineInfo.LinePosition;
}
}
}
}
@@ -118,14 +118,16 @@ namespace Mono.Xml.XPath
int IXmlLineInfo.LineNumber {
get {
return currentIsAttr ? attributes [currentAttr].LineNumber :
nodes [currentNode].LineNumber;
currentIsNode ? nodes [currentNode].LineNumber :
namespaces [currentNs].LineNumber;
}
}
int IXmlLineInfo.LinePosition {
get {
return currentIsAttr ? attributes [currentAttr].LinePosition :
nodes [currentNode].LinePosition;
currentIsNode ? nodes [currentNode].LinePosition :
namespaces [currentNs].LinePosition;
}
}
@@ -100,5 +100,7 @@ namespace Mono.Xml.XPath
public int NextNamespace;
public int Name;
public int Namespace;
public int LineNumber;
public int LinePosition;
}
}
@@ -111,13 +111,13 @@ namespace System.Xml
public XmlTextReader (string url, XmlNameTable nt)
{
string uriString;
Stream stream = GetStreamFromUrl (url, out uriString);
reader_uri = resolver.ResolveUri (null, url);
string uriString = (reader_uri == null) ? String.Empty : reader_uri.ToString ();
XmlParserContext ctx = new XmlParserContext (nt,
new XmlNamespaceManager (nt),
String.Empty,
XmlSpace.None);
this.InitializeContext (uriString, ctx, new XmlStreamReader (stream), XmlNodeType.Document);
this.InitializeContext (uriString, ctx, null, XmlNodeType.Document);
}
public XmlTextReader (TextReader input, XmlNameTable nt)
@@ -138,6 +138,7 @@ namespace System.Xml
}
this.XmlResolver = resolver;
string uriString;
Stream stream = GetStreamFromUrl (url, out uriString);
this.InitializeContext (uriString, context, new XmlStreamReader (stream), fragType);
}
@@ -180,7 +181,12 @@ namespace System.Xml
InitializeContext (url, context, fragment, fragType);
}
private Stream GetStreamFromUrl (string url, out string absoluteUriString)
Uri ResolveUri (string url)
{
return resolver.ResolveUri (null, url);
}
Stream GetStreamFromUrl (string url, out string absoluteUriString)
{
#if NET_2_1
if (url == null)
@@ -188,7 +194,7 @@ namespace System.Xml
if (url.Length == 0)
throw new ArgumentException ("url");
#endif
Uri uri = resolver.ResolveUri (null, url);
Uri uri = ResolveUri (url);
absoluteUriString = uri != null ? uri.ToString () : String.Empty;
return resolver.GetEntity (uri, null, typeof (Stream)) as Stream;
}
@@ -928,6 +934,7 @@ namespace System.Xml
private StringBuilder valueBuffer;
Uri reader_uri;
private TextReader reader;
private char [] peekChars;
private int peekCharsIndex;
@@ -1239,6 +1246,12 @@ namespace System.Xml
private bool ReadTextReader (int remained)
{
if (reader == null && reader_uri != null) {
Uri uri = reader_uri;
reader_uri = null;
string uriString;
reader = new XmlStreamReader (GetStreamFromUrl (uri.ToString (), out uriString));
}
if (peekCharsLength < 0) { // initialized buffer
peekCharsLength = reader.Read (peekChars, 0, peekChars.Length);
return peekCharsLength > 0;
@@ -31,7 +31,7 @@ using XPI = System.Xml.Linq.XProcessingInstruction;
namespace System.Xml.Linq
{
internal class XNodeReader : XmlReader
internal class XNodeReader : XmlReader, IXmlLineInfo
{
ReadState state = ReadState.Initial;
XNode node, start;
@@ -46,6 +46,24 @@ namespace System.Xml.Linq
start = node;
}
int IXmlLineInfo.LineNumber {
get {
var o = (XObject) GetCurrentAttribute () ?? node;
return o != null ? o.LineNumber : 0;
}
}
int IXmlLineInfo.LinePosition {
get {
var o = (XObject) GetCurrentAttribute () ?? node;
return o != null ? o.LinePosition : 0;
}
}
bool IXmlLineInfo.HasLineInfo ()
{
var o = (XObject) GetCurrentAttribute () ?? node;
return o != null ? ((IXmlLineInfo) o).HasLineInfo () : false;
}
public override int AttributeCount {
get {
if (state != ReadState.Interactive || end_element)
@@ -182,9 +182,8 @@ namespace System.Collections.Generic
public void Clear ()
{
count = 0;
first = null;
version++;
while (first != null)
Remove (first);
}
public bool Contains (T value)
@@ -2,9 +2,10 @@
//
// Authors:
// Marek Habersack ([email protected])
// Gonzalo Paniagua Javier (gonzalo@novell.com)
// Gonzalo Paniagua Javier (gonzalo@xamarin.com)
//
// Copyright (c) 2008,2010 Novell, Inc. (http://www.novell.com)
// Copyright (c) 2011 Xamarin, Inc. (http://xamarin.com)
//
//
@@ -37,6 +38,8 @@ namespace System.Net.Sockets
{
public class SocketAsyncEventArgs : EventArgs, IDisposable
{
bool disposed;
int in_progress;
internal Socket.Worker Worker;
EndPoint remote_ep;
#if MOONLIGHT || NET_4_0
@@ -147,7 +150,11 @@ namespace System.Net.Sockets
void Dispose (bool disposing)
{
disposed = true;
if (disposing) {
if (disposed || Interlocked.CompareExchange (ref in_progress, 0, 0) != 0)
return;
if (Worker != null) {
Worker.Dispose ();
Worker = null;
@@ -171,6 +178,10 @@ namespace System.Net.Sockets
internal void SetLastOperation (SocketAsyncOperation op)
{
if (disposed)
throw new ObjectDisposedException ("System.Net.Sockets.SocketAsyncEventArgs");
if (Interlocked.Exchange (ref in_progress, 1) != 0)
throw new InvalidOperationException ("Operation already in progress");
LastOperation = op;
}
@@ -219,6 +230,8 @@ namespace System.Net.Sockets
static void DispatcherCB (IAsyncResult ares)
{
SocketAsyncEventArgs args = (SocketAsyncEventArgs) ares.AsyncState;
if (Interlocked.Exchange (ref args.in_progress, 0) != 1)
throw new InvalidOperationException ("No operation in progress");
SocketAsyncOperation op = args.LastOperation;
// Notes;
// -SocketOperation.AcceptReceive not used in SocketAsyncEventArgs
@@ -5,6 +5,7 @@
// Gonzalo Paniagua Javier ([email protected])
//
// (C) 2003 Ximian, Inc (http://www.ximian.com)
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
//
@@ -160,7 +161,7 @@ namespace System.Net
if (rnd == null)
rnd = new Random ();
int idx = (count > 1) ? rnd.Next (0, count - 1) : 0;
int idx = (count > 1) ? rnd.Next (0, count) : 0;
cncRef = (WeakReference) connections [idx];
cnc = cncRef.Target as WebConnection;
if (cnc == null) {
+6 -3
View File
@@ -246,10 +246,10 @@ namespace System.Net
[MonoTODO("Needs to respect Module, Proxy.AutoDetect, and Proxy.ScriptLocation config settings")]
static IWebProxy GetDefaultWebProxy ()
{
WebProxy p = null;
#if CONFIGURATION_DEP
DefaultProxySection sec = ConfigurationManager.GetSection ("system.net/defaultProxy") as DefaultProxySection;
WebProxy p;
if (sec == null)
return GetSystemWebProxy ();
@@ -265,8 +265,11 @@ namespace System.Net
if (pe.BypassOnLocal != ProxyElement.BypassOnLocalValues.Unspecified)
p.BypassProxyOnLocal = (pe.BypassOnLocal == ProxyElement.BypassOnLocalValues.True);
#endif
return p;
#else
return GetSystemWebProxy ();
#endif
}
#endif
@@ -6,6 +6,7 @@
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2006 Novell Inc. (http://www.novell.com)
// Copyright (C) 2011 Xamarin Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -601,7 +602,7 @@ namespace System.Security.Cryptography.X509Certificates {
// TODO 6.1.4.g-j
// 6.1.4.k - Verify that the certificate is a CA certificate
X509BasicConstraintsExtension bce = (X509BasicConstraintsExtension) certificate.Extensions["2.5.29.19"];
X509BasicConstraintsExtension bce = (certificate.Extensions["2.5.29.19"] as X509BasicConstraintsExtension);
if (bce != null) {
if (!bce.CertificateAuthority) {
element.StatusFlags |= X509ChainStatusFlags.InvalidBasicConstraints;
@@ -636,7 +637,7 @@ namespace System.Security.Cryptography.X509Certificates {
}
// 6.1.4.n - if key usage extension is present...
X509KeyUsageExtension kue = (X509KeyUsageExtension) certificate.Extensions["2.5.29.15"];
X509KeyUsageExtension kue = (certificate.Extensions["2.5.29.15"] as X509KeyUsageExtension);
if (kue != null) {
// ... verify keyCertSign is set
X509KeyUsageFlags success = X509KeyUsageFlags.KeyCertSign;
@@ -703,7 +704,7 @@ namespace System.Security.Cryptography.X509Certificates {
private string GetSubjectKeyIdentifier (X509Certificate2 certificate)
{
X509SubjectKeyIdentifierExtension ski = (X509SubjectKeyIdentifierExtension) certificate.Extensions["2.5.29.14"];
X509SubjectKeyIdentifierExtension ski = (certificate.Extensions["2.5.29.14"] as X509SubjectKeyIdentifierExtension);
return (ski == null) ? String.Empty : ski.SubjectKeyIdentifier;
}
@@ -816,7 +817,7 @@ namespace System.Security.Cryptography.X509Certificates {
private X509ChainStatusFlags CheckRevocation (X509Certificate2 certificate, X509Certificate2 ca_cert, bool online)
{
// change this if/when we support OCSP
X509KeyUsageExtension kue = (X509KeyUsageExtension) ca_cert.Extensions["2.5.29.15"];
X509KeyUsageExtension kue = (ca_cert.Extensions["2.5.29.15"] as X509KeyUsageExtension);
if (kue != null) {
// ... verify CrlSign is set
X509KeyUsageFlags success = X509KeyUsageFlags.CrlSign;
@@ -834,7 +835,7 @@ namespace System.Security.Cryptography.X509Certificates {
// crl = FindCrl (ca_cert, ref valid, ref out_of_date);
// We need to get the subjectAltName and an URI from there (or use OCSP)
// X509KeyUsageExtension subjectAltName = (X509KeyUsageExtension) ca_cert.Extensions["2.5.29.17"];
// X509KeyUsageExtension subjectAltName = (ca_cert.Extensions["2.5.29.17"] as X509KeyUsageExtension);
}
if (crl != null) {
@@ -224,7 +224,7 @@ namespace System.Text.RegularExpressions {
RegexOptions.IgnoreCase |
RegexOptions.Multiline |
RegexOptions.ExplicitCapture |
#if !NET_2_1
#if MOBILE || !NET_2_1
RegexOptions.Compiled |
#endif
RegexOptions.Singleline |
@@ -236,7 +236,7 @@ namespace System.Text.RegularExpressions {
const RegexOptions ecmaopts =
RegexOptions.IgnoreCase |
RegexOptions.Multiline |
#if !NET_2_1
#if MOBILE || !NET_2_1
RegexOptions.Compiled |
#endif
RegexOptions.ECMAScript;
@@ -35,7 +35,7 @@ namespace System.Text.RegularExpressions {
IgnoreCase = 0x001,
Multiline = 0x002,
ExplicitCapture = 0x004,
#if !NET_2_1
#if MOBILE || !NET_2_1
Compiled = 0x008,
#endif
Singleline = 0x010,
@@ -84,8 +84,13 @@ namespace MonoTests.System.Collections.Generic
[Test]
public void ClearTest ()
{
LinkedListNode <int> node = intlist.First;
intlist.Clear ();
Assert.AreEqual (0, intlist.Count);
Assert.AreEqual (2, node.Value);
Assert.IsNull (node.Next);
Assert.IsNull (node.Previous);
}
[Test]
+11 -1
View File
@@ -17,15 +17,25 @@ namespace zipsharp
AddInZip = 2
}
[UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
internal delegate IntPtr OpenFileFunc (IntPtr opaque, string filename, int mode);
[UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
internal delegate /* ulong */ IntPtr ReadFileFunc (IntPtr opaque, IntPtr stream, IntPtr buffer, /* ulong */ IntPtr size);
[UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
internal delegate /* ulong */ IntPtr WriteFileFunc (IntPtr opaque, IntPtr stream, IntPtr buffer, /* ulong */ IntPtr size);
[UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
internal delegate /* long */ IntPtr TellFileFunc (IntPtr opaque, IntPtr stream);
[UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
internal delegate /* long */ IntPtr SeekFileFunc (IntPtr opaque, IntPtr stream, /* ulong */ IntPtr offset, int origin);
[UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
internal delegate int CloseFileFunc (IntPtr opaque, IntPtr stream);
[UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
internal delegate int TestErrorFileFunc (IntPtr opaque, IntPtr stream);
[StructLayout (LayoutKind.Sequential)]
@@ -38,6 +48,6 @@ namespace zipsharp
[MarshalAs (UnmanagedType.FunctionPtr)] public SeekFileFunc zseek_file;
[MarshalAs (UnmanagedType.FunctionPtr)] public CloseFileFunc zclose_file;
[MarshalAs (UnmanagedType.FunctionPtr)] public TestErrorFileFunc zerror_file;
[MarshalAs (UnmanagedType.FunctionPtr)] public IntPtr opaque;
public IntPtr opaque;
}
}
+11 -11
View File
@@ -147,34 +147,34 @@ namespace zipsharp
return unzReadCurrentFile (handle, b, (uint)count);
}
[DllImport ("MonoPosixHelper")]
[DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
static extern int unzCloseCurrentFile (UnzipHandle handle);
[DllImport ("MonoPosixHelper")]
[DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr unztell (UnzipHandle handle);
[DllImport ("MonoPosixHelper")]
[DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
static extern int unzGoToFirstFile (UnzipHandle handle);
[DllImport ("MonoPosixHelper")]
[DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
static extern UnzipHandle unzOpen2 (string path,
ref ZlibFileFuncDef pzlib_filefunc_def);
[DllImport ("MonoPosixHelper")]
[DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
static extern int unzGoToNextFile (UnzipHandle handle);
[DllImport ("MonoPosixHelper")]
[DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
static extern int unzLocateFile (UnzipHandle handle,
string szFileName,
int iCaseSensitivity);
[DllImport ("MonoPosixHelper")]
[DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
static extern int unzOpenCurrentFile2 (UnzipHandle handle,
out int method,
out int level,
int raw);
[DllImport ("MonoPosixHelper")]
[DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
static extern int unzGetCurrentFileInfo (UnzipHandle handle,
out UnzipFileInfo pfile_info,
StringBuilder szFileName,
@@ -184,15 +184,15 @@ namespace zipsharp
StringBuilder szComment,
IntPtr commentBufferSize); // uLong
[DllImport ("MonoPosixHelper")]
[DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
static unsafe extern int unzReadCurrentFile (UnzipHandle handle,
byte* buf, // voidp
uint len);
//[DllImport ("MonoPosixHelper")]
//[DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
//static extern int unzSetOffset (UnzipHandle handle, IntPtr pos); // uLong
[DllImport ("MonoPosixHelper")]
[DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
static extern int unzClose (UnzipHandle handle);
}
}
@@ -162,7 +162,7 @@ namespace System.Globalization {
public string CultureName {
get {
if (customCultureName == null)
customCultureName = ci.Name;
customCultureName = ci == null ? String.Empty : ci.Name;
return customCultureName;
}
}
+4 -4
View File
@@ -220,7 +220,7 @@ namespace System.IO
}
if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
#if NET_2_1
#if MOONLIGHT
if (anonymous)
throw new IsolatedStorageException ("Enum value for FileAccess was out of legal range.");
else
@@ -229,7 +229,7 @@ namespace System.IO
}
if (share < FileShare.None || share > (FileShare.ReadWrite | FileShare.Delete)) {
#if NET_2_1
#if MOONLIGHT
if (anonymous)
throw new IsolatedStorageException ("Enum value for FileShare was out of legal range.");
else
@@ -275,7 +275,7 @@ namespace System.IO
// don't leak the path information for isolated storage
string msg = Locale.GetText ("Could not find a part of the path \"{0}\".");
string fname = (anonymous) ? dname : Path.GetFullPath (path);
#if NET_2_1
#if MOONLIGHT
// don't use GetSecureFileName for the directory name
throw new IsolatedStorageException (String.Format (msg, fname));
#else
@@ -289,7 +289,7 @@ namespace System.IO
// don't leak the path information for isolated storage
string msg = Locale.GetText ("Could not find file \"{0}\".");
string fname = GetSecureFileName (path);
#if NET_2_1
#if MOONLIGHT
throw new IsolatedStorageException (String.Format (msg, fname));
#else
throw new FileNotFoundException (String.Format (msg, fname), fname);
@@ -256,6 +256,11 @@ namespace System.IO {
throw new ArgumentException ("An empty file name is not valid.");
if (path.IndexOfAny (Path.InvalidPathChars) != -1)
throw new ArgumentException ("Illegal characters in path.");
if (Environment.IsRunningOnWindows) {
int idx = path.IndexOf (':');
if (idx >= 0 && idx != 1)
throw new ArgumentException ("path");
}
}
internal MonoIOStat stat;
+2 -2
View File
@@ -82,7 +82,7 @@ namespace System.IO
// FIXME: add more exception mappings here
case MonoIOError.ERROR_FILE_NOT_FOUND:
message = String.Format ("Could not find file \"{0}\"", path);
#if NET_2_1
#if MOONLIGHT
return new IsolatedStorageException (message);
#else
return new FileNotFoundException (message, path);
@@ -93,7 +93,7 @@ namespace System.IO
case MonoIOError.ERROR_PATH_NOT_FOUND:
message = String.Format ("Could not find a part of the path \"{0}\"", path);
#if NET_2_1
#if MOONLIGHT
return new IsolatedStorageException (message);
#else
return new DirectoryNotFoundException (message);
+5
View File
@@ -841,6 +841,11 @@ namespace System.IO {
throw new ArgumentException (Locale.GetText ("Path is empty"));
if (path.IndexOfAny (Path.InvalidPathChars) != -1)
throw new ArgumentException (Locale.GetText ("Path contains invalid chars"));
if (Environment.IsRunningOnWindows) {
int idx = path.IndexOf (':');
if (idx >= 0 && idx != 1)
throw new ArgumentException (parameterName);
}
#if MOONLIGHT
// On Moonlight (SL4+) there are some limitations in "Elevated Trust"
if (SecurityManager.HasElevatedPermissions) {
@@ -281,8 +281,13 @@ namespace System.Reflection {
"name");
ManifestResourceInfo info = GetManifestResourceInfo (name);
if (info == null)
return null;
if (info == null) {
Assembly a = AppDomain.CurrentDomain.DoResourceResolve (name, this);
if (a != null && a != this)
return a.GetManifestResourceStream (name);
else
return null;
}
if (info.ReferencedAssembly != null)
return info.ReferencedAssembly.GetManifestResourceStream (name);
@@ -8,6 +8,7 @@
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) Tim Coleman, 2004
// Copyright (C) 2004-2007,2011 Novell, Inc (http://www.novell.com)
// Copyright (C) 2011 Xamarin Inc. http://www.xamarin.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -489,6 +490,8 @@ public partial class CryptoConfig {
if (algo == null)
algo = name;
algoClass = Type.GetType (algo);
if (algoClass == null)
return null;
// call the constructor for the type
return Activator.CreateInstance (algoClass, args);
}
@@ -94,6 +94,7 @@ namespace System.Text
public override void Reset ()
{
fallback_assigned = false;
current = 0;
}
}
@@ -31,14 +31,15 @@ using System.Threading;
namespace System.Threading.Tasks
{
public class SynchronizationContextScheduler : TaskScheduler
sealed class SynchronizationContextScheduler : TaskScheduler
{
readonly SynchronizationContext ctx;
static readonly SendOrPostCallback callback = TaskLaunchWrapper;
readonly SendOrPostCallback callback;
public SynchronizationContextScheduler (SynchronizationContext ctx)
{
this.ctx = ctx;
this.callback = TaskLaunchWrapper;
}
protected internal override void QueueTask (Task task)
@@ -46,9 +47,9 @@ namespace System.Threading.Tasks
ctx.Post (callback, task);
}
static void TaskLaunchWrapper (object obj)
void TaskLaunchWrapper (object obj)
{
((Task)obj).Execute (null);
TryExecuteTask ((Task)obj);
}
protected override System.Collections.Generic.IEnumerable<Task> GetScheduledTasks ()
@@ -63,15 +64,8 @@ namespace System.Threading.Tasks
protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
{
if (task.IsCompleted)
return false;
if (task.Status == TaskStatus.WaitingToRun) {
task.Execute (null);
return true;
}
return false;
ctx.Send (callback, task);
return true;
}
public override int MaximumConcurrencyLevel {
+111 -33
View File
@@ -30,8 +30,8 @@ using System.Collections.Concurrent;
namespace System.Threading.Tasks
{
[System.Diagnostics.DebuggerDisplay ("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}")]
[System.Diagnostics.DebuggerTypeProxy ("System.Threading.Tasks.SystemThreadingTasks_TaskDebugView")]
[System.Diagnostics.DebuggerDisplay ("Id = {Id}, Status = {Status}")]
[System.Diagnostics.DebuggerTypeProxy (typeof (TaskDebuggerView))]
public class Task : IDisposable, IAsyncResult
{
// With this attribute each thread has its own value so that it's correct for our Schedule code
@@ -57,17 +57,22 @@ namespace System.Threading.Tasks
volatile AggregateException exception;
volatile bool exceptionObserved;
ConcurrentQueue<AggregateException> childExceptions;
TaskStatus status;
Action<object> action;
Action simpleAction;
object state;
AtomicBooleanValue executing;
ConcurrentQueue<EventHandler> completed = new ConcurrentQueue<EventHandler> ();
ConcurrentQueue<EventHandler> completed;
CancellationToken token;
const TaskCreationOptions MaxTaskCreationOptions =
TaskCreationOptions.PreferFairness | TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent;
public Task (Action action) : this (action, TaskCreationOptions.None)
{
@@ -84,8 +89,13 @@ namespace System.Threading.Tasks
}
public Task (Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: this ((o) => { if (action != null) action (); }, null, cancellationToken, creationOptions)
: this (null, null, cancellationToken, creationOptions, current)
{
if (action == null)
throw new ArgumentNullException ("action");
if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None)
throw new ArgumentOutOfRangeException ("creationOptions");
this.simpleAction = action;
}
public Task (Action<object> action, object state) : this (action, state, TaskCreationOptions.None)
@@ -101,24 +111,35 @@ namespace System.Threading.Tasks
: this (action, state, cancellationToken, TaskCreationOptions.None)
{
}
public Task (Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: this (action, state, cancellationToken, creationOptions, current)
{
if (action == null)
throw new ArgumentNullException ("action");
if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None)
throw new ArgumentOutOfRangeException ("creationOptions");
}
internal Task (Action<object> action,
object state,
CancellationToken cancellationToken,
TaskCreationOptions creationOptions,
Task parent)
{
this.taskCreationOptions = creationOptions;
this.action = action == null ? EmptyFunc : action;
this.action = action;
this.state = state;
this.taskId = Interlocked.Increment (ref id);
this.status = cancellationToken.IsCancellationRequested ? TaskStatus.Canceled : TaskStatus.Created;
this.token = cancellationToken;
this.parent = parent;
// Process taskCreationOptions
if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent)) {
parent = current;
if (parent != null)
parent.AddChild ();
}
if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent) && parent != null)
parent.AddChild ();
}
~Task ()
{
if (exception != null && !exceptionObserved)
@@ -130,10 +151,6 @@ namespace System.Threading.Tasks
return (opt & member) == member;
}
static void EmptyFunc (object o)
{
}
#region Start
public void Start ()
{
@@ -162,9 +179,24 @@ namespace System.Threading.Tasks
public void RunSynchronously (TaskScheduler scheduler)
{
if (scheduler.TryExecuteTask (this))
return;
if (scheduler == null)
throw new ArgumentNullException ("scheduler");
if (Status > TaskStatus.WaitingForActivation)
throw new InvalidOperationException ("The task is not in a valid state to be started");
SetupScheduler (scheduler);
var saveStatus = status;
status = TaskStatus.WaitingToRun;
try {
if (scheduler.RunInline (this))
return;
} catch (Exception inner) {
throw new TaskSchedulerException (inner);
}
status = saveStatus;
Start (scheduler);
Wait ();
}
@@ -193,7 +225,11 @@ namespace System.Threading.Tasks
public Task ContinueWith (Action<Task> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
Task continuation = new Task ((o) => continuationAction ((Task)o), this, cancellationToken, GetCreationOptions (continuationOptions));
Task continuation = new Task ((o) => continuationAction ((Task)o),
this,
cancellationToken,
GetCreationOptions (continuationOptions),
this);
ContinueWithCore (continuation, continuationOptions, scheduler);
return continuation;
@@ -227,7 +263,11 @@ namespace System.Threading.Tasks
if (scheduler == null)
throw new ArgumentNullException ("scheduler");
Task<TResult> t = new Task<TResult> ((o) => continuationFunction ((Task)o), this, cancellationToken, GetCreationOptions (continuationOptions));
Task<TResult> t = new Task<TResult> ((o) => continuationFunction ((Task)o),
this,
cancellationToken,
GetCreationOptions (continuationOptions),
this);
ContinueWithCore (t, continuationOptions, scheduler);
@@ -236,7 +276,7 @@ namespace System.Threading.Tasks
internal void ContinueWithCore (Task continuation, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
ContinueWithCore (continuation, continuationOptions, scheduler, () => true);
ContinueWithCore (continuation, continuationOptions, scheduler, null);
}
internal void ContinueWithCore (Task continuation, TaskContinuationOptions kind,
@@ -249,8 +289,8 @@ namespace System.Threading.Tasks
AtomicBoolean launched = new AtomicBoolean ();
EventHandler action = delegate (object sender, EventArgs e) {
if (!launched.Value && launched.TrySet ()) {
if (!predicate ())
if (launched.TryRelaxedSet ()) {
if (predicate != null && !predicate ())
return;
if (!ContinuationStatusCheck (kind)) {
@@ -269,6 +309,8 @@ namespace System.Threading.Tasks
return;
}
if (completed == null)
Interlocked.CompareExchange (ref completed, new ConcurrentQueue<EventHandler> (), null);
completed.Enqueue (action);
// Retry in case completion was achieved but event adding was too late
@@ -321,7 +363,7 @@ namespace System.Threading.Tasks
void CheckAndSchedule (Task continuation, TaskContinuationOptions options, TaskScheduler scheduler, bool fromCaller)
{
if ((options & TaskContinuationOptions.ExecuteSynchronously) > 0)
continuation.ThreadStart ();
continuation.RunSynchronously (scheduler);
else
continuation.Start (scheduler);
}
@@ -342,7 +384,7 @@ namespace System.Threading.Tasks
#region Internal and protected thingies
internal void Schedule ()
{
{
status = TaskStatus.WaitingToRun;
// If worker is null it means it is a local one, revert to the old behavior
@@ -377,7 +419,7 @@ namespace System.Threading.Tasks
try {
InnerInvoke ();
} catch (OperationCanceledException oce) {
if (oce.CancellationToken == token)
if (token != CancellationToken.None && oce.CancellationToken == token)
CancelReal ();
else
HandleGenericException (oce);
@@ -402,23 +444,31 @@ namespace System.Threading.Tasks
childTasks.AddCount ();
}
internal void ChildCompleted ()
internal void ChildCompleted (AggregateException childEx)
{
childTasks.Signal ();
if (childTasks.IsSet && status == TaskStatus.WaitingForChildrenToComplete) {
if (childEx != null) {
if (childExceptions == null)
Interlocked.CompareExchange (ref childExceptions, new ConcurrentQueue<AggregateException> (), null);
childExceptions.Enqueue (childEx);
}
if (childTasks.Signal () && status == TaskStatus.WaitingForChildrenToComplete) {
status = TaskStatus.RanToCompletion;
ProcessChildExceptions ();
ProcessCompleteDelegates ();
}
}
internal virtual void InnerInvoke ()
{
if (action != null)
if (action == null && simpleAction != null)
simpleAction ();
else if (action != null)
action (state);
// Set action to null so that the GC can collect the delegate and thus
// any big object references that the user might have captured in an anonymous method
action = null;
simpleAction = null;
state = null;
}
@@ -443,17 +493,33 @@ namespace System.Threading.Tasks
TaskScheduler.Current = null;
// Tell parent that we are finished
if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent) && parent != null){
parent.ChildCompleted ();
if (CheckTaskOptions (taskCreationOptions, TaskCreationOptions.AttachedToParent) && parent != null) {
parent.ChildCompleted (this.Exception);
}
}
void ProcessCompleteDelegates ()
{
if (completed == null)
return;
EventHandler handler;
while (completed.TryDequeue (out handler))
handler (this, EventArgs.Empty);
}
void ProcessChildExceptions ()
{
if (childExceptions == null)
return;
if (exception == null)
exception = new AggregateException ();
AggregateException childEx;
while (childExceptions.TryDequeue (out childEx))
exception.AddChildException (childEx);
}
#endregion
#region Cancel and Wait related method
@@ -471,6 +537,7 @@ namespace System.Threading.Tasks
internal void HandleGenericException (AggregateException e)
{
exception = e;
Thread.MemoryBarrier ();
status = TaskStatus.Faulted;
if (scheduler != null && scheduler.FireUnobservedEvent (exception).Observed)
exceptionObserved = true;
@@ -729,6 +796,9 @@ namespace System.Threading.Tasks
protected virtual void Dispose (bool disposing)
{
if (!IsCompleted)
throw new InvalidOperationException ("A task may only be disposed if it is in a completion state");
// Set action to null so that the GC can collect the delegate and thus
// any big object references that the user might have captured in a anonymous method
if (disposing) {
@@ -826,6 +896,14 @@ namespace System.Threading.Tasks
return parent;
}
}
internal string DisplayActionMethod {
get {
Delegate d = simpleAction ?? (Delegate) action;
return d == null ? "<none>" : d.Method.ToString ();
}
}
#endregion
}
}
@@ -1,10 +1,12 @@
//
// TaskCompletionSource.cs
//
// Author:
// Authors:
// Jérémie "Garuma" Laval <[email protected]>
// Marek Safar <[email protected]>
//
// Copyright (c) 2009 Jérémie "Garuma" Laval
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -32,7 +34,8 @@ namespace System.Threading.Tasks
{
public class TaskCompletionSource<TResult>
{
Task<TResult> source;
readonly Task<TResult> source;
SpinLock opLock = new SpinLock (false);
public TaskCompletionSource ()
{
@@ -63,15 +66,18 @@ namespace System.Threading.Tasks
if (!ApplyOperation (source.CancelReal))
ThrowInvalidException ();
}
public void SetException (Exception exception)
{
if (exception == null)
throw new ArgumentNullException ("exception");
SetException (new Exception[] { exception });
}
public void SetException (IEnumerable<Exception> exceptions)
{
if (!ApplyOperation (() => source.HandleGenericException (new AggregateException (exceptions))))
if (!TrySetException (exceptions))
ThrowInvalidException ();
}
@@ -81,7 +87,7 @@ namespace System.Threading.Tasks
ThrowInvalidException ();
}
void ThrowInvalidException ()
static void ThrowInvalidException ()
{
throw new InvalidOperationException ("The underlying Task is already in one of the three final states: RanToCompletion, Faulted, or Canceled.");
}
@@ -93,12 +99,22 @@ namespace System.Threading.Tasks
public bool TrySetException (Exception exception)
{
if (exception == null)
throw new ArgumentNullException ("exception");
return TrySetException (new Exception[] { exception });
}
public bool TrySetException (IEnumerable<Exception> exceptions)
{
return ApplyOperation (() => source.HandleGenericException (new AggregateException (exceptions)));
if (exceptions == null)
throw new ArgumentNullException ("exceptions");
var aggregate = new AggregateException (exceptions);
if (aggregate.InnerExceptions.Count == 0)
throw new ArgumentNullException ("exceptions");
return ApplyOperation (() => source.HandleGenericException (aggregate));
}
public bool TrySetResult (TResult result)
@@ -108,17 +124,24 @@ namespace System.Threading.Tasks
bool ApplyOperation (Action action)
{
if (CheckInvalidState ())
return false;
bool taken = false;
try {
opLock.Enter (ref taken);
if (CheckInvalidState ())
return false;
source.Status = TaskStatus.Running;
source.Status = TaskStatus.Running;
if (action != null)
action ();
if (action != null)
action ();
source.Finish ();
source.Finish ();
return true;
return true;
} finally {
if (taken)
opLock.Exit ();
}
}
bool CheckInvalidState ()
@@ -0,0 +1,86 @@
//
// TaskDebuggerView.cs
//
// Authors:
// Marek Safar <[email protected]>
//
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
// 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_4_0 || MOBILE
using System;
using System.Diagnostics;
namespace System.Threading.Tasks
{
//
// Custom debugger type proxy for tasks
//
sealed class TaskDebuggerView
{
readonly Task task;
public TaskDebuggerView (Task task)
{
this.task = task;
}
public object AsyncState {
get {
return task.AsyncState;
}
}
public TaskCreationOptions CreationOptions {
get {
return task.CreationOptions;
}
}
public Exception Exception {
get {
return task.Exception;
}
}
public int Id {
get {
return task.Id;
}
}
public string Method {
get {
return task.DisplayActionMethod;
}
}
public TaskStatus Status {
get {
return task.Status;
}
}
}
}
#endif
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,463 @@
//
// TaskFactory_T.cs
//
// Authors:
// Jérémie "Garuma" Laval <[email protected]>
// Marek Safar <[email protected]>
//
// Copyright (c) 2009 Jérémie "Garuma" Laval
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
// 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_4_0 || MOBILE
using System;
using System.Threading;
namespace System.Threading.Tasks
{
public class TaskFactory<TResult>
{
readonly TaskScheduler scheduler;
TaskCreationOptions creationOptions;
TaskContinuationOptions continuationOptions;
CancellationToken cancellationToken;
TaskFactory parent;
const TaskCreationOptions FromAsyncOptionsNotSupported = TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness;
public TaskFactory ()
: this (CancellationToken.None)
{
}
public TaskFactory (TaskScheduler scheduler)
: this (CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, scheduler)
{
}
public TaskFactory (CancellationToken cancellationToken)
: this (cancellationToken, TaskCreationOptions.None, TaskContinuationOptions.None, null)
{
}
public TaskFactory (TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions)
: this (CancellationToken.None, creationOptions, continuationOptions, null)
{
}
public TaskFactory (CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
this.cancellationToken = cancellationToken;
this.scheduler = scheduler;
this.creationOptions = creationOptions;
this.continuationOptions = continuationOptions;
TaskFactory.CheckContinuationOptions (continuationOptions);
this.parent = new TaskFactory (cancellationToken, creationOptions, continuationOptions, scheduler);
}
public TaskScheduler Scheduler {
get {
return scheduler;
}
}
public TaskContinuationOptions ContinuationOptions {
get {
return continuationOptions;
}
}
public TaskCreationOptions CreationOptions {
get {
return creationOptions;
}
}
public CancellationToken CancellationToken {
get {
return cancellationToken;
}
}
#region StartNew for Task<TResult>
public Task<TResult> StartNew (Func<TResult> function)
{
return StartNew (function, cancellationToken, creationOptions, GetScheduler ());
}
public Task<TResult> StartNew (Func<TResult> function, TaskCreationOptions creationOptions)
{
return StartNew (function, cancellationToken, creationOptions, GetScheduler ());
}
public Task<TResult> StartNew (Func<TResult> function, CancellationToken cancellationToken)
{
return StartNew (function, cancellationToken, creationOptions, GetScheduler ());
}
public Task<TResult> StartNew (Func<TResult> function,
CancellationToken cancellationToken,
TaskCreationOptions creationOptions,
TaskScheduler scheduler)
{
return StartNew ((o) => function (), null, cancellationToken, creationOptions, scheduler);
}
public Task<TResult> StartNew (Func<object, TResult> function, object state)
{
return StartNew (function, state, cancellationToken, creationOptions, GetScheduler ());
}
public Task<TResult> StartNew (Func<object, TResult> function, object state, TaskCreationOptions creationOptions)
{
return StartNew (function, state, cancellationToken, creationOptions, GetScheduler ());
}
public Task<TResult> StartNew (Func<object, TResult> function, object state, CancellationToken cancellationToken)
{
return StartNew (function, state, cancellationToken, creationOptions, GetScheduler ());
}
public Task<TResult> StartNew (Func<object, TResult> function, object state,
CancellationToken cancellationToken,
TaskCreationOptions creationOptions,
TaskScheduler scheduler)
{
return parent.StartNew<TResult> (function, state, cancellationToken, creationOptions, scheduler);
}
#endregion
#region Continue
public Task<TResult> ContinueWhenAny (Task[] tasks,
Func<Task, TResult> continuationFunction)
{
return ContinueWhenAny (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAny (Task[] tasks,
Func<Task, TResult> continuationFunction,
CancellationToken cancellationToken)
{
return ContinueWhenAny (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAny (Task[] tasks,
Func<Task, TResult> continuationFunction,
TaskContinuationOptions continuationOptions)
{
return ContinueWhenAny (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAny (Task[] tasks,
Func<Task, TResult> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
return parent.ContinueWhenAny (tasks, continuationFunction, cancellationToken, continuationOptions, scheduler);
}
public Task<TResult> ContinueWhenAny<TAntecedentResult> (Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>, TResult> continuationFunction)
{
return ContinueWhenAny (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAny<TAntecedentResult> (Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>, TResult> continuationFunction,
CancellationToken cancellationToken)
{
return ContinueWhenAny (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAny<TAntecedentResult> (Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>, TResult> continuationFunction,
TaskContinuationOptions continuationOptions)
{
return ContinueWhenAny (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAny<TAntecedentResult> (Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>, TResult> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
return parent.ContinueWhenAny (tasks, continuationFunction, cancellationToken, continuationOptions, scheduler);
}
public Task<TResult> ContinueWhenAll (Task[] tasks, Func<Task[], TResult> continuationFunction)
{
return ContinueWhenAll (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAll (Task[] tasks,
Func<Task[], TResult> continuationFunction,
TaskContinuationOptions continuationOptions)
{
return ContinueWhenAll (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAll (Task[] tasks,
Func<Task[], TResult> continuationFunction,
CancellationToken cancellationToken)
{
return ContinueWhenAll (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAll (Task[] tasks,
Func<Task[], TResult> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
return parent.ContinueWhenAll (tasks, continuationFunction, cancellationToken, continuationOptions, scheduler);
}
public Task<TResult> ContinueWhenAll<TAntecedentResult> (Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>[], TResult> continuationFunction)
{
return ContinueWhenAll (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAll<TAntecedentResult> (Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>[], TResult> continuationFunction,
TaskContinuationOptions continuationOptions)
{
return ContinueWhenAll (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAll<TAntecedentResult> (Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>[], TResult> continuationFunction,
CancellationToken cancellationToken)
{
return ContinueWhenAll (tasks, continuationFunction, cancellationToken, continuationOptions, GetScheduler ());
}
public Task<TResult> ContinueWhenAll<TAntecedentResult> (Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>[], TResult> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
return parent.ContinueWhenAll (tasks, continuationFunction, cancellationToken, continuationOptions, scheduler);
}
#endregion
#region FromAsync
public Task<TResult> FromAsync (IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod)
{
return FromAsync (asyncResult, endMethod, creationOptions);
}
public Task<TResult> FromAsync (IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod, TaskCreationOptions creationOptions)
{
return FromAsync (asyncResult, endMethod, creationOptions, GetScheduler ());
}
public Task<TResult> FromAsync (IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod, TaskCreationOptions creationOptions, TaskScheduler scheduler)
{
return FromIAsyncResult (asyncResult, endMethod, creationOptions, scheduler);
}
internal static Task<TResult> FromIAsyncResult (IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod, TaskCreationOptions creationOptions, TaskScheduler scheduler)
{
if (asyncResult == null)
throw new ArgumentNullException ("asyncResult");
if (endMethod == null)
throw new ArgumentNullException ("endMethod");
if (scheduler == null)
throw new ArgumentNullException ("scheduler");
if ((creationOptions & FromAsyncOptionsNotSupported) != 0)
throw new ArgumentOutOfRangeException ("creationOptions");
var source = new CancellationTokenSource ();
var task = new Task<TResult> (l => {
try {
return endMethod (asyncResult);
} catch (OperationCanceledException) {
source.Cancel ();
source.Token.ThrowIfCancellationRequested ();
}
return default (TResult);
}, null, source.Token, creationOptions);
// Take quick path for completed operations
if (asyncResult.IsCompleted) {
task.RunSynchronously (scheduler);
} else {
ThreadPool.RegisterWaitForSingleObject (asyncResult.AsyncWaitHandle,
(s, t) => task.RunSynchronously (scheduler),
null, Timeout.Infinite, true);
}
return task;
}
public Task<TResult> FromAsync (Func<AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
object state)
{
return FromAsync (beginMethod, endMethod, state, creationOptions);
}
public Task<TResult> FromAsync (Func<AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
object state, TaskCreationOptions creationOptions)
{
return FromAsyncBeginEnd (beginMethod, endMethod, state, creationOptions);
}
internal static Task<TResult> FromAsyncBeginEnd (Func<AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
object state, TaskCreationOptions creationOptions)
{
if (beginMethod == null)
throw new ArgumentNullException ("beginMethod");
if (endMethod == null)
throw new ArgumentNullException ("endMethod");
if ((creationOptions & FromAsyncOptionsNotSupported) != 0)
throw new ArgumentOutOfRangeException ("creationOptions");
var tcs = new TaskCompletionSource<TResult> (state, creationOptions);
beginMethod (l => InnerInvoke (tcs, endMethod, l), state);
return tcs.Task;
}
public Task<TResult> FromAsync<TArg1> (Func<TArg1, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, object state)
{
return FromAsync (beginMethod, endMethod, arg1, state, creationOptions);
}
public Task<TResult> FromAsync<TArg1> (Func<TArg1, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, object state, TaskCreationOptions creationOptions)
{
return FromAsyncBeginEnd (beginMethod, endMethod, arg1, state, creationOptions);
}
internal static Task<TResult> FromAsyncBeginEnd<TArg1> (Func<TArg1, AsyncCallback, object, IAsyncResult> beginMethod,
Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, object state, TaskCreationOptions creationOptions)
{
if (beginMethod == null)
throw new ArgumentNullException ("beginMethod");
if (endMethod == null)
throw new ArgumentNullException ("endMethod");
if ((creationOptions & FromAsyncOptionsNotSupported) != 0)
throw new ArgumentOutOfRangeException ("creationOptions");
var tcs = new TaskCompletionSource<TResult> (state, creationOptions);
beginMethod (arg1, l => InnerInvoke (tcs, endMethod, l), state);
return tcs.Task;
}
public Task<TResult> FromAsync<TArg1, TArg2> (Func<TArg1, TArg2, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, TArg2 arg2, object state)
{
return FromAsync (beginMethod, endMethod, arg1, arg2, state, creationOptions);
}
public Task<TResult> FromAsync<TArg1, TArg2> (Func<TArg1, TArg2, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, TArg2 arg2, object state, TaskCreationOptions creationOptions)
{
return FromAsyncBeginEnd (beginMethod, endMethod, arg1, arg2, state, creationOptions);
}
internal static Task<TResult> FromAsyncBeginEnd<TArg1, TArg2> (Func<TArg1, TArg2, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, TArg2 arg2, object state, TaskCreationOptions creationOptions)
{
if (beginMethod == null)
throw new ArgumentNullException ("beginMethod");
if (endMethod == null)
throw new ArgumentNullException ("endMethod");
if ((creationOptions & FromAsyncOptionsNotSupported) != 0)
throw new ArgumentOutOfRangeException ("creationOptions");
var tcs = new TaskCompletionSource<TResult> (state, creationOptions);
beginMethod (arg1, arg2, l => InnerInvoke (tcs, endMethod, l), state);
return tcs.Task;
}
public Task<TResult> FromAsync<TArg1, TArg2, TArg3> (Func<TArg1, TArg2, TArg3, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, TArg2 arg2, TArg3 arg3, object state)
{
return FromAsync (beginMethod, endMethod, arg1, arg2, arg3, state, creationOptions);
}
public Task<TResult> FromAsync<TArg1, TArg2, TArg3> (Func<TArg1, TArg2, TArg3, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, TArg2 arg2, TArg3 arg3, object state,
TaskCreationOptions creationOptions)
{
return FromAsyncBeginEnd (beginMethod, endMethod, arg1, arg2, arg3, state, creationOptions);
}
internal static Task<TResult> FromAsyncBeginEnd<TArg1, TArg2, TArg3> (Func<TArg1, TArg2, TArg3, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod,
TArg1 arg1, TArg2 arg2, TArg3 arg3, object state, TaskCreationOptions creationOptions)
{
if (beginMethod == null)
throw new ArgumentNullException ("beginMethod");
if (endMethod == null)
throw new ArgumentNullException ("endMethod");
if ((creationOptions & FromAsyncOptionsNotSupported) != 0)
throw new ArgumentOutOfRangeException ("creationOptions");
var tcs = new TaskCompletionSource<TResult> (state, creationOptions);
beginMethod (arg1, arg2, arg3, l => InnerInvoke (tcs, endMethod, l), state);
return tcs.Task;
}
#endregion
TaskScheduler GetScheduler ()
{
return scheduler ?? TaskScheduler.Current;
}
static void InnerInvoke (TaskCompletionSource<TResult> tcs, Func<IAsyncResult, TResult> endMethod, IAsyncResult l)
{
try {
tcs.SetResult (endMethod (l));
} catch (OperationCanceledException) {
tcs.SetCanceled ();
} catch (Exception e) {
tcs.SetException (e);
}
}
}
}
#endif
@@ -35,8 +35,7 @@ namespace System.Threading.Tasks
[System.Diagnostics.DebuggerTypeProxy ("System.Threading.Tasks.TaskScheduler+SystemThreadingTasks_TaskSchedulerDebugView")]
public abstract class TaskScheduler
{
static TaskScheduler defaultScheduler =
Environment.GetEnvironmentVariable ("USE_OLD_TASK_SCHED") != null ? (TaskScheduler)new Scheduler () : (TaskScheduler)new TpScheduler ();
static TaskScheduler defaultScheduler = new TpScheduler ();
SchedulerProxy proxy;
[ThreadStatic]
@@ -53,6 +52,10 @@ namespace System.Threading.Tasks
this.proxy = new SchedulerProxy (this);
}
~TaskScheduler ()
{
}
public static TaskScheduler FromCurrentSynchronizationContext ()
{
var syncCtx = SynchronizationContext.Current;
@@ -125,7 +128,17 @@ namespace System.Threading.Tasks
}
protected abstract bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued);
internal bool RunInline (Task task)
{
if (!TryExecuteTaskInline (task, false))
return false;
if (!task.IsCompleted)
throw new InvalidOperationException ("The TryExecuteTaskInline call to the underlying scheduler succeeded, but the task body was not invoked");
return true;
}
internal UnobservedTaskExceptionEventArgs FireUnobservedEvent (AggregateException e)
{
UnobservedTaskExceptionEventArgs args = new UnobservedTaskExceptionEventArgs (e);
@@ -30,7 +30,7 @@ namespace System.Threading.Tasks
{
public class TaskSchedulerException : Exception
{
const string exceptionDefaultMessage = "TaskScheduler exception";
const string exceptionDefaultMessage = "An exception was thrown by a TaskScheduler";
public TaskSchedulerException () : base (exceptionDefaultMessage)
{
@@ -0,0 +1,212 @@
//
// Task_T.cs
//
// Copyright (c) 2008 Jérémie "Garuma" Laval
//
// 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_4_0 || MOBILE
using System;
namespace System.Threading.Tasks
{
[System.Diagnostics.DebuggerDisplay ("Id = {Id}, Status = {Status}, Result = {ResultAsString}")]
[System.Diagnostics.DebuggerTypeProxy (typeof (TaskDebuggerView))]
public class Task<TResult>: Task
{
TResult value;
static TaskFactory<TResult> factory = new TaskFactory<TResult> ();
static readonly Action<object> emptyAction = delegate {};
internal Func<object, TResult> function;
object state;
[System.Diagnostics.DebuggerBrowsable (System.Diagnostics.DebuggerBrowsableState.Never)]
public TResult Result {
get {
if (function != null)
Wait ();
else if (Exception != null)
throw Exception;
return value;
}
internal set {
this.value = value;
}
}
string ResultAsString {
get {
if ((Status & (TaskStatus.RanToCompletion)) != 0)
return "" + value;
return "<value not available>";
}
}
public static new TaskFactory<TResult> Factory {
get {
return factory;
}
}
public Task (Func<TResult> function) : this (function, TaskCreationOptions.None)
{
}
public Task (Func<TResult> function, CancellationToken cancellationToken)
: this (function == null ? (Func<object, TResult>)null : (o) => function(), null, cancellationToken, TaskCreationOptions.None)
{
}
public Task (Func<TResult> function, TaskCreationOptions creationOptions)
: this (function == null ? (Func<object, TResult>)null : (o) => function(), null, CancellationToken.None, creationOptions)
{
}
public Task (Func<TResult> function, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: this (function == null ? (Func<object, TResult>)null : (o) => function(), null, cancellationToken, creationOptions)
{
}
public Task (Func<object, TResult> function, object state) : this (function, state, TaskCreationOptions.None)
{
}
public Task (Func<object, TResult> function, object state, CancellationToken cancellationToken)
: this (function, state, cancellationToken, TaskCreationOptions.None)
{
}
public Task (Func<object, TResult> function, object state, TaskCreationOptions creationOptions)
: this (function, state, CancellationToken.None, creationOptions)
{
}
public Task (Func<object, TResult> function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: base (emptyAction, state, cancellationToken, creationOptions)
{
this.function = function;
this.state = state;
}
internal Task (Func<object, TResult> function,
object state,
CancellationToken cancellationToken,
TaskCreationOptions creationOptions,
Task parent)
: base (null, state, cancellationToken, creationOptions, parent)
{
this.function = function;
this.state = state;
}
internal override void InnerInvoke ()
{
if (function != null)
value = function (state);
function = null;
state = null;
}
public Task ContinueWith (Action<Task<TResult>> continuationAction)
{
return ContinueWith (continuationAction, TaskContinuationOptions.None);
}
public Task ContinueWith (Action<Task<TResult>> continuationAction, TaskContinuationOptions continuationOptions)
{
return ContinueWith (continuationAction, CancellationToken.None, continuationOptions, TaskScheduler.Current);
}
public Task ContinueWith (Action<Task<TResult>> continuationAction, CancellationToken cancellationToken)
{
return ContinueWith (continuationAction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
}
public Task ContinueWith (Action<Task<TResult>> continuationAction, TaskScheduler scheduler)
{
return ContinueWith (continuationAction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
}
public Task ContinueWith (Action<Task<TResult>> continuationAction, CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationAction == null)
throw new ArgumentNullException ("continuationFunction");
if (scheduler == null)
throw new ArgumentNullException ("scheduler");
Task t = new Task ((o) => continuationAction ((Task<TResult>)o),
this,
cancellationToken,
GetCreationOptions (continuationOptions),
this);
ContinueWithCore (t, continuationOptions, scheduler);
return t;
}
public Task<TNewResult> ContinueWith<TNewResult> (Func<Task<TResult>, TNewResult> continuationFunction)
{
return ContinueWith<TNewResult> (continuationFunction, TaskContinuationOptions.None);
}
public Task<TNewResult> ContinueWith<TNewResult> (Func<Task<TResult>, TNewResult> continuationFunction, CancellationToken cancellationToken)
{
return ContinueWith<TNewResult> (continuationFunction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
}
public Task<TNewResult> ContinueWith<TNewResult> (Func<Task<TResult>, TNewResult> continuationFunction, TaskContinuationOptions continuationOptions)
{
return ContinueWith<TNewResult> (continuationFunction, CancellationToken.None, continuationOptions, TaskScheduler.Current);
}
public Task<TNewResult> ContinueWith<TNewResult> (Func<Task<TResult>, TNewResult> continuationFunction, TaskScheduler scheduler)
{
return ContinueWith<TNewResult> (continuationFunction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
}
public Task<TNewResult> ContinueWith<TNewResult> (Func<Task<TResult>, TNewResult> continuationFunction,
CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions,
TaskScheduler scheduler)
{
Task<TNewResult> t = new Task<TNewResult> ((o) => continuationFunction ((Task<TResult>)o),
this,
cancellationToken,
GetCreationOptions (continuationOptions),
this);
ContinueWithCore (t, continuationOptions, scheduler);
return t;
}
}
}
#endif
@@ -25,7 +25,7 @@
*/
#if NET_4_0
#if NET_4_0 || MOBILE
using System;
using System.Runtime.Serialization;
@@ -34,7 +34,9 @@ using System.Runtime.CompilerServices;
namespace System.Threading
{
[Serializable]
#if !MOBILE
[TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
#endif
public class LockRecursionException : Exception
{
public LockRecursionException ()
@@ -22,7 +22,7 @@
//
//
#if NET_4_0
#if NET_4_0 || MOBILE
using System;
using System.Collections.Concurrent;
@@ -121,6 +121,16 @@ namespace System
return innerExceptions.AsReadOnly ();
}
}
internal void AddChildException (AggregateException childEx)
{
if (innerExceptions == null)
innerExceptions = new List<Exception> ();
if (childEx == null)
return;
innerExceptions.Add (childEx);
}
public override string ToString ()
{
+19
View File
@@ -1316,6 +1316,25 @@ namespace System {
}
}
internal Assembly DoResourceResolve (string name, Assembly requesting) {
if (ResourceResolve == null)
return null;
Delegate[] invocation_list = ResourceResolve.GetInvocationList ();
foreach (Delegate eh in invocation_list) {
ResolveEventHandler handler = (ResolveEventHandler) eh;
#if NET_4_0
Assembly assembly = handler (this, new ResolveEventArgs (name, requesting));
#else
Assembly assembly = handler (this, new ResolveEventArgs (name));
#endif
if (assembly != null)
return assembly;
}
return null;
}
private void DoDomainUnload ()
{
if (DomainUnload != null)
+1 -1
View File
@@ -26,7 +26,7 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_4_0
#if NET_4_0 || MOBILE
namespace System
{
+1 -1
View File
@@ -26,7 +26,7 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_4_0
#if NET_4_0 || MOBILE
namespace System
{
+11 -2
View File
@@ -8,6 +8,7 @@
//
// (C) Ximian, Inc.
// Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
// Copyright 2011 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -54,6 +55,9 @@ namespace System
// Fields
static TimeZone currentTimeZone;
[NonSerialized]
static long timezone_check;
// Constructor
protected TimeZone ()
{
@@ -62,8 +66,13 @@ namespace System
// Properties
public static TimeZone CurrentTimeZone {
get {
if (currentTimeZone == null)
currentTimeZone = new CurrentSystemTimeZone (DateTime.GetNow ());
long now = DateTime.GetNow ();
if (currentTimeZone == null || (now - timezone_check) > TimeSpan.TicksPerMinute) {
currentTimeZone = new CurrentSystemTimeZone (now);
timezone_check = now;
}
return currentTimeZone;
}
}
@@ -40,7 +40,7 @@ namespace MonoTests.System.Collections.Generic
public class ComparerTest
{
#if !NET_4_0 // FIXME: the blob contains the 2.0 mscorlib version
#if !NET_4_0 && !NET_2_1 // FIXME: the blob contains the 2.0 mscorlib version
[Test] // bug #80929
public void SerializeDefault ()
@@ -337,7 +337,7 @@ namespace MonoTests.System.Collections.Generic {
Assert.AreEqual (- (l.Count + 1), l.BinarySearch (int.MaxValue));
}
#if !NET_4_0 // FIXME: the blob contains the 2.0 mscorlib version
#if !NET_4_0 && !NET_2_1 // FIXME: the blob contains the 2.0 mscorlib version
[Test]
[Category ("TargetJvmNotWorking")]
@@ -127,12 +127,14 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly ();
Assert.AreEqual (Int64.MaxValue, isf.MaximumSize, "MaximumSize");
Assert.AreEqual (IsolatedStorageScope.User | IsolatedStorageScope.Assembly, isf.Scope, "Scope");
#if !NET_2_1
Assert.IsTrue ((isf.AssemblyIdentity is Url), "AssemblyIdentity");
// note: mono transforms the CodeBase into uppercase
// for net 1.1 which uses file:// and not file:///
string codebase = Assembly.GetExecutingAssembly ().CodeBase.ToUpper ().Substring (8);
Assert.IsTrue ((isf.AssemblyIdentity.ToString ().ToUpper ().IndexOf (codebase) > 0), "Url");
Assert.IsTrue ((isf.AssemblyIdentity.ToString ().ToUpper ().IndexOf (codebase) > 0), "Url");
#endif
Assert.IsTrue ((isf.CurrentSize >= 0), "CurrentSize");
}
@@ -160,6 +162,7 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForDomain ();
Assert.AreEqual (Int64.MaxValue, isf.MaximumSize, "MaximumSize");
Assert.AreEqual (IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, isf.Scope, "Scope");
#if !NET_2_1
Assert.IsTrue ((isf.AssemblyIdentity is Url), "AssemblyIdentity");
// note: mono transforms the CodeBase into uppercase
// for net 1.1 which uses file:// and not file:///
@@ -170,6 +173,7 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
// so we're using the first parameter to GetCommandLineArgs
string exe = Environment.GetCommandLineArgs ()[0].Replace ("\\", "/").ToUpper ();
Assert.IsTrue ((isf.DomainIdentity.ToString ().ToUpper ().IndexOf (exe) > 0), exe + "\n" + isf.DomainIdentity.ToString ().ToUpper ()); //"Url - Domain");
#endif
Assert.IsTrue ((isf.CurrentSize >= 0), "CurrentSize");
}
@@ -196,12 +200,15 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
{
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication ();
Assert.AreEqual (Int64.MaxValue, isf.MaximumSize, "MaximumSize");
#if !NET_2_1
Assert.AreEqual (IsolatedStorageScope.User | IsolatedStorageScope.Assembly, isf.Scope, "Scope");
Assert.IsTrue ((isf.AssemblyIdentity is Url), "AssemblyIdentity");
Assert.IsTrue ((isf.AssemblyIdentity.ToString ().IndexOf (Assembly.GetExecutingAssembly ().CodeBase) > 0), "Url");
#endif
Assert.IsTrue ((isf.CurrentSize >= 0), "CurrentSize");
}
#if !NET_2_1
[Test]
[ExpectedException (typeof (IsolatedStorageException))]
public void GetUserStoreForApplication_AssemblyIdentity ()
@@ -218,6 +225,7 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
object o = isf.DomainIdentity;
}
#endif
#endif
#if NET_4_0
// This is supposed to be working only in SL.
@@ -235,11 +243,13 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
IsolatedStorageScope scope = IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly;
IsolatedStorageFile isf = IsolatedStorageFile.GetStore (scope, typeof (Zone), typeof (Zone));
Assert.AreEqual (Int64.MaxValue, isf.MaximumSize, "MaximumSize");
#if !NET_2_1
Assert.AreEqual (IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, isf.Scope, "Scope");
Assert.IsTrue ((isf.AssemblyIdentity is Zone), "AssemblyIdentity");
Assert.IsTrue ((isf.AssemblyIdentity.ToString ().IndexOf ("MyComputer") > 0), "Zone - Assembly");
Assert.IsTrue ((isf.DomainIdentity is Zone), "DomainIdentity");
Assert.IsTrue ((isf.DomainIdentity.ToString ().IndexOf ("MyComputer") > 0), "Zone - Domain");
#endif
Assert.IsTrue ((isf.CurrentSize >= 0), "CurrentSize");
}
@@ -258,12 +268,14 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
IsolatedStorageFile isf = IsolatedStorageFile.GetStore (scope, typeof (StrongName), typeof (Url));
Assert.AreEqual (Int64.MaxValue, isf.MaximumSize, "MaximumSize");
Assert.AreEqual (scope, isf.Scope, "Scope");
#if !NET_2_1
Assert.IsTrue ((isf.AssemblyIdentity is Url), "AssemblyIdentity");
// note: mono transforms the CodeBase into uppercase
// for net 1.1 which uses file:// and not file:///
string codebase = Assembly.GetExecutingAssembly ().CodeBase.ToUpper ().Substring (8);
Assert.IsTrue ((isf.AssemblyIdentity.ToString ().ToUpper ().IndexOf (codebase) > 0), "Url");
// DomainIdentity throws a InvalidOperationException
#endif
Assert.IsTrue ((isf.CurrentSize >= 0), "CurrentSize");
}
@@ -348,10 +360,12 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
// Maximum size for Internet isn't (by default) Int64.MaxValue
Assert.AreEqual (scope, isf.Scope, "Scope");
#if !NET_2_1
Assert.IsTrue ((isf.AssemblyIdentity is Zone), "AssemblyIdentity");
Assert.IsTrue ((isf.AssemblyIdentity.ToString ().IndexOf ("Intranet") > 0), "Zone - Assembly");
Assert.IsTrue ((isf.DomainIdentity is Zone), "DomainIdentity");
Assert.IsTrue ((isf.DomainIdentity.ToString ().IndexOf ("Internet") > 0), isf.DomainIdentity.ToString ()); //"Zone - Domain");
#endif
Assert.IsTrue ((isf.CurrentSize >= 0), "CurrentSize");
}
@@ -439,7 +453,7 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
try {
isf.CreateDirectory (path);
}
#if NET_4_0
#if NET_4_0 || NET_2_1
catch (IsolatedStorageException ex) {
Assert.IsFalse (ex.Message.IndexOf (path) >= 0, "Message");
Assert.IsNull (ex.InnerException, "InnerException");
@@ -480,7 +494,7 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
}
[Test]
#if NET_4_0
#if NET_4_0 || NET_2_1
[ExpectedException (typeof (ArgumentException))]
#else
[ExpectedException (typeof (SecurityException))]
@@ -580,8 +594,10 @@ namespace MonoTests.System.IO.IsolatedStorageTest {
{
IsolatedStorageScope scope = IsolatedStorageScope.User | IsolatedStorageScope.Roaming | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain;
IsolatedStorageFile isf = IsolatedStorageFile.GetStore (scope, null, null);
#if !NET_2_1
Assert.AreEqual (typeof (Url), isf.AssemblyIdentity.GetType (), "AssemblyIdentity");
Assert.AreEqual (typeof (Url), isf.DomainIdentity.GetType (), "DomainIdentity");
#endif
}
[Test]
@@ -12,6 +12,7 @@
using NUnit.Framework;
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace MonoTests.System.IO
@@ -21,6 +22,10 @@ namespace MonoTests.System.IO
{
string TempFolder = Path.Combine (Path.GetTempPath (), "MonoTests.System.IO.Tests");
static readonly char DSC = Path.DirectorySeparatorChar;
static bool MacOSX = false;
[DllImport ("libc")]
static extern int uname (IntPtr buf);
[TearDown]
public void TearDown ()
@@ -36,6 +41,12 @@ namespace MonoTests.System.IO
Directory.Delete (TempFolder, true);
Directory.CreateDirectory (TempFolder);
// from XplatUI.cs
IntPtr buf = Marshal.AllocHGlobal (8192);
if (uname (buf) == 0)
MacOSX = Marshal.PtrToStringAnsi (buf) == "Darwin";
Marshal.FreeHGlobal (buf);
}
public void TestCtr ()
@@ -102,6 +113,9 @@ namespace MonoTests.System.IO
Assert.Fail ("#B1");
} catch (FileNotFoundException ex) {
Assert.AreEqual (typeof (FileNotFoundException), ex.GetType (), "#B2");
// under OSX 'var' is a symlink to 'private/var'
if (MacOSX)
path = "/private" + path;
Assert.AreEqual (path, ex.FileName, "#B3");
Assert.IsNull (ex.InnerException, "#B4");
Assert.IsNotNull (ex.Message, "#B5");
@@ -147,6 +161,9 @@ namespace MonoTests.System.IO
Assert.Fail ("#B1");
} catch (FileNotFoundException ex) {
Assert.AreEqual (typeof (FileNotFoundException), ex.GetType (), "#B2");
// under OSX 'var' is a symlink to 'private/var'
if (MacOSX)
path = "/private" + path;
Assert.AreEqual (path, ex.FileName, "#B3");
Assert.IsNull (ex.InnerException, "#B4");
Assert.IsNotNull (ex.Message, "#B5");
@@ -658,7 +658,7 @@ namespace MonoTests.System.Reflection.Emit
Assert.AreEqual ("FOO", ((ObsoleteAttribute) attrs [0]).Message, "#B3");
}
}
#if !NET_2_1
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void TestAddDeclarativeSecurityAlreadyCreated ()
@@ -717,7 +717,7 @@ namespace MonoTests.System.Reflection.Emit
mb.AddDeclarativeSecurity (SecurityAction.Demand, set);
mb.AddDeclarativeSecurity (SecurityAction.Demand, set);
}
#endif
[AttributeUsage (AttributeTargets.Parameter)]
class ParamAttribute : Attribute
{
@@ -1992,6 +1992,16 @@ public class AssemblyNameTest {
Assert.IsNotNull (ex.Message, "#4");
}
}
[Test (Description="Xamarin bug #99 - whitespaces in key=value")]
public void WhiteSpaceInKeyValue ()
{
string nameWithSpaces = String.Format ("MySql.Data.Tests, PublicKey = \t {0}, Culture =\tneutral, Version=\t1.2.3.4", GetTokenString (publicKey1));
string fullName = "MySql.Data.Tests, Version=1.2.3.4, Culture=neutral, PublicKeyToken=ce5276d8687ec6dc";
var an = new AssemblyName (nameWithSpaces);
Assert.AreEqual (fullName, an.FullName);
}
#endif
}
@@ -69,12 +69,12 @@ namespace MonoTests.System.Reflection.Emit
#if NET_4_0
Assert.AreEqual ("foo.type[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", inst.FullName, "#3");
Assert.AreEqual ("foo.type[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], MonoTests.System.Reflection.Emit.MonoGenericClassTest, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", inst.AssemblyQualifiedName, "#4");
#elif NET_2_1
Assert.AreEqual ("foo.type[[System.Double, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.String, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", inst.FullName, "#3");
Assert.AreEqual ("foo.type[[System.Double, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.String, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], MonoTests.System.Reflection.Emit.MonoGenericClassTest, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", inst.AssemblyQualifiedName, "#4");
#else
Assert.AreEqual ("foo.type[[System.Double, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", inst.FullName, "#3");
Assert.AreEqual ("foo.type[[System.Double, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], MonoTests.System.Reflection.Emit.MonoGenericClassTest, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", inst.AssemblyQualifiedName, "#4");
#endif
Assert.AreEqual ("foo.type[System.Double,System.String]", inst.ToString (), "#5");
}
@@ -73,7 +73,7 @@ namespace MonoTests.System.Reflection
}
}
#if NET_2_0
#if NET_2_0 && !NET_2_1
public enum ParamEnum {
None = 0,
Foo = 1,
@@ -55,6 +55,9 @@ namespace MonoTests.System.Runtime.InteropServices {
}
[Test]
#if NET_2_1
[Ignore ("There's no GAC for the NET_2_1 based profiles (Moonlight, MonoTouch and Mono for Android")]
#endif
public void FromGlobalAccessCache ()
{
Assembly corlib = typeof (int).Assembly;
@@ -103,6 +103,9 @@ namespace MonoTests.System.Security.Cryptography.X509Certificates {
}
[Test]
#if NET_2_1
[Ignore ("This constructor always throw a NotSupportedException under NET_2_1 and is useless without CryptoAPI (i.e. outside Windows)")]
#endif
public void ConstructorIntPtr ()
{
byte[] cert = { 0x30,0x82,0x01,0xFF,0x30,0x82,0x01,0x6C,0x02,0x05,0x02,0x72,0x00,0x06,0xE8,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x02,0x05,0x00,0x30,0x5F,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x20,0x30,0x1E,0x06,0x03,0x55,0x04,0x0A,0x13,0x17,0x52,0x53,0x41,0x20,0x44,0x61,0x74,0x61,0x20,0x53,0x65,0x63,0x75,0x72,0x69,0x74,0x79,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x2E,0x30,0x2C,0x06,0x03,0x55,0x04,0x0B,0x13,0x25,0x53,0x65,0x63,0x75,0x72,0x65,0x20,0x53,0x65,0x72,0x76,
@@ -136,6 +136,9 @@ public class CryptoConfigTest {
// additional names (URL) used for XMLDSIG (System.Security.Cryptography.Xml)
// URL taken from http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/
[Test]
#if NET_2_1
[Ignore ("System.Security.dll is not part of Moonlight, MonoTouch and Mono for Android")]
#endif
public void CreateFromURL ()
{
// URL used in SignatureMethod element
@@ -26,7 +26,8 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
// NET_2_1 profile lacks some (of the few) CAS features required to execute those tests
#if NET_2_0 && !NET_2_1
using NUnit.Framework;
using System;
@@ -2,9 +2,10 @@
// EncoderReplacementFallbackBuffer.cs
//
// Author:
// Atsushi Enomoto <[email protected]>
// Atsushi Enomoto <[email protected]> <[email protected]>
//
// Copyright (C) 2005 Novell, Inc. http://www.novell.com
// Copyright (C) 2011 Xamain, Inc. http://xamarin.com
//
#if NET_2_0
@@ -85,6 +86,13 @@ namespace MonoTests.System.Text
Assert.IsFalse (b.MovePrevious (), "#8");
// Assert.AreEqual ('?', b.GetNextChar (), "#9");
}
[Test]
public void Reset ()
{
// Xamarin bug #545
Encoding.UTF8.GetBytes ("\uDE7E\uDE7E");
}
}
}
@@ -66,7 +66,7 @@ namespace MonoTests.System.Threading.Tasks
static Task<int> CreateNestedFuture(int level)
{
if (level == 0)
return Task.Factory.StartNew(() => { Thread.Sleep (10); return 1; });
return Task.Factory.StartNew(() => { Thread.Sleep (1); return 1; });
var t = CreateNestedFuture(level - 1);
return Task.Factory.StartNew(() => t.Result + 1);
@@ -75,14 +75,15 @@ namespace MonoTests.System.Threading.Tasks
[Test]
public void NestedFutureTest ()
{
var t = CreateNestedFuture(10);
var t2 = CreateNestedFuture(100);
var t3 = CreateNestedFuture(100);
var t4 = CreateNestedFuture(100);
Assert.AreEqual (11, t.Result);
Assert.AreEqual (101, t2.Result);
Assert.AreEqual (101, t3.Result);
Assert.AreEqual (101, t4.Result);
ParallelTestHelper.Repeat (delegate {
var t = CreateNestedFuture(10);
var t2 = CreateNestedFuture(100);
var t3 = CreateNestedFuture(100);
Assert.AreEqual (11, t.Result);
Assert.AreEqual (101, t2.Result);
Assert.AreEqual (101, t3.Result);
}, 50);
}
[Test]
@@ -1,4 +1,3 @@
#if NET_4_0
//
// TaskCompletionSourceTests.cs
//
@@ -25,6 +24,8 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if NET_4_0
using System;
using System.Threading;
using System.Threading.Tasks;
@@ -96,6 +97,24 @@ namespace MonoTests.System.Threading.Tasks
Assert.IsFalse (completionSource.TrySetCanceled (), "#8");
Assert.AreEqual (TaskStatus.Faulted, completionSource.Task.Status, "#9");
}
[Test]
public void SetExceptionInvalid ()
{
try {
completionSource.TrySetException (new ApplicationException[0]);
Assert.Fail ("#1");
} catch (ArgumentException) {
}
try {
completionSource.TrySetException (new [] { new ApplicationException (), null });
Assert.Fail ("#2");
} catch (ArgumentException) {
}
Assert.AreEqual (TaskStatus.WaitingForActivation, completionSource.Task.Status, "r1");
}
[Test, ExpectedException (typeof (InvalidOperationException))]
public void SetResultExceptionTest ()
@@ -1,7 +1,12 @@
#if NET_4_0
//
// TaskFactoryTest.cs
//
// Authors:
// Jérémie "Garuma" Laval <[email protected]>
// Marek Safar <[email protected]>
//
// Copyright (c) 2010 Jérémie "Garuma" Laval
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -23,9 +28,12 @@
//
//
#if NET_4_0 || MOBILE
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using NUnit.Framework;
@@ -34,14 +42,98 @@ namespace MonoTests.System.Threading.Tasks
[TestFixture]
public class TaskFactoryTests
{
class CompletedAsyncResult : IAsyncResult
{
public object AsyncState
{
get { throw new NotImplementedException (); }
}
public WaitHandle AsyncWaitHandle
{
get { throw new NotImplementedException (); }
}
public bool CompletedSynchronously
{
get { throw new NotImplementedException (); }
}
public bool IsCompleted
{
get { return true; }
}
}
class TestAsyncResult : IAsyncResult
{
WaitHandle wh = new ManualResetEvent (true);
public object AsyncState
{
get { throw new NotImplementedException (); }
}
public WaitHandle AsyncWaitHandle
{
get
{
return wh;
}
}
public bool CompletedSynchronously
{
get { throw new NotImplementedException (); }
}
public bool IsCompleted
{
get { return false; }
}
}
class TestScheduler : TaskScheduler
{
public bool ExecutedInline { get; set; }
protected override void QueueTask (Task task)
{
throw new NotImplementedException ();
}
protected override bool TryDequeue (Task task)
{
throw new NotImplementedException ();
}
protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
{
if (taskWasPreviouslyQueued)
throw new ArgumentException ("taskWasPreviouslyQueued");
if (task.Status != TaskStatus.WaitingToRun)
throw new ArgumentException ("task.Status");
ExecutedInline = true;
return TryExecuteTask (task);
}
protected override IEnumerable<Task> GetScheduledTasks ()
{
throw new NotImplementedException ();
}
}
TaskFactory factory;
[SetUp]
public void Setup ()
{
this.factory = Task.Factory;
}
[Test]
public void StartNewTest ()
{
@@ -49,62 +141,86 @@ namespace MonoTests.System.Threading.Tasks
factory.StartNew (() => result = true).Wait ();
Assert.IsTrue (result);
}
[Test]
public void NoDefaultScheduler ()
{
Assert.IsNull (factory.Scheduler, "#1");
}
[Test]
public void ContinueWhenAllTest ()
{
bool r1 = false, r2 = false, r3 = false;
Task[] tasks = new Task[3];
tasks[0] = new Task (() => { Thread.Sleep (100); r1 = true; });
tasks[1] = new Task (() => { Thread.Sleep (500); r2 = true; });
tasks[2] = new Task (() => { Thread.Sleep (300); r3 = true; });
bool result = false;
Task cont = factory.ContinueWhenAll (tasks, (ts) => { if (r1 && r2 && r3) result = true; });
foreach (Task t in tasks)
t.Start ();
cont.Wait ();
Assert.IsTrue (r1, "#1");
Assert.IsTrue (r2, "#2");
Assert.IsTrue (r3, "#3");
Assert.IsTrue (result, "#4");
}
[Test]
public void ContinueWhenAnyTest ()
{
bool r = false, result = false, finished = false;
Task[] tasks = new Task[2];
tasks[0] = new Task (() => { Thread.Sleep (300); r = true; });
tasks[1] = new Task (() => { SpinWait sw; while (!finished) sw.SpinOnce (); });
tasks[1] = new Task (() => { SpinWait sw = new SpinWait (); while (!finished) sw.SpinOnce (); });
//tasks[2] = new Task (() => { SpinWait sw; while (!finished) sw.SpinOnce (); });
Task cont = factory.ContinueWhenAny (tasks, (t) => { if (r) result = t == tasks[0]; finished = true; });
foreach (Task t in tasks)
t.Start ();
cont.Wait ();
Assert.IsTrue (r, "#1");
Assert.IsTrue (result, "#2");
Assert.IsTrue (finished, "#3");
}
[Test]
public void FromAsyncWithBeginTest ()
public void FromAsyncBeginInvoke_WithResult ()
{
bool result = false;
Func<int, int> func = (i) => {
Assert.IsTrue (Thread.CurrentThread.IsThreadPoolThread);
result = true; return i + 3;
};
var task = factory.FromAsync<int, int> (func.BeginInvoke, func.EndInvoke, 1, "state", TaskCreationOptions.AttachedToParent);
Assert.IsTrue (task.Wait (5000), "#1");
Assert.IsTrue (result, "#2");
Assert.AreEqual (4, task.Result, "#3");
Assert.AreEqual ("state", (string) task.AsyncState, "#4");
Assert.AreEqual (TaskCreationOptions.AttachedToParent, task.CreationOptions, "#5");
}
[Test]
public void FromAsyncBeginMethod_DirectResult ()
{
bool result = false;
bool continuationTest = false;
Func<int, int> func = (i) => { result = true; return i + 3; };
Task<int> task = factory.FromAsync<int, int> (func.BeginInvoke, func.EndInvoke, 1, null);
Task<int> task = factory.FromAsync<int> (func.BeginInvoke (1, delegate { }, null), func.EndInvoke);
var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
task.Wait ();
cont.Wait ();
@@ -115,24 +231,7 @@ namespace MonoTests.System.Threading.Tasks
}
[Test]
public void FromAsyncWithDirectAsyncResultTest ()
{
bool result = false;
bool continuationTest = false;
Func<int, int> func = (i) => { result = true; return i + 3; };
Task<int> task = factory.FromAsync<int> (func.BeginInvoke (1, delegate {}, null), func.EndInvoke);
var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
task.Wait ();
cont.Wait ();
Assert.IsTrue (result);
Assert.IsTrue (continuationTest);
Assert.AreEqual (4, task.Result);
}
[Test]
public void FromAsyncWithBeginAndExceptionTest ()
public void FromAsyncBeginMethod_Exception ()
{
bool result = false;
bool continuationTest = false;
@@ -142,7 +241,7 @@ namespace MonoTests.System.Threading.Tasks
var cont = task.ContinueWith (_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);
try {
task.Wait ();
} catch {}
} catch { }
cont.Wait ();
Assert.IsTrue (result);
@@ -151,6 +250,215 @@ namespace MonoTests.System.Threading.Tasks
var agg = task.Exception;
Assert.AreEqual (1, agg.InnerExceptions.Count);
Assert.IsInstanceOfType (typeof (ApplicationException), agg.InnerExceptions[0]);
Assert.AreEqual (TaskStatus.Faulted, task.Status);
try {
var a = task.Result;
Assert.Fail ();
} catch (AggregateException) {
}
}
[Test]
public void FromAsync_ArgumentsCheck ()
{
var result = new CompletedAsyncResult ();
try {
factory.FromAsync (null, l => { });
Assert.Fail ("#1");
} catch (ArgumentNullException) {
}
try {
factory.FromAsync (result, null);
Assert.Fail ("#2");
} catch (ArgumentNullException) {
}
try {
factory.FromAsync (result, l => { }, TaskCreationOptions.LongRunning);
Assert.Fail ("#3");
} catch (ArgumentOutOfRangeException) {
}
try {
factory.FromAsync (result, l => { }, TaskCreationOptions.PreferFairness);
Assert.Fail ("#4");
} catch (ArgumentOutOfRangeException) {
}
try {
factory.FromAsync (result, l => { }, TaskCreationOptions.None, null);
Assert.Fail ("#5");
} catch (ArgumentNullException) {
}
try {
factory.FromAsync (null, l => { }, null, TaskCreationOptions.None);
Assert.Fail ("#6");
} catch (ArgumentNullException) {
}
try {
factory.FromAsync ((a, b) => null, l => { }, null, TaskCreationOptions.LongRunning);
Assert.Fail ("#7");
} catch (ArgumentOutOfRangeException) {
}
}
[Test]
public void FromAsync_Completed ()
{
var completed = new CompletedAsyncResult ();
bool? valid = null;
Action<IAsyncResult> end = l => {
Assert.IsFalse (Thread.CurrentThread.IsThreadPoolThread, "#2");
valid = l == completed;
};
Task task = factory.FromAsync (completed, end);
Assert.IsTrue (valid == true, "#1");
}
[Test]
public void FromAsync_CompletedWithException ()
{
var completed = new CompletedAsyncResult ();
Action<IAsyncResult> end = l => {
throw new ApplicationException ();
};
Task task = factory.FromAsync (completed, end);
Assert.AreEqual (TaskStatus.Faulted, task.Status, "#1");
}
[Test]
public void FromAsync_CompletedCanceled ()
{
var completed = new CompletedAsyncResult ();
Action<IAsyncResult> end = l => {
throw new OperationCanceledException ();
};
Task task = factory.FromAsync (completed, end);
Assert.AreEqual (TaskStatus.Canceled, task.Status, "#1");
Assert.IsNull (task.Exception, "#2");
}
[Test]
public void FromAsync_SimpleAsyncResult ()
{
var result = new TestAsyncResult ();
bool called = false;
var task = factory.FromAsync (result, l => {
called = true;
});
Assert.IsTrue (task.Wait (1000), "#1");
Assert.IsTrue (called, "#2");
}
[Test]
public void FromAsync_ResultException ()
{
var result = new TestAsyncResult ();
var task = factory.FromAsync (result, l => {
throw new ApplicationException ();
});
try {
Assert.IsFalse (task.Wait (1000), "#1");
} catch (AggregateException) {
}
Assert.AreEqual (TaskStatus.Faulted, task.Status, "#2");
}
[Test]
public void FromAsync_ReturnInt ()
{
var result = new TestAsyncResult ();
bool called = false;
var task = factory.FromAsync<int> (result, l => {
called = true;
return 4;
});
Assert.IsTrue (task.Wait (1000), "#1");
Assert.IsTrue (called, "#2");
Assert.AreEqual (4, task.Result, "#3");
}
[Test]
public void FromAsync_Scheduler_Explicit ()
{
var result = new TestAsyncResult ();
bool called = false;
var scheduler = new TestScheduler ();
var task = factory.FromAsync (result, l => {
called = true;
}, TaskCreationOptions.None, scheduler);
Assert.IsTrue (task.Wait (5000), "#1");
Assert.IsTrue (called, "#2");
Assert.IsTrue (scheduler.ExecutedInline, "#3");
}
[Test]
public void FromAsync_Scheduler_Implicit ()
{
var result = new TestAsyncResult ();
bool called = false;
var scheduler = new TestScheduler ();
factory = new TaskFactory (scheduler);
Task task = factory.FromAsync (result, l => {
Assert.IsTrue (Thread.CurrentThread.IsThreadPoolThread, "#6");
called = true;
}, TaskCreationOptions.AttachedToParent);
Assert.AreEqual (TaskCreationOptions.AttachedToParent, task.CreationOptions, "#1");
Assert.IsNull (task.AsyncState, "#2");
Assert.IsTrue (task.Wait (5000), "#3");
Assert.IsTrue (called, "#4");
Assert.IsTrue (scheduler.ExecutedInline, "#5");
}
[Test]
public void FromAsync_BeginCallback ()
{
bool called = false;
bool called2 = false;
var task = factory.FromAsync (
(a, b, c) => {
if (a != "h")
Assert.Fail ("#10");
if ((TaskCreationOptions) c != TaskCreationOptions.AttachedToParent)
Assert.Fail ("#11");
Assert.IsFalse (Thread.CurrentThread.IsThreadPoolThread, "#12");
called2 = true;
b.Invoke (null);
return null;
},
l => {
called = true;
},
"h", TaskCreationOptions.AttachedToParent);
Assert.AreEqual (TaskCreationOptions.None, task.CreationOptions, "#1");
Assert.AreEqual (TaskCreationOptions.AttachedToParent, (TaskCreationOptions) task.AsyncState, "#2");
Assert.IsTrue (task.Wait (5000), "#3");
Assert.IsTrue (called, "#4");
Assert.IsTrue (called2, "#5");
}
}
}
@@ -0,0 +1,184 @@
//
// TaskFactory_T_Test.cs
//
// Author:
// Marek Safar <marek.safargmail.com>
//
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
// 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_4_0 || MOBILE
using System;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
namespace MonoTests.System.Threading.Tasks
{
[TestFixture]
public class TaskFactory_T_Tests
{
class CompletedAsyncResult : IAsyncResult
{
public object AsyncState
{
get { throw new NotImplementedException (); }
}
public WaitHandle AsyncWaitHandle
{
get { throw new NotImplementedException (); }
}
public bool CompletedSynchronously
{
get { throw new NotImplementedException (); }
}
public bool IsCompleted
{
get { return true; }
}
}
class TestAsyncResult : IAsyncResult
{
WaitHandle wh = new ManualResetEvent (true);
public object AsyncState
{
get { throw new NotImplementedException (); }
}
public WaitHandle AsyncWaitHandle
{
get
{
return wh;
}
}
public bool CompletedSynchronously
{
get { throw new NotImplementedException (); }
}
public bool IsCompleted
{
get { return false; }
}
}
[SetUp]
public void Setup ()
{
}
[Test]
public void ConstructorTest ()
{
try {
new TaskFactory<int> (TaskCreationOptions.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.LongRunning);
Assert.Fail ("#1");
} catch (ArgumentOutOfRangeException) {
}
try {
new TaskFactory<int> (TaskCreationOptions.None, TaskContinuationOptions.OnlyOnRanToCompletion);
Assert.Fail ("#2");
} catch (ArgumentOutOfRangeException) {
}
try {
new TaskFactory<int> (TaskCreationOptions.None, TaskContinuationOptions.NotOnRanToCompletion);
Assert.Fail ("#3");
} catch (ArgumentOutOfRangeException) {
}
}
[Test]
public void NoDefaultScheduler ()
{
var tf = new TaskFactory<object> ();
Assert.IsNull (tf.Scheduler, "#1");
}
[Test]
public void FromAsync_ArgumentsCheck ()
{
var factory = new TaskFactory<object> ();
var result = new CompletedAsyncResult ();
try {
factory.FromAsync (null, l => 1);
Assert.Fail ("#1");
} catch (ArgumentNullException) {
}
try {
factory.FromAsync (result, null);
Assert.Fail ("#2");
} catch (ArgumentNullException) {
}
try {
factory.FromAsync (result, l => 1, TaskCreationOptions.LongRunning);
Assert.Fail ("#3");
} catch (ArgumentOutOfRangeException) {
}
try {
factory.FromAsync (result, l => 1, TaskCreationOptions.PreferFairness);
Assert.Fail ("#4");
} catch (ArgumentOutOfRangeException) {
}
try {
factory.FromAsync (result, l => 1, TaskCreationOptions.None, null);
Assert.Fail ("#5");
} catch (ArgumentNullException) {
}
try {
factory.FromAsync (null, l => 1, null, TaskCreationOptions.None);
Assert.Fail ("#6");
} catch (ArgumentNullException) {
}
}
[Test]
public void FromAsync_SimpleAsyncResult ()
{
var result = new TestAsyncResult ();
var factory = new TaskFactory<int> ();
var task = factory.FromAsync (result, l => 5);
Assert.IsTrue (task.Wait (1000), "#1");
Assert.AreEqual (5, task.Result, "#2");
}
}
}
#endif
@@ -0,0 +1,113 @@
// TaskSchedulerTest.cs
//
// Copyright (c) 2008 Jérémie "Garuma" Laval
//
// 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_4_0
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using NUnit.Framework;
namespace MonoTests.System.Threading.Tasks
{
[TestFixture]
public class TaskSchedulerTests
{
[Test]
public void BasicRunSynchronouslyTest ()
{
bool ran = false;
var t = new Task (() => ran = true);
t.RunSynchronously ();
Assert.IsTrue (t.IsCompleted);
Assert.IsFalse (t.IsFaulted);
Assert.IsFalse (t.IsCanceled);
Assert.IsTrue (ran);
}
class LazyCatScheduler : TaskScheduler
{
public TaskStatus ExecuteInlineStatus {
get;
set;
}
protected override void QueueTask (Task task)
{
throw new NotImplementedException ();
}
protected override bool TryDequeue (Task task)
{
throw new NotImplementedException ();
}
protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
{
ExecuteInlineStatus = task.Status;
return true;
}
protected override IEnumerable<Task> GetScheduledTasks ()
{
throw new NotImplementedException ();
}
}
[Test]
public void RunSynchronouslyButNoExecutionTest ()
{
TaskSchedulerException ex = null;
var ts = new LazyCatScheduler ();
Task t = new Task (() => {});
try {
t.RunSynchronously (ts);
} catch (TaskSchedulerException e) {
ex = e;
}
Assert.IsNotNull (ex);
Assert.IsNotNull (ex.InnerException);
Assert.IsInstanceOfType (typeof (InvalidOperationException), ex.InnerException);
}
[Test]
public void RunSynchronouslyTaskStatusTest ()
{
var ts = new LazyCatScheduler ();
var t = new Task (() => { });
try {
t.RunSynchronously (ts);
} catch {}
Assert.AreEqual (TaskStatus.WaitingToRun, ts.ExecuteInlineStatus);
}
}
}
#endif
@@ -1,4 +1,4 @@
#if NET_4_0
//
// TaskTest.cs
//
// Copyright (c) 2008 Jérémie "Garuma" Laval
@@ -23,6 +23,8 @@
//
//
#if NET_4_0
using System;
using System.Threading;
using System.Threading.Tasks;
@@ -286,6 +288,17 @@ namespace MonoTests.System.Threading.Tasks
Assert.AreEqual (1, val);
}
[Test]
public void RunSynchronouslyArgumentChecks ()
{
Task t = new Task (() => { });
try {
t.RunSynchronously (null);
Assert.Fail ("#1");
} catch (ArgumentNullException) {
}
}
[Test]
public void UnobservedExceptionOnFinalizerThreadTest ()
{
@@ -312,6 +325,25 @@ namespace MonoTests.System.Threading.Tasks
t.Start ();
}
[Test, ExpectedException (typeof (InvalidOperationException))]
public void DisposeUnstartedTest ()
{
var t = new Task (() => { });
t.Dispose ();
}
[Test]
public void ThrowingUnrelatedCanceledExceptionTest ()
{
Task t = new Task (() => {
throw new TaskCanceledException ();
});
t.RunSynchronously ();
Assert.IsTrue (t.IsFaulted);
Assert.IsFalse (t.IsCanceled);
}
}
}
#endif
@@ -3237,6 +3237,21 @@ namespace MonoTests.System
asm.GetTypes();
}
[Test]
public void ResourceResolve ()
{
bool called = false;
ResolveEventHandler del = delegate (object sender, ResolveEventArgs args) {
called = true;
return null;
};
AppDomain.CurrentDomain.ResourceResolve += del;
Stream st = Assembly.GetExecutingAssembly ().GetManifestResourceStream ("NOT_EXISTING");
Assert.IsTrue (called);
AppDomain.CurrentDomain.ResourceResolve -= del;
}
private static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
return Assembly.ReflectionOnlyLoad(args.Name);
@@ -128,7 +128,7 @@ namespace MonoTests.System
Assert.IsFalse (d.IsSynchronized, "IsSynchronized");
}
#if NET_2_0 && !TARGET_JVM
#if NET_2_0 && !TARGET_JVM && !NET_2_1
[Test] // bug #333740
public void GetEnvironmentVariables_NewlySet ()
{
@@ -151,7 +151,7 @@ namespace MonoTests.System
Assert.IsNotNull (args [0], "application");
}
#if NET_2_0
#if NET_2_0 && !NET_2_1
[Test]
[ExpectedException (typeof (ArgumentException))]
public void GetEnvironmentVariable_Target_Invalid ()
+4 -4
View File
@@ -794,7 +794,7 @@ public class TimeSpanTest {
ParseHelper (" 13:45:15 ",false, false, "13:45:15");
ParseHelper (" -1:2:3 ", false, false, "-01:02:03");
#if NET_4_0
#if NET_4_0 || NET_2_1
// In 4.0 when the first part is out of range, it parses it as day.
ParseHelper (" 25:11:12 ", false, false, "25.11:12:00");
ParseHelper (" 24:11:12 ", false, false, "24.11:12:00");
@@ -811,14 +811,14 @@ public class TimeSpanTest {
ParseHelper ("24:60:60", false, true, "dontcare");
ParseHelper ("0001:0002:0003.12 ", false, false, "01:02:03.1200000");
#if NET_4_0
#if NET_4_0 || NET_2_1
// In 4.0 when a section has more than 7 digits an OverflowException is thrown.
ParseHelper (" 1:2:3:12345678 ", false, true, "dontcare");
#else
ParseHelper (" 1:2:3:12345678 ", true, false, "dontcare");
#endif
#if NET_4_0
#if NET_4_0 || NET_2_1
ParseHelper ("10:11:12:13", false, false, "10.11:12:13"); // Days using : instead of . as separator
ParseHelper ("10.11", true, false, "dontcare"); // days+hours is invalid
@@ -894,7 +894,7 @@ public class TimeSpanTest {
{
// hours should be between 0 and 23 but format is also invalid (too many dots)
// In 2.0 overflow as precedence over format, but not in 4.0
#if NET_4_0
#if NET_4_0 || NET_2_1
try {
TimeSpan.Parse ("0.99.99.0");
Assert.Fail ("#A1");
+4
View File
@@ -3894,6 +3894,10 @@ PublicKeyToken=b77a5c561934e089"));
MustTLE (string.Format ("{0}ZZZZ,{1}", typeof (MyRealEnum).FullName, aqn));
}
[Test] //bug #124
public void IsAssignableFromWithNullable () {
Console.WriteLine(typeof(IEnumerable<int?>).IsAssignableFrom(typeof(IEnumerable<int>)));
}
#endif
public abstract class Stream : IDisposable
+3 -1
View File
@@ -1531,6 +1531,7 @@ System/Predicate.cs
System.Collections.Generic/Comparer.cs
System.Threading.Tasks/TaskFactory.cs
System.Threading.Tasks/TaskFactory_T.cs
System.Threading.Tasks/TaskStatus.cs
System.Threading.Tasks/TaskCreationOptions.cs
System.Threading.Tasks/ThreadWorker.cs
@@ -1540,8 +1541,9 @@ System.Threading.Tasks/CyclicDeque.cs
System.Threading.Tasks/TaskScheduler.cs
System.Threading.Tasks/TaskContinuationOptions.cs
System.Threading.Tasks/TaskCanceledException.cs
System.Threading.Tasks/Future.cs
System.Threading.Tasks/Task_T.cs
System.Threading.Tasks/Task.cs
System.Threading.Tasks/TaskDebuggerView.cs
System.Threading.Tasks/TaskCompletionSource.cs
System.Threading.Tasks/TaskSchedulerException.cs
System.Collections.Concurrent/OrderablePartitioner.cs
Loaded 100 of 164 files, more files were not shown because too many files have changed in this diff. Show more