#define g_utf8_get_char_validated monoeg_utf8_get_char_validated
#define g_utf8_prev_char monoeg_utf8_prev_char
#define g_utf8_to_ucs4 monoeg_utf8_to_ucs4
+
+
+#define g_log_default_handler monoeg_log_default_handler
+#define g_log_set_default_handler monoeg_log_set_default_handler
+#define g_set_print_handler monoeg_set_print_handler
+#define g_set_printerr_handler monoeg_set_printerr_handler
#define g_message(...) g_log (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, __VA_ARGS__)
#define g_debug(...) g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, __VA_ARGS__)
#endif /* ndef HAVE_C99_SUPPORT */
-#define g_log_set_handler(a,b,c,d)
-#define G_GNUC_INTERNAL
+typedef void (*GLogFunc) (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data);
+typedef void (*GPrintFunc) (const gchar *string);
+void g_log_default_handler (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer unused_data);
+GLogFunc g_log_set_default_handler (GLogFunc log_func, gpointer user_data);
+GPrintFunc g_set_print_handler (GPrintFunc func);
+GPrintFunc g_set_printerr_handler (GPrintFunc func);
/*
* Conversions
*/
/* The current fatal levels, error is always fatal */
static GLogLevelFlags fatal = G_LOG_LEVEL_ERROR;
+static GLogFunc default_log_func;
+static gpointer default_log_func_user_data;
+static GPrintFunc stdout_handler, stderr_handler;
-#if PLATFORM_ANDROID
-#include <android/log.h>
-
-static android_LogPriority
-to_android_priority (GLogLevelFlags log_level)
-{
- switch (log_level & G_LOG_LEVEL_MASK)
- {
- case G_LOG_LEVEL_ERROR: return ANDROID_LOG_FATAL;
- case G_LOG_LEVEL_CRITICAL: return ANDROID_LOG_ERROR;
- case G_LOG_LEVEL_WARNING: return ANDROID_LOG_WARN;
- case G_LOG_LEVEL_MESSAGE: return ANDROID_LOG_INFO;
- case G_LOG_LEVEL_INFO: return ANDROID_LOG_DEBUG;
- case G_LOG_LEVEL_DEBUG: return ANDROID_LOG_VERBOSE;
- }
- return ANDROID_LOG_UNKNOWN;
-}
-
-static void
-out_vfprintf (FILE *ignore, const gchar *format, va_list args)
-{
- /* TODO: provide a proper app name */
- __android_log_vprint (ANDROID_LOG_ERROR, "mono", format, args);
-}
-#elif MONOTOUCH && defined(__arm__)
-#include <asl.h>
-
-static int
-to_asl_priority (GLogLevelFlags log_level)
-{
- switch (log_level & G_LOG_LEVEL_MASK)
- {
- case G_LOG_LEVEL_ERROR: return ASL_LEVEL_CRIT;
- case G_LOG_LEVEL_CRITICAL: return ASL_LEVEL_ERR;
- case G_LOG_LEVEL_WARNING: return ASL_LEVEL_WARNING;
- case G_LOG_LEVEL_MESSAGE: return ASL_LEVEL_NOTICE;
- case G_LOG_LEVEL_INFO: return ASL_LEVEL_INFO;
- case G_LOG_LEVEL_DEBUG: return ASL_LEVEL_DEBUG;
- }
- return ASL_LEVEL_ERR;
-}
-
-static void
-out_vfprintf (FILE *ignore, const gchar *format, va_list args)
-{
- asl_vlog (NULL, NULL, ASL_LEVEL_WARNING, format, args);
-}
-
-#else
-static void
-out_vfprintf (FILE *file, const gchar *format, va_list args)
-{
- vfprintf (file, format, args);
-}
-#endif
+static void default_stdout_handler (const gchar *string);
+static void default_stderr_handler (const gchar *string);
void
g_print (const gchar *format, ...)
{
+ char *msg;
va_list args;
va_start (args, format);
+ if (vasprintf (&msg, format, args) < 0)
+ return;
+ va_end (args);
- out_vfprintf (stdout, format, args);
+ if (!stdout_handler)
+ stdout_handler = default_stdout_handler;
- va_end (args);
+ stdout_handler (msg);
+ free (msg);
}
void
g_printerr (const gchar *format, ...)
{
+ char *msg;
va_list args;
va_start (args, format);
+ if (vasprintf (&msg, format, args) < 0)
+ return;
+ va_end (args);
- out_vfprintf (stderr, format, args);
+ if (!stderr_handler)
+ stderr_handler = default_stderr_handler;
- va_end (args);
+ stdout_handler (msg);
+ free (msg);
}
GLogLevelFlags
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);
-#elif MONOTOUCH && defined(__arm__)
- asl_vlog (NULL, NULL, to_asl_priority (log_level), format, args);
-#else
char *msg;
+
+ if (!default_log_func)
+ default_log_func = g_log_default_handler;
if (vasprintf (&msg, format, args) < 0)
return;
-#ifdef G_OS_WIN32
- printf ("%s%s%s\n",
- log_domain != NULL ? log_domain : "",
- log_domain != NULL ? ": " : "",
- msg);
-#else
-#if MONOTOUCH
- FILE *target = stderr;
-#else
- FILE *target = stdout;
-#endif
-
- fprintf (target, "%s%s%s\n",
- log_domain != NULL ? log_domain : "",
- log_domain != NULL ? ": " : "",
- msg);
-#endif
+ default_log_func (log_domain, log_level, msg, default_log_func_user_data);
free (msg);
- if (log_level & fatal){
- fflush (stdout);
- fflush (stderr);
- }
-#endif
- if (log_level & fatal){
- abort ();
- }
}
void
va_start (args, format);
g_logv (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR, format, args);
va_end (args);
- abort ();
+}
+
+
+#if PLATFORM_ANDROID
+#include <android/log.h>
+
+static android_LogPriority
+to_android_priority (GLogLevelFlags log_level)
+{
+ switch (log_level & G_LOG_LEVEL_MASK)
+ {
+ case G_LOG_LEVEL_ERROR: return ANDROID_LOG_FATAL;
+ case G_LOG_LEVEL_CRITICAL: return ANDROID_LOG_ERROR;
+ case G_LOG_LEVEL_WARNING: return ANDROID_LOG_WARN;
+ case G_LOG_LEVEL_MESSAGE: return ANDROID_LOG_INFO;
+ case G_LOG_LEVEL_INFO: return ANDROID_LOG_DEBUG;
+ case G_LOG_LEVEL_DEBUG: return ANDROID_LOG_VERBOSE;
+ }
+ return ANDROID_LOG_UNKNOWN;
+}
+
+void
+g_log_default_handler (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer unused_data)
+{
+ __android_log_write (to_android_priority (log_level), log_domain, message);
+ if (log_level & fatal)
+ abort ();
+}
+
+static void
+default_stdout_handler (const gchar *message)
+{
+ /* TODO: provide a proper app name */
+ __android_log_write (ANDROID_LOG_ERROR, "mono", message);
+}
+
+static void
+default_stderr_handler (const gchar *message)
+{
+ /* TODO: provide a proper app name */
+ __android_log_write (ANDROID_LOG_ERROR, "mono", message);
+}
+
+
+#elif MONOTOUCH
+#include <asl.h>
+
+static int
+to_asl_priority (GLogLevelFlags log_level)
+{
+ switch (log_level & G_LOG_LEVEL_MASK)
+ {
+ case G_LOG_LEVEL_ERROR: return ASL_LEVEL_CRIT;
+ case G_LOG_LEVEL_CRITICAL: return ASL_LEVEL_ERR;
+ case G_LOG_LEVEL_WARNING: return ASL_LEVEL_WARNING;
+ case G_LOG_LEVEL_MESSAGE: return ASL_LEVEL_NOTICE;
+ case G_LOG_LEVEL_INFO: return ASL_LEVEL_INFO;
+ case G_LOG_LEVEL_DEBUG: return ASL_LEVEL_DEBUG;
+ }
+ return ASL_LEVEL_ERR;
+}
+
+void
+g_log_default_handler (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer unused_data)
+{
+ asl_vlog (NULL, NULL, to_asl_priority (log_level), "%s", message);
+ if (log_level & fatal)
+ abort ();
+}
+
+static void
+default_stdout_handler (const gchar *message)
+{
+ asl_vlog (NULL, NULL, ASL_LEVEL_WARNING, "%s", message);
+}
+
+static void
+default_stderr_handler (const gchar *message)
+{
+ asl_vlog (NULL, NULL, ASL_LEVEL_WARNING, "%s", message);
+}
+
+#else
+
+void
+g_log_default_handler (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer unused_data)
+{
+ FILE *target = stdout;
+
+ fprintf (target, "%s%s%s\n",
+ log_domain != NULL ? log_domain : "",
+ log_domain != NULL ? ": " : "",
+ message);
+
+ if (log_level & fatal) {
+ fflush (stdout);
+ fflush (stderr);
+ abort ();
+ }
+}
+
+static void
+default_stdout_handler (const gchar *string)
+{
+ fprintf (stdout, "%s", string);
+}
+
+static void
+default_stderr_handler (const gchar *string)
+{
+ fprintf (stderr, "%s", string);
+}
+
+#endif
+
+GLogFunc
+g_log_set_default_handler (GLogFunc log_func, gpointer user_data)
+{
+ GLogFunc old = default_log_func;
+ default_log_func = log_func;
+ default_log_func_user_data = user_data;
+ return old;
+}
+
+GPrintFunc
+g_set_print_handler (GPrintFunc func)
+{
+ GPrintFunc old = stdout_handler;
+ stdout_handler = func;
+ return old;
+}
+
+GPrintFunc
+g_set_printerr_handler (GPrintFunc func)
+{
+ GPrintFunc old = stderr_handler;
+ stdout_handler = func;
+ return old;
}
-Subproject commit 92df59f033ef81a9b5a9cc6b09d44ed18d244517
+Subproject commit 22534de2098acbcf208f6b06836d122dab799e4b
if (propertyName != null)
element.SetAttribute ("PropertyName", propertyName);
}
-
- [MonoTODO]
+
public bool Execute ()
{
- bool result = false;
TaskEngine taskEngine;
LogTaskStarted ();
- ITask task = null;
+ ITask task;
try {
- try {
- task = InitializeTask ();
- } catch (Exception e) {
- LogError ("Error initializing task {0}: {1}", taskElement.LocalName, e.Message);
- LogMessage (MessageImportance.Low, "Error initializing task {0}: {1}",
- taskElement.LocalName, e.ToString ());
- return false;
- }
+ task = InitializeTask ();
+ } catch (Exception e) {
+ LogError ("Error initializing task {0}: {1}", taskElement.LocalName, e.Message);
+ LogMessage (MessageImportance.Low, "Error initializing task {0}: {1}",
+ taskElement.LocalName, e.ToString ());
+ return false;
+ }
+
+ try {
+ taskEngine = new TaskEngine (parentTarget.Project, task, Type);
+ taskEngine.Prepare (GetParameters ());
+ var result = taskEngine.Execute ();
+ if (result)
+ taskEngine.PublishOutput (taskElement, taskEngine.ValueFromExecution);
- try {
- taskEngine = new TaskEngine (parentTarget.Project);
- taskEngine.Prepare (task, this.taskElement, GetParameters (), this.Type);
- result = taskEngine.Execute ();
- if (result)
- taskEngine.PublishOutput ();
- } catch (Exception e) {
- task_logger.LogError ("Error executing task {0}: {1}", taskElement.LocalName, e.Message);
- task_logger.LogMessage (MessageImportance.Low,
- "Error executing task {0}: {1}", taskElement.LocalName, e.ToString ());
- result = false;
- }
- } finally {
LogTaskFinished (result);
+ return result;
+ } catch (Exception e) {
+ task_logger.LogError ("Error executing task {0}: {1}", taskElement.LocalName, e.Message);
+ task_logger.LogMessage (MessageImportance.Low,
+ "Error executing task {0}: {1}", taskElement.LocalName, e.ToString ());
+ return false;
}
-
- return result;
}
return taskElement.GetAttribute (attributeName);
}
+
+ bool IBuildTask.ResolveOutputItems ()
+ {
+ var taskEngine = new TaskEngine (parentTarget.Project, null, Type);
+
+ taskEngine.PublishOutput (taskElement, l => {
+ var pv = GetParameterValue (l.Name);
+
+ Expression exp = new Expression ();
+ exp.Parse (pv, ParseOptions.AllowItemsNoMetadataAndSplit);
+ return exp.ConvertTo (parentTarget.Project, l.PropertyType);
+ });
+
+ return true;
+ }
public void SetParameterValue (string parameterName,
string parameterValue)
foreach (XmlAttribute attrib in XmlElement.Attributes)
yield return attrib.Value;
}
+
+ public bool ResolveOutputItems ()
+ {
+ return true;
+ }
}
}
{
return GetAttributes ();
}
-
+
+ public bool ResolveOutputItems ()
+ {
+ return true;
+ }
}
}
}
bool Execute ();
+ bool ResolveOutputItems ();
IEnumerable<string> GetAttributes ();
}
using Microsoft.Build.Framework;
namespace Microsoft.Build.BuildEngine {
-
internal class TargetBatchingImpl : BatchingImplBase
{
string inputs;
{
executeOnErrors = false;
try {
- string reason;
- if (!BuildTargetNeeded (out reason)) {
- LogTargetStarted (target);
- LogTargetSkipped (target, reason);
- LogTargetFinished (target, true);
- return true;
- }
-
- if (!String.IsNullOrEmpty (reason))
- target.Engine.LogMessage (MessageImportance.Low, reason);
-
Init ();
ParseTargetAttributes (target);
executeOnErrors = false;
LogTargetStarted (target);
+
if (bucket != null)
project.PushBatch (bucket, commonItemsByName);
+
try {
+ TaskExecutionMode taskExecutionMode;
string reason;
if (!BuildTargetNeeded (out reason)) {
LogTargetSkipped (target, reason);
- return true;
- }
+ taskExecutionMode = TaskExecutionMode.SkipAndSetOutput;
+ } else {
+ taskExecutionMode = TaskExecutionMode.Complete;
- if (!String.IsNullOrEmpty (reason))
- target.Engine.LogMessage (MessageImportance.Low, reason);
+ if (!String.IsNullOrEmpty (reason))
+ target.Engine.LogMessage (MessageImportance.Low, reason);
+ }
for (int i = 0; i < target.BuildTasks.Count; i ++) {
//FIXME: parsing attributes repeatedly
IBuildTask bt = target.BuildTasks [i];
TaskBatchingImpl batchingImpl = new TaskBatchingImpl (project);
- bool task_result = batchingImpl.Build (bt, out executeOnErrors);
+ bool task_result = batchingImpl.Build (bt, taskExecutionMode, out executeOnErrors);
if (task_result)
continue;
} finally {
if (bucket != null)
project.PopBatch ();
+
LogTargetFinished (target, target_result);
}
{
}
- public bool Build (IBuildTask buildTask, out bool executeOnErrors)
+ public bool Build (IBuildTask buildTask, TaskExecutionMode taskExecutionMode, out bool executeOnErrors)
{
executeOnErrors = false;
try {
// populate list of referenced items and metadata
ParseTaskAttributes (buildTask);
if (consumedMetadataReferences.Count == 0) {
- // No batching required
- if (ConditionParser.ParseAndEvaluate (buildTask.Condition, project))
- return buildTask.Execute ();
- else // skipped, it should be logged
- return true;
+ return Execute (buildTask, taskExecutionMode);
}
BatchAndPrepareBuckets ();
- return Run (buildTask, out executeOnErrors);
+ return Run (buildTask, taskExecutionMode, out executeOnErrors);
} finally {
consumedItemsByName = null;
consumedMetadataReferences = null;
}
}
- bool Run (IBuildTask buildTask, out bool executeOnErrors)
+ bool Run (IBuildTask buildTask, TaskExecutionMode taskExecutionMode, out bool executeOnErrors)
{
executeOnErrors = false;
bool retval = true;
if (buckets.Count == 0) {
// batched mode, but no values in the corresponding items!
- if (ConditionParser.ParseAndEvaluate (buildTask.Condition, project)) {
- retval = buildTask.Execute ();
- if (!retval && !buildTask.ContinueOnError)
- executeOnErrors = true;
- }
+ retval = Execute (buildTask, taskExecutionMode);
+ if (!retval && !buildTask.ContinueOnError)
+ executeOnErrors = true;
return retval;
}
foreach (Dictionary<string, BuildItemGroup> bucket in buckets) {
project.PushBatch (bucket, commonItemsByName);
try {
- if (ConditionParser.ParseAndEvaluate (buildTask.Condition, project)) {
- retval = buildTask.Execute ();
- if (!retval && !buildTask.ContinueOnError) {
- executeOnErrors = true;
- break;
- }
+ retval = Execute (buildTask, taskExecutionMode);
+ if (!retval && !buildTask.ContinueOnError) {
+ executeOnErrors = true;
+ break;
}
} finally {
project.PopBatch ();
return retval;
}
+ bool Execute (IBuildTask buildTask, TaskExecutionMode taskExecutionMode)
+ {
+ if (ConditionParser.ParseAndEvaluate (buildTask.Condition, project)) {
+ switch (taskExecutionMode) {
+ case TaskExecutionMode.Complete:
+ return buildTask.Execute ();
+ case TaskExecutionMode.SkipAndSetOutput:
+ return buildTask.ResolveOutputItems ();
+ default:
+ throw new NotImplementedException ();
+ }
+ }
+
+ return true;
+ }
+
// Parse task attributes to get list of referenced metadata and items
// to determine batching
namespace Microsoft.Build.BuildEngine {
internal class TaskEngine {
- ITask task;
- XmlElement taskElement;
Type taskType;
Project parentProject;
+ ITask task;
static Type requiredAttribute;
static Type outputAttribute;
outputAttribute = typeof (Microsoft.Build.Framework.OutputAttribute);
}
- public TaskEngine (Project project)
+ public TaskEngine (Project project, ITask task, Type taskType)
{
parentProject = project;
+ this.task = task;
+ this.taskType = taskType;
}
// Rules (inferred) for property values incase of empty data
// string/
// ITaskItem[] empty/whitespace null No
- public void Prepare (ITask task, XmlElement taskElement,
- IDictionary <string, string> parameters, Type taskType)
+ public void Prepare (IDictionary <string, string> parameters)
{
Dictionary <string, object> values;
PropertyInfo currentProperty;
PropertyInfo[] properties;
object value;
- this.task = task;
- this.taskElement = taskElement;
- this.taskType = taskType;
values = new Dictionary <string, object> (StringComparer.OrdinalIgnoreCase);
foreach (KeyValuePair <string, string> de in parameters) {
InitializeParameter (pi, val);
}
}
-
+
public bool Execute ()
{
return task.Execute ();
}
- public void PublishOutput ()
+ public void PublishOutput (XmlElement taskElement, Func<PropertyInfo, object> valueProvider)
{
XmlElement xmlElement;
- PropertyInfo propertyInfo;
string propertyName;
string taskParameter;
string itemName;
- object o;
foreach (XmlNode xmlNode in taskElement.ChildNodes) {
if (!(xmlNode is XmlElement))
taskParameter = xmlElement.GetAttribute ("TaskParameter");
itemName = xmlElement.GetAttribute ("ItemName");
propertyName = xmlElement.GetAttribute ("PropertyName");
-
- propertyInfo = taskType.GetProperty (taskParameter, BindingFlags.Public | BindingFlags.Instance |
- BindingFlags.IgnoreCase);
+
+ var propertyInfo = taskType.GetProperty (taskParameter, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
+
if (propertyInfo == null)
- throw new InvalidProjectFileException (String.Format (
- "The parameter '{0}' was not found for the '{1}' task.", taskParameter, taskElement.Name));
+ throw new InvalidProjectFileException (String.Format ("The parameter '{0}' was not found for the '{1}' task.", taskParameter, taskElement.Name));
+
if (!propertyInfo.IsDefined (outputAttribute, false))
- throw new InvalidProjectFileException ("This is not output property.");
+ throw new InvalidProjectFileException ("This is not output property.");
- o = propertyInfo.GetValue (task, null);
+ var o = valueProvider (propertyInfo);
+
if (itemName != String.Empty) {
PublishItemGroup (propertyInfo, o, itemName);
} else {
return true;
}
+
+ public object ValueFromExecution (PropertyInfo propertyInfo)
+ {
+ return propertyInfo.GetValue (task, null);
+ }
}
}
--- /dev/null
+//
+// TaskExecutionMode.cs
+//
+// Authors:
+// Marek Safar <marek.safar@gmail.com>
+//
+// Copyright (C) 2014 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.
+//
+
+namespace Microsoft.Build.BuildEngine
+{
+ enum TaskExecutionMode
+ {
+ Complete = 0,
+ SkipAndSetOutput = 1
+ }
+}
\ No newline at end of file
Microsoft.Build.BuildEngine/Target.cs
Microsoft.Build.BuildEngine/TaskDatabase.cs
Microsoft.Build.BuildEngine/TaskEngine.cs
+Microsoft.Build.BuildEngine/TaskExecutionMode.cs
Microsoft.Build.BuildEngine/Token.cs
Microsoft.Build.BuildEngine/Toolset.cs
Microsoft.Build.BuildEngine/ToolsetCollection.cs
get {
return message;
}
+#if NET_4_0
+ protected set {
+ message = value;
+ }
+#endif
}
public string SenderName {
{
}
- public BuildEventContext (int nodeId, int projectInstanceId, int targetId, int projectContextId, int taskId)
- : this (rnd.Next (), nodeId, projectInstanceId, targetId, projectContextId, taskId)
+ public BuildEventContext (int nodeId, int projectInstanceId, int projectContextId, int targetId, int taskId)
+ : this (rnd.Next (), nodeId, projectInstanceId, projectContextId, targetId, taskId)
{
}
- public BuildEventContext (int submissionId, int nodeId, int projectInstanceId, int targetId, int projectContextId, int taskId)
+ public BuildEventContext (int submissionId, int nodeId, int projectInstanceId, int projectContextId, int targetId, int taskId)
{
SubmissionId = submissionId;
NodeId = nodeId;
public int TaskId { get; private set; }
// MSDN document says "true if the references are equal, false otherwise." but that doesn't make sense.
- public override bool Equals (object other)
+ public override bool Equals (object obj)
{
- var o = other as BuildEventContext;
+ var o = obj as BuildEventContext;
return (object) o != null &&
o.NodeId == NodeId &&
o.ProjectContextId == ProjectContextId &&
namespace Microsoft.Build.Framework
{
[Serializable]
- public abstract class LazyFormattedBuildEventArgs : BuildEventArgs {
+ public class LazyFormattedBuildEventArgs : BuildEventArgs {
string message, format;
object[] args;
{
public enum RegisteredTaskObjectLifetime
{
- AppDomain,
- Build
+ Build,
+ AppDomain
}
}
#endif
namespace Microsoft.Build.Tasks
{
- public class CodeTaskFactory : ITaskFactory2
+ public class CodeTaskFactory : ITaskFactory
{
public CodeTaskFactory ()
{
public void CleanupTask (ITask task)
{
}
- public ITask CreateTask (IBuildEngine taskFactoryLoggingHost)
+ public ITask CreateTask (IBuildEngine loggingHost)
{
- return CreateTask (taskFactoryLoggingHost, null);
+ return CreateTask (loggingHost, null);
}
- public ITask CreateTask (IBuildEngine taskFactoryLoggingHost, IDictionary<string, string> taskIdentityParameters)
+
+ ITask CreateTask (IBuildEngine taskFactoryLoggingHost, IDictionary<string, string> taskIdentityParameters)
{
if (assembly == null)
return null;
{
return parameter_group != null ? parameter_group.Values.ToArray () : new TaskPropertyInfo [0];
}
- public bool Initialize (string taskName, IDictionary<string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost)
+ public bool Initialize (string taskName, IDictionary<string, TaskPropertyInfo> taskParameters, string taskElementContents, IBuildEngine taskFactoryLoggingHost)
{
- return Initialize (taskName, null, parameterGroup, taskBody, taskFactoryLoggingHost);
+ return Initialize (taskName, null, taskParameters, taskElementContents, taskFactoryLoggingHost);
}
- public bool Initialize (string taskName, IDictionary<string, string> factoryIdentityParameters, IDictionary<string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost)
+ bool Initialize (string taskName, IDictionary<string, string> factoryIdentityParameters, IDictionary<string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost)
{
task_name = taskName;
if (parameterGroup != null)
protected abstract string CreateManifestName (string fileName,
string linkFileName,
- string rootNamespace,
+ string rootNamespaceName,
string dependentUponFileName,
Stream binaryStream);
///// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/////
-#if NET_2_0
+#if !NET_4_0
using System;
using Microsoft.Build.Framework;
Log.LogMessage (MessageImportance.Normal, "Executing: " + command);
}
- protected override void LogEventsFromTextOutput (string singleLine, MessageImportance importance)
+ protected override void LogEventsFromTextOutput (string singleLine, MessageImportance messageImportance)
{
#if NET_4_0
if (IgnoreStandardErrorWarningFormat ||
(!errorMatcher (singleLine) && !warningMatcher (singleLine)))
#endif
- Log.LogMessage (importance, singleLine);
+ Log.LogMessage (messageImportance, singleLine);
}
#if NET_4_0
namespace Microsoft.Build.Tasks {
//FIXME: This should be in v3.5 only
- public sealed class FindAppConfigFile : TaskExtension {
+ public class FindAppConfigFile : TaskExtension {
public FindAppConfigFile ()
{
"It should have either 2 or 3 comma separated components.", moniker_literal);
}
- [Required]
public string TargetFrameworkMoniker { get; set; }
public string RootPath { get; set; }
public string TargetFrameworkMonikerDisplayName { get; set; }
[Output]
- public string[] ReferenceAssemblyPaths { get; set; }
+ public string[] ReferenceAssemblyPaths { get; private set; }
[Output]
- public string[] FullFrameworkReferenceAssemblyPaths { get; set; }
+ public string[] FullFrameworkReferenceAssemblyPaths { get; private set; }
static string DefaultFrameworksBasePath {
get {
get { return findSerializationAssemblies; }
set { findSerializationAssemblies = value; }
}
-
+/*
public string[] InstalledAssemblyTables {
get { return installedAssemblyTables; }
set { installedAssemblyTables = value; }
}
-
+*/
[Output]
public ITaskItem[] RelatedFiles {
get { return relatedFiles; }
//
-// UpdateManifest.cs
+// VCBuild.cs
//
// Author:
// Leszek Ciesielski <skolima@gmail.com>
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
-#if NET_2_0
+#if !NET_4_0
using System;
using System.Collections.Specialized;
return true;
}
- protected override void LogEventsFromTextOutput (string singleLine, MessageImportance importance)
+ protected override void LogEventsFromTextOutput (string singleLine, MessageImportance messageImportance)
{
singleLine = singleLine.Trim ();
if (singleLine.Length == 0)
Match match = ErrorRegex.Match (singleLine);
if (!match.Success) {
- Log.LogMessage (importance, singleLine);
+ Log.LogMessage (messageImportance, singleLine);
return;
}
Log.LogError (null, code, null, filename, lineNumber, columnNumber, -1,
-1, text, null);
} else {
- Log.LogMessage (importance, singleLine);
+ Log.LogMessage (messageImportance, singleLine);
}
}
}
[MonoTODO]
- public bool IsVerbosityAtLeast (LoggerVerbosity verbosity)
+ public bool IsVerbosityAtLeast (LoggerVerbosity checkVerbosity)
{
- return (this.verbosity >= verbosity) ? true : false;
+ return this.verbosity >= checkVerbosity;
}
}
}
hasLoggedErrors = true;
}
- public void LogErrorFromException (Exception e)
+ public void LogErrorFromException (Exception exception)
{
- LogErrorFromException (e, true);
+ LogErrorFromException (exception, true);
}
- public void LogErrorFromException (Exception e,
+ public void LogErrorFromException (Exception exception,
bool showStackTrace)
{
- LogErrorFromException (e, showStackTrace, true, String.Empty);
+ LogErrorFromException (exception, showStackTrace, true, String.Empty);
}
[MonoTODO ("Arguments @showDetail and @file are not honored")]
- public void LogErrorFromException (Exception e,
+ public void LogErrorFromException (Exception exception,
bool showStackTrace, bool showDetail, string file)
{
- if (e == null)
- throw new ArgumentNullException ("e");
+ if (exception == null)
+ throw new ArgumentNullException ("exception");
StringBuilder sb = new StringBuilder ();
- sb.Append (e.Message);
+ sb.Append (exception.Message);
if (showStackTrace == true)
- sb.Append (e.StackTrace);
+ sb.Append (exception.StackTrace);
BuildErrorEventArgs beea = new BuildErrorEventArgs (
null, null, buildEngine.ProjectFileOfTaskNode, 0, 0, 0, 0, sb.ToString (),
- e.HelpLink, e.Source);
+ exception.HelpLink, exception.Source);
buildEngine.LogErrorEvent (beea);
hasLoggedErrors = true;
}
messageResourceName), messageArgs);
}
- public bool LogMessagesFromFile (string filename)
+ public bool LogMessagesFromFile (string fileName)
{
- return LogMessagesFromFile (filename, MessageImportance.Normal);
+ return LogMessagesFromFile (fileName, MessageImportance.Normal);
}
- public bool LogMessagesFromFile (string filename,
+ public bool LogMessagesFromFile (string fileName,
MessageImportance messageImportance)
{
try {
- StreamReader sr = new StreamReader (filename);
+ StreamReader sr = new StreamReader (fileName);
LogMessage (messageImportance, sr.ReadToEnd (),
null);
sr.Close ();
}
public bool LogMessageFromText (string lineOfText,
- MessageImportance importance)
+ MessageImportance messageImportance)
{
if (lineOfText == null)
throw new ArgumentNullException ("lineOfText");
BuildMessageEventArgs bmea = new BuildMessageEventArgs (
lineOfText, helpKeywordPrefix,
- null, importance);
+ null, messageImportance);
buildEngine.LogMessageEvent (bmea);
return true;
buildEngine.LogWarningEvent (bwea);
}
- public void LogWarningFromException (Exception e)
+ public void LogWarningFromException (Exception exception)
{
- LogWarningFromException (e, false);
+ LogWarningFromException (exception, false);
}
- public void LogWarningFromException (Exception e,
+ public void LogWarningFromException (Exception exception,
bool showStackTrace)
{
StringBuilder sb = new StringBuilder ();
- sb.Append (e.Message);
+ sb.Append (exception.Message);
if (showStackTrace)
- sb.Append (e.StackTrace);
+ sb.Append (exception.StackTrace);
LogWarning (null, null, null, null, 0, 0, 0, 0,
sb.ToString (), null);
}
}
}
- protected virtual void LogEventsFromTextOutput (string singleLine, MessageImportance importance)
+ protected virtual void LogEventsFromTextOutput (string singleLine, MessageImportance messageImportance)
{
if (singleLine.Length == 0) {
- Log.LogMessage (singleLine, importance);
+ Log.LogMessage (singleLine, messageImportance);
return;
}
var result = MSBuildErrorParser.TryParseLine (singleLine);
if (result == null) {
- Log.LogMessage (importance, singleLine);
+ Log.LogMessage (messageImportance, singleLine);
return;
}
return String.Format ("@{0}", responseFilePath);
}
- protected virtual ProcessStartInfo GetProcessStartInfo (string pathToTool, string commandLineCommands, string responseFileSwitch)
+ protected ProcessStartInfo GetProcessStartInfo (string pathToTool, string commandLineCommands, string responseFileSwitch)
{
var pinfo = new ProcessStartInfo (pathToTool, String.Format ("{0} {1}", commandLineCommands, responseFileSwitch));
{
}
- [MonoTODO ("No TimeoutException is thrown")]
public TransactionScope (TransactionScopeOption option,
TimeSpan timeout)
{
completed = false;
isRoot = false;
nested = 0;
+
+ if (timeout < TimeSpan.Zero)
+ throw new ArgumentOutOfRangeException ("timeout");
+
this.timeout = timeout;
oldTransaction = Transaction.CurrentInternal;
public class TransactionScopeTest
{
+ [Test]
+ public void TransactionScopeWithInvalidTimeSpanThrows ()
+ {
+ try {
+ TransactionScope scope = new TransactionScope (TransactionScopeOption.Required, TimeSpan.FromSeconds (-1));
+ Assert.Fail ("Expected exception when passing TransactionScopeOption and an invalid TimeSpan.");
+ } catch (ArgumentOutOfRangeException ex) {
+ Assert.AreEqual (ex.ParamName, "timeout");
+ }
+
+ try {
+ TransactionScope scope = new TransactionScope (null, TimeSpan.FromSeconds (-1));
+ Assert.Fail ("Expected exception when passing TransactionScopeOption and an invalid TimeSpan.");
+ } catch (ArgumentOutOfRangeException ex) {
+ Assert.AreEqual (ex.ParamName, "timeout");
+ }
+ }
+
[Test]
public void TransactionScopeCommit ()
{
WriteLine (string.Empty);
}
- WriteLine ("string " + GetGetEnumValueName (map) + " (" + map.TypeData.CSharpFullName + " val)");
+ WriteLine ("string " + GetGetEnumValueName (map) + " (" + GetTypeFullName (map.TypeData) + " val)");
WriteLineInd ("{");
void GenerateWriteObject (XmlTypeMapping typeMap)
{
- WriteLine ("void " + GetWriteObjectName (typeMap) + " (" + typeMap.TypeData.CSharpFullName + " ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)");
+ WriteLine ("void " + GetWriteObjectName (typeMap) + " (" + GetTypeFullName (typeMap.TypeData) + " ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)");
WriteLineInd ("{");
PushHookContext ();
if (typeMap.TypeData.SchemaType == SchemaTypes.XmlNode)
{
if (_format == SerializationFormat.Literal)
- WriteLine ("WriteElementLiteral (ob, \"\", \"\", true, " + typeMap.IsAny + ");");
+ WriteLine ("WriteElementLiteral (ob, \"\", \"\", true, " + GetLiteral(typeMap.IsAny) + ");");
else
- WriteLine ("WriteElementEncoded (ob, \"\", \"\", true, " + typeMap.IsAny + ");");
+ WriteLine ("WriteElementEncoded (ob, \"\", \"\", true, " + GetLiteral(typeMap.IsAny) + ");");
GenerateEndHook ();
WriteLineUni ("}");
if (typeMap.TypeData.SchemaType == SchemaTypes.XmlSerializable)
{
- WriteLine ("WriteSerializable (ob, element, namesp, isNullable, " + !typeMap.IsAny + ");");
+ WriteLine ("WriteSerializable (ob, element, namesp, isNullable, " + GetLiteral(!typeMap.IsAny) + ");");
GenerateEndHook ();
WriteLineUni ("}");
void GenerateWriteAnyElementContent (XmlTypeMapMemberAnyElement member, string memberValue)
{
- bool singleElement = (member.TypeData.Type == typeof (XmlElement));
+ bool singleElement = (member.TypeData.Type == typeof (XmlElement) || member.TypeData.Type == typeof (XmlNode));
string var, var2;
var = GetObTempVar ();
else
WriteLine ("return ReadXmlNode (false);");
} else {
- WriteLineInd ("if (Reader.LocalName != " + GetLiteral (typeMap.ElementName) + " || Reader.NamespaceURI != " + GetLiteral (typeMap.Namespace) + ")");
- WriteLine ("throw CreateUnknownNodeException();");
- Unindent ();
+ if (!typeMap.IsAny) {
+ WriteLineInd ("if (Reader.LocalName != " + GetLiteral (typeMap.ElementName) + " || Reader.NamespaceURI != " + GetLiteral (typeMap.Namespace) + ")");
+ WriteLine ("throw CreateUnknownNodeException();");
+ Unindent ();
+ }
WriteLine ("return " + GetReadObjectCall (typeMap, GetLiteral(typeMap.IsNullable), "true") + ";");
}
WriteLine ("Reader.MoveToContent();");
WriteLine ("if (Reader.NodeType == System.Xml.XmlNodeType.Element) ");
WriteLineInd ("{");
- WriteLineInd ("if (Reader.LocalName == " + GetLiteral(typeMap.ElementName) + " && Reader.NamespaceURI == " + GetLiteral (typeMap.Namespace) + ")");
+ if (!typeMap.IsAny)
+ WriteLineInd ("if (Reader.LocalName == " + GetLiteral(typeMap.ElementName) + " && Reader.NamespaceURI == " + GetLiteral (typeMap.Namespace) + ")");
WriteLine ("ob = ReadReferencedElement();");
Unindent ();
- WriteLineInd ("else ");
- WriteLine ("throw CreateUnknownNodeException();");
- Unindent ();
+ if (!typeMap.IsAny) {
+ WriteLineInd ("else ");
+ WriteLine ("throw CreateUnknownNodeException();");
+ Unindent ();
+ }
WriteLineUni ("}");
WriteLineInd ("else ");
WriteLine ("UnknownNode(null);");
{
string isNullable;
if (_format == SerializationFormat.Literal) {
- WriteLine ("public " + typeMap.TypeData.CSharpFullName + " " + GetReadObjectName (typeMap) + " (bool isNullable, bool checkType)");
+ WriteLine ("public " + GetTypeFullName(typeMap.TypeData) + " " + GetReadObjectName (typeMap) + " (bool isNullable, bool checkType)");
isNullable = "isNullable";
}
else {
WriteLine ("Reader.MoveToContent ();");
WriteLine ("if (Reader.NodeType == XmlNodeType.Element)");
WriteLineInd ("{");
- WriteLine ("if (Reader.LocalName == " + GetLiteral (typeMap.ElementName) + " && Reader.NamespaceURI == " + GetLiteral (typeMap.Namespace) + ")");
+ if (!typeMap.IsAny)
+ WriteLineInd ("if (Reader.LocalName == " + GetLiteral (typeMap.ElementName) + " && Reader.NamespaceURI == " + GetLiteral (typeMap.Namespace) + ")");
WriteLine (String.Format ("\treturn ({0}) ReadSerializable (({0}) Activator.CreateInstance(typeof({0}), true));", typeMap.TypeData.CSharpFullName));
- WriteLine ("else");
- WriteLine ("\tthrow CreateUnknownNodeException ();");
+ Unindent ();
+ if (!typeMap.IsAny) {
+ WriteLine ("else");
+ WriteLine ("\tthrow CreateUnknownNodeException ();");
+ }
WriteLineUni ("}");
WriteLine ("else UnknownNode (null);");
WriteLine ("");
string GetRootTypeName ()
{
- if (_typeMap is XmlTypeMapping) return ((XmlTypeMapping)_typeMap).TypeData.CSharpFullName;
+ if (_typeMap is XmlTypeMapping) return GetTypeFullName (((XmlTypeMapping)_typeMap).TypeData);
else return "object[]";
}
string GetCast (TypeData td, string val)
{
- if (td.IsNullable && td.IsValueType)
- return "((" + td.CSharpFullName + "?) " + val + ")";
- else
- return "((" + td.CSharpFullName + ") " + val + ")";
+ return "((" + GetTypeFullName (td) + ") " + val + ")";
}
string GetCast (Type td, string val)
string GetTypeOf (TypeData td)
{
- return "typeof(" + td.CSharpFullName + ")";
+ return "typeof(" + GetTypeFullName (td) + ")";
}
string GetTypeOf (Type td)
{
return "typeof(" + ToCSharpFullName (td) + ")";
}
+
+ string GetTypeFullName (TypeData td) {
+ if (td.IsNullable && td.IsValueType)
+ return td.CSharpFullName + "?";
+
+ return td.CSharpFullName;
+ }
string GetLiteral (object ob)
{
else {
generationThreshold = int.Parse (th, CultureInfo.InvariantCulture);
backgroundGeneration = (generationThreshold != 0);
- if (generationThreshold < 1) generationThreshold = 1;
}
}
#endif
bool generate = false;
lock (serializerData)
{
- generate = (++serializerData.UsageCount == generationThreshold);
+ generate = (serializerData.UsageCount++ == generationThreshold);
}
if (generate)
using System.Data;
using System.Xml.Schema;
using System.Xml.Serialization;
+using System.Reflection;
#if NET_2_0
using System.Collections.Generic;
#endif
}
}
}
+
+ public class ClassWithXmlAnyElement
+ {
+ [XmlAnyElement ("Contents")]
+ public XmlNode Contents;
+ }
+
+ [Test] // bug #3211
+ public void TestClassWithXmlAnyElement ()
+ {
+ var d = new XmlDocument ();
+ var e = d.CreateElement ("Contents");
+ e.AppendChild (d.CreateElement ("SomeElement"));
+
+ var c = new ClassWithXmlAnyElement {
+ Contents = e,
+ };
+
+ var ser = new XmlSerializer (typeof (ClassWithXmlAnyElement));
+ using (var sw = new StringWriter ())
+ ser.Serialize (sw, c);
+ }
+ }
+
+ // Test generated serialization code.
+ public class XmlSerializerGeneratorTests : XmlSerializerTests {
+
+ private FieldInfo backgroundGeneration;
+ private FieldInfo generationThreshold;
+ private FieldInfo generatorFallback;
+
+ private bool backgroundGenerationOld;
+ private int generationThresholdOld;
+ private bool generatorFallbackOld;
+
+ [SetUp]
+ public void SetUp ()
+ {
+ // Make sure XmlSerializer static constructor is called
+ XmlSerializer.FromTypes (new Type [] {});
+
+ const BindingFlags binding = BindingFlags.Static | BindingFlags.NonPublic;
+ backgroundGeneration = typeof (XmlSerializer).GetField ("backgroundGeneration", binding);
+ generationThreshold = typeof (XmlSerializer).GetField ("generationThreshold", binding);
+ generatorFallback = typeof (XmlSerializer).GetField ("generatorFallback", binding);
+
+ if (backgroundGeneration == null)
+ Assert.Ignore ("Unable to access field backgroundGeneration");
+ if (generationThreshold == null)
+ Assert.Ignore ("Unable to access field generationThreshold");
+ if (generatorFallback == null)
+ Assert.Ignore ("Unable to access field generatorFallback");
+
+ backgroundGenerationOld = (bool) backgroundGeneration.GetValue (null);
+ generationThresholdOld = (int) generationThreshold.GetValue (null);
+ generatorFallbackOld = (bool) generatorFallback.GetValue (null);
+
+ backgroundGeneration.SetValue (null, false);
+ generationThreshold.SetValue (null, 0);
+ generatorFallback.SetValue (null, false);
+ }
+
+ [TearDown]
+ public void TearDown ()
+ {
+ if (backgroundGeneration == null || generationThreshold == null || generatorFallback == null)
+ return;
+
+ backgroundGeneration.SetValue (null, backgroundGenerationOld);
+ generationThreshold.SetValue (null, generationThresholdOld);
+ generatorFallback.SetValue (null, generatorFallbackOld);
+ }
}
}
using System.Text.RegularExpressions;
using System.Threading;
using System.Collections.Generic;
+ using System.Globalization;
internal class CSharpCodeCompiler : CSharpCodeGenerator, ICodeCompiler
{
if (Environment.GetEnvironmentVariable ("MONO_TESTS_IN_PROGRESS") != null) {
string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH");
if (!String.IsNullOrEmpty (monoPath)) {
- monoPath = monoPath.Replace ("/class/lib/net_2_0", "/class/lib/net_4_0");
+ const string basePath = "/class/lib/";
+ const string profile = "net_2_0";
+ var basePathIndex = monoPath.IndexOf (basePath, StringComparison.Ordinal);
+ if (basePathIndex > 0 && basePathIndex + basePath.Length + profile.Length <= monoPath.Length) {
+ var currentProfile = monoPath.Substring (basePathIndex + basePath.Length, profile.Length);
+ if (currentProfile.Equals (profile, StringComparison.OrdinalIgnoreCase))
+ monoPath = monoPath.Replace (basePath + currentProfile, basePath + "net_4_0");
+ }
mcs.StartInfo.EnvironmentVariables ["MONO_PATH"] = monoPath;
}
}
using System.IO;
using System.Security.Principal;
using System.Text;
+#if NET_4_5
+using System.Threading.Tasks;
+using System.Net.WebSockets;
+#endif
+
namespace System.Net {
public sealed class HttpListenerContext {
HttpListenerRequest request;
return null;
}
}
+
+#if NET_4_5
+ public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync (string subProtocol)
+ {
+ throw new NotImplementedException ();
+ }
+
+ public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync (string subProtocol, int receiveBufferSize, TimeSpan keepAliveInterval)
+ {
+ throw new NotImplementedException ();
+ }
+
+ public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync (string subProtocol, int receiveBufferSize, TimeSpan keepAliveInterval, ArraySegment<byte> internalBuffer)
+ {
+ throw new NotImplementedException ();
+ }
+#endif
}
}
#endif
SetBusy ();
async = false;
WebRequest request = SetupRequest (address, method, true);
- return request.GetRequestStream ();
+ return OpenWriteStream (request);
} catch (WebException) {
throw;
} catch (Exception ex) {
}
}
+ Stream OpenWriteStream (WebRequest request)
+ {
+ var stream = request.GetRequestStream ();
+ var wcs = stream as WebConnectionStream;
+ if (wcs != null)
+ wcs.GetResponseOnClose = true;
+ return stream;
+ }
+
private string DetermineMethod (Uri address, string method, bool is_upload)
{
if (method != null)
WebRequest request = null;
try {
request = SetupRequest ((Uri) args [0], (string) args [1], true);
- Stream stream = request.GetRequestStream ();
+ var stream = OpenWriteStream (request);
OnOpenWriteCompleted (
new OpenWriteCompletedEventArgs (stream, null, false, args [2]));
} catch (ThreadInterruptedException){
try {
SetBusy ();
cts = new CancellationTokenSource ();
- request = SetupRequest (address);
- return await request.GetRequestStreamAsync ().ConfigureAwait (false);
+ request = await SetupRequestAsync (address, method, true).ConfigureAwait (false);
+ var stream = await request.GetRequestStreamAsync ();
+ var wcs = stream as WebConnectionStream;
+ if (wcs != null)
+ wcs.GetResponseOnClose = true;
+ return stream;
} catch (WebException) {
throw;
} catch (OperationCanceledException) {
if (data == null)
throw new ArgumentNullException ("data");
+ string cType = Headers ["Content-Type"];
+ if (cType != null && String.Compare (cType, urlEncodedCType, true) != 0)
+ throw new WebException ("Content-Type header cannot be changed from its default " +
+ "value for this request.");
+ Headers ["Content-Type"] = urlEncodedCType;
+
WebRequest request = null;
try {
SetBusy ();
CancellationToken token)
{
token.ThrowIfCancellationRequested ();
- string cType = Headers ["Content-Type"];
- if (cType != null && String.Compare (cType, urlEncodedCType, true) != 0)
- throw new WebException ("Content-Type header cannot be changed from its default " +
- "value for this request.");
WebResponse response = null;
-
- Headers ["Content-Type"] = urlEncodedCType;
try {
MemoryStream tmpStream = new MemoryStream ();
foreach (string key in data) {
disposed = true;
}
+ internal bool GetResponseOnClose {
+ get; set;
+ }
+
public override void Close ()
{
+ if (GetResponseOnClose) {
+ if (disposed)
+ return;
+ disposed = true;
+ var response = (HttpWebResponse)request.GetResponse ();
+ response.ReadAll ();
+ response.Close ();
+ return;
+ }
+
if (sendChunked) {
if (disposed)
return;
using System;
using System.IO;
using System.Runtime.InteropServices;
+#if NET_4_5
+using System.Threading;
+using System.Threading.Tasks;
+#endif
namespace System.IO
{
#if NET_4_0
SafeBuffer safebuffer;
#endif
+#if NET_4_5
+ Task<int> read_task;
+#endif
internal event EventHandler Closed;
return progress;
}
+#if NET_4_5
+ public override Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException("buffer");
+ if (offset < 0)
+ throw new ArgumentOutOfRangeException("offset", "Non-negative number required.");
+ if (count < 0)
+ throw new ArgumentOutOfRangeException("count", "Non-negative number required.");
+ if ((buffer.Length - offset) < count)
+ throw new ArgumentException("The length of the buffer array minus the offset parameter is less than the count parameter");
+
+ if (cancellationToken.IsCancellationRequested)
+ return TaskConstants<int>.Canceled;
+
+ try {
+ count = Read (buffer, offset, count);
+
+ // Try not to allocate a new task for every buffer read
+ if (read_task == null || read_task.Result != count)
+ read_task = Task<int>.FromResult (count);
+
+ return read_task;
+ } catch (Exception ex) {
+ return Task<int>.FromException (ex);
+ }
+ }
+
+#endif
+
public override int ReadByte ()
{
if (closed)
//This method performs no action for this class
//but is included as part of the Stream base class
}
+
+#if NET_4_5
+ public override Task FlushAsync (CancellationToken cancellationToken)
+ {
+ if (cancellationToken.IsCancellationRequested)
+ return TaskConstants.Canceled;
+
+ try {
+ Flush ();
+ return TaskConstants.Finished;
+ } catch (Exception ex) {
+ return Task<object>.FromException (ex);
+ }
+ }
+#endif
protected override void Dispose (bool disposing)
{
if (current_position > length)
length = current_position;
}
+
+#if NET_4_5
+ public override Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException("The buffer parameter is a null reference");
+ if (offset < 0)
+ throw new ArgumentOutOfRangeException("offset", "Non-negative number required.");
+ if (count < 0)
+ throw new ArgumentOutOfRangeException("count", "Non-negative number required.");
+ if ((buffer.Length - offset) < count)
+ throw new ArgumentException("The length of the buffer array minus the offset parameter is less than the count parameter");
+ if (current_position > capacity - count)
+ throw new NotSupportedException ("Unable to expand length of this stream beyond its capacity.");
+
+ if (cancellationToken.IsCancellationRequested)
+ return TaskConstants.Canceled;
+
+ try {
+ Write (buffer, offset, count);
+ return TaskConstants.Finished;
+ } catch (Exception ex) {
+ return Task<object>.FromException (ex);
+ }
+ }
+#endif
public override void WriteByte (byte value)
{
}
}
- //
- // The following functions are only for the Mono Debugger.
- //
-
- [MethodImplAttribute (MethodImplOptions.InternalCall)]
- internal static extern int MonoDebugger_GetMethodToken (MethodBase method);
-
[MonoTODO ("Currently it always returns zero")]
[ComVisible (false)]
public
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Text;
+using System.Runtime.Serialization;
namespace System.Reflection
{
[Serializable]
[ClassInterfaceAttribute (ClassInterfaceType.None)]
[StructLayout (LayoutKind.Sequential)]
-#if MOBILE
- public partial class ParameterInfo : ICustomAttributeProvider {
-#else
- public partial class ParameterInfo : ICustomAttributeProvider, _ParameterInfo {
+ public partial class ParameterInfo : ICustomAttributeProvider
+
+#if !MOBILE
+ , _ParameterInfo
#endif
+#if NET_4_0
+ , IObjectReference
+#endif
+ {
protected Type ClassImpl;
protected object DefaultValueImpl;
protected MemberInfo MemberImpl;
return new object [0];
}
+ public object GetRealObject (StreamingContext context)
+ {
+ throw new NotImplementedException ();
+ }
+
public virtual bool IsDefined( Type attributeType, bool inherit) {
return false;
}
-#if NET_4_5
//
// InterfaceImplementedInVersionAttribute.cs
//
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-using System;
+
+#if NET_4_5
using System.Runtime.CompilerServices;
namespace System.Runtime.InteropServices.WindowsRuntime
{
- [AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Interface, AllowMultiple = false, Inherited = false)]
+ [AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
public sealed class InterfaceImplementedInVersionAttribute : Attribute
{
public InterfaceImplementedInVersionAttribute (Type interfaceType, byte majorVersion, byte minorVersion,
namespace System.Runtime.Serialization
{
[System.Runtime.InteropServices.ComVisibleAttribute (true)]
- public sealed class FormatterServices
+#if NET_4_5
+ static
+#else
+ sealed
+#endif
+ public class FormatterServices
{
private const BindingFlags fieldFlags = BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.DeclaredOnly;
+#if !NET_4_5
private FormatterServices ()
{
}
+#endif
public static object [] GetObjectData (object obj, MemberInfo [] members)
{
--- /dev/null
+//
+// CompatibilitySwitch.cs
+//
+// Authors:
+// Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2014 Xamarin Inc
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+#if NET_4_5
+
+namespace System.Runtime.Versioning {
+ public static class CompatibilitySwitch
+ {
+ public static bool IsEnabled (string compatibilitySwitchName)
+ {
+ return false;
+ }
+
+ public static string GetValue (string compatibilitySwitchName)
+ {
+ return null;
+ }
+ }
+}
+
+#endif
\ No newline at end of file
get { return false; }
}
- [MonoTODO ("Always returns GCLatencyMode.Interactive and ignores set (.NET 2.0 SP1 member)")]
+ [MonoTODO ("Always returns GCLatencyMode.Interactive and ignores set")]
public static GCLatencyMode LatencyMode {
[ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
get { return GCLatencyMode.Interactive; }
[ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
set { ; }
}
+
+#if NET_4_5
+ public static GCLargeObjectHeapCompactionMode LargeObjectHeapCompactionMode {
+ [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
+ get;
+ [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
+ set;
+ }
+#endif
}
}
+++ /dev/null
-//
-// Claim.cs
-//
-// Authors:
-// Miguel de Icaza (miguel@xamarin.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-using System;
-
-namespace System.Security.Claims {
-
- public static class AuthenticationTypes {
- public const string Basic = "Basic";
- public const string Federation = "Federation";
- public const string Kerberos = "Kerberos";
- public const string Negotiate = "Negotiate";
- public const string Password = "Password";
- public const string Signature = "Signature";
- public const string Windows = "Windows";
- public const string X509 = "X509";
- }
-}
public const string AuthorizationDecision = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authorizationdecision";
- public const string ClaimsType2005Namespace = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims";
-
- public const string ClaimsType2009Namespace = "http://schemas.xmlsoap.org/ws/2009/09/identity/claims";
-
- public const string ClaimsTypeNamespace = "http://schemas.microsoft.com/ws/2008/06/identity/claims";
-
public const string CookiePath = "http://schemas.microsoft.com/ws/2008/06/identity/claims/cookiepath";
public const string Country = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country";
public const string DateOfBirth = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth";
- public const string DenyOnlyPrimaryGroup = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarygroup";
+ public const string DenyOnlyPrimaryGroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarygroupsid";
public const string DenyOnlyPrimarySid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarysid";
public const string DenyOnlySid = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/denyonlysid";
+ public const string DenyOnlyWindowsDeviceGroup = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlywindowsdevicegroup";
+
public const string Dns = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dns";
public const string Dsa = "http://schemas.microsoft.com/ws/2008/06/identity/claims/dsa";
- public const string Email = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/email";
+ public const string Email = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress";
public const string Expiration = "http://schemas.microsoft.com/ws/2008/06/identity/claims/expiration";
public const string PostalCode = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode";
- public const string PPID = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier";
-
public const string PrimaryGroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarygroupsid";
public const string PrimarySid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid";
public const string WindowsAccountName = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname";
+ public const string WindowsDeviceClaim = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdeviceclaim";
+
+ public const string WindowsDeviceGroup = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdevicegroup";
+
+ public const string WindowsFqbnVersion = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsfqbnversion";
+
+ public const string WindowsSubAuthority = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowssubauthority";
+
+ public const string WindowsUserClaim = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsuserclaim";
+
public const string X500DistinguishedName = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/x500distinguishedname";
}
}
//
// Authors:
// Miguel de Icaza (miguel@xamarin.com)
+// Marek Safar (marek.safar@gmail.com)
//
// Copyright 2014 Xamarin Inc
//
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_4_5
-using System;
+
using System.Collections.Generic;
using System.Security.Principal;
using System.Runtime.Serialization;
+
namespace System.Security.Claims {
[Serializable]
[NonSerializedAttribute]
public const string DefaultIssuer = "LOCAL AUTHORITY";
- List<Claim> claims;
+ readonly List<Claim> claims;
ClaimsIdentity actor;
- string auth_type;
+ readonly string auth_type;
public ClaimsIdentity ()
: this (claims: null, authenticationType: null, nameType: null, roleType: null)
public ClaimsIdentity(IEnumerable<Claim> claims, string authenticationType, string nameType, string roleType)
: this (identity: null, claims: claims, authenticationType: authenticationType, nameType: nameType, roleType: roleType)
{
- claims = claims == null ? new List<Claim> (): new List<Claim> (claims);
-
- // Special case: if empty, set to null.
- if (authenticationType == "")
- auth_type = null;
- else
- auth_type = authenticationType;
-
- NameClaimType = nameType == null ? DefaultNameClaimType : nameType;
- RoleClaimType = roleType == null ? DefaultRoleClaimType : roleType;
}
public ClaimsIdentity (IIdentity identity, IEnumerable<Claim> claims)
: this (identity, claims, authenticationType: null, nameType: null, roleType: null)
- { }
+ {
+ }
public ClaimsIdentity (IIdentity identity, IEnumerable<Claim> claims, string authenticationType, string nameType, string roleType)
{
- var ci = identity as ClaimsIdentity;
- NameClaimType = nameType == null ? DefaultNameClaimType : nameType;
- RoleClaimType = roleType == null ? DefaultRoleClaimType : roleType;
-
+ NameClaimType = string.IsNullOrEmpty (nameType) ? DefaultNameClaimType : nameType;
+ RoleClaimType = string.IsNullOrEmpty (roleType) ? DefaultRoleClaimType : roleType;
+ auth_type = authenticationType;
+
this.claims = new List<Claim> ();
- if (ci != null){
- actor = ci.Actor;
- BootstrapContext = ci.BootstrapContext;
- foreach (var c in ci.Claims)
- this.claims.Add (c);
+
+ if (identity != null) {
+ if (string.IsNullOrEmpty (authenticationType))
+ auth_type = identity.AuthenticationType;
+
+ var ci = identity as ClaimsIdentity;
+ if (ci != null) {
+ actor = ci.Actor;
+ BootstrapContext = ci.BootstrapContext;
+ foreach (var c in ci.Claims)
+ this.claims.Add (c);
- Label = ci.Label;
- NameClaimType = ci.NameClaimType;
- RoleClaimType = ci.RoleClaimType;
- auth_type = ci.AuthenticationType;
+ Label = ci.Label;
+ NameClaimType = string.IsNullOrEmpty (nameType) ? ci.NameClaimType : nameType;
+ RoleClaimType = string.IsNullOrEmpty (roleType) ? ci.RoleClaimType : roleType;
+ } else if (!string.IsNullOrEmpty (identity.Name)) {
+ AddDefaultClaim (identity.Name);
+ }
}
if (claims != null) {
- foreach (var c in claims)
- this.claims.Add (c);
+ AddClaims (claims);
}
}
return actor;
}
set {
- if (actor == this)
+ if (value == this)
throw new InvalidOperationException ("can not set the Actor property to this instance");
+
actor = value;
}
}
{
if (claim == null)
throw new ArgumentNullException ("claim");
+
+ if (claim.Subject != this)
+ claim = claim.Clone (this);
+
claims.Add (claim);
}
{
if (claims == null)
throw new ArgumentNullException ("claims");
+
foreach (var c in claims)
- this.claims.Add (c);
+ AddClaim (c);
+ }
+
+ internal void AddDefaultClaim (string identityName)
+ {
+ this.claims.Add (new Claim (NameClaimType, identityName, "http://www.w3.org/2001/XMLSchema#string", DefaultIssuer, DefaultIssuer, this));
}
public virtual ClaimsIdentity Clone ()
yield return c;
}
- public virtual IEnumerable<Claim> FindAll(string type)
+ public virtual IEnumerable<Claim> FindAll (string type)
{
if (type == null)
throw new ArgumentNullException ("type");
foreach (var c in claims)
- if (c.Type == type)
+ if (string.Equals (c.Type, type, StringComparison.OrdinalIgnoreCase))
yield return c;
}
if (type == null)
throw new ArgumentNullException ("type");
foreach (var c in claims)
- if (c.Type == type)
+ if (string.Equals (c.Type, type, StringComparison.OrdinalIgnoreCase))
return c;
return null;
}
if (value == null)
throw new ArgumentNullException ("value");
foreach (var c in claims){
- if (c.Type == type && c.Value == value)
+ if (string.Equals (c.Type, type, StringComparison.OrdinalIgnoreCase) && c.Value == value)
return true;
}
return false;
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_4_5
-using System;
+
using System.Collections.Generic;
using System.Security.Principal;
using System.Runtime.Serialization;
throw new ArgumentNullException ("identity");
identities = new List<ClaimsIdentity> ();
- identities.Add (new ClaimsIdentity (identity));
+ identities.Add (identity as ClaimsIdentity ?? new ClaimsIdentity (identity));
}
public ClaimsPrincipal (IPrincipal principal)
//
// System.Security.Principal.GenericIdentity.cs
//
-// Author:
+// Authors:
// Miguel de Icaza (miguel@ximian.com)
+// Marek Safar (marek.safar@gmail.com)
//
// (C) Ximian, Inc. http://www.ximian.com
// Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
//
using System.Runtime.InteropServices;
+using System.Collections.Generic;
+#if NET_4_5
+using System.Security.Claims;
+#endif
namespace System.Security.Principal {
[Serializable]
[ComVisible (true)]
- public class GenericIdentity : IIdentity {
+ public class GenericIdentity :
+#if NET_4_5
+ ClaimsIdentity
+#else
+ IIdentity
+#endif
+ {
// field names are serialization compatible with .net
private string m_name;
m_name = name;
m_type = type;
+
+#if NET_4_5
+ AddDefaultClaim (name);
+#endif
}
public GenericIdentity (string name)
{
}
- public virtual string AuthenticationType {
+#if NET_4_5
+ protected GenericIdentity (GenericIdentity identity)
+ : base (identity)
+ {
+ }
+#endif
+
+#if NET_4_5
+ override
+#else
+ virtual
+#endif
+ public string AuthenticationType {
get {
return m_type;
}
}
- public virtual string Name {
+#if NET_4_5
+ override
+#else
+ virtual
+#endif
+ public string Name {
get {
return m_name;
}
}
- public virtual bool IsAuthenticated {
+#if NET_4_5
+ override
+#else
+ virtual
+#endif
+ public bool IsAuthenticated {
get {
return (m_name.Length > 0);
}
}
+
+#if NET_4_5
+ public override IEnumerable<Claim> Claims {
+ get {
+ return base.Claims;
+ }
+ }
+#endif
}
}
//
using System.Runtime.InteropServices;
+#if NET_4_5
+using System.Security.Claims;
+#endif
namespace System.Security.Principal {
[Serializable]
[ComVisible (true)]
- public class GenericPrincipal : IPrincipal {
+ public class GenericPrincipal :
+#if NET_4_5
+ ClaimsPrincipal
+#else
+ IPrincipal
+#endif
+ {
// field names are serialization compatible with .net
private IIdentity m_identity;
get { return m_roles; }
}
- public virtual IIdentity Identity {
+#if NET_4_5
+ override
+#else
+ virtual
+#endif
+ public IIdentity Identity {
get { return m_identity; }
}
- public virtual bool IsInRole (string role)
+#if NET_4_5
+ override
+#else
+ virtual
+#endif
+ public bool IsInRole (string role)
{
if (m_roles == null)
return false;
static private IntPtr invalidWindows = IntPtr.Zero;
+#if NET_4_5
+ [NonSerialized]
+ public new const string DefaultIssuer = "AD AUTHORITY";
+#endif
+
[SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
public WindowsIdentity (IntPtr userToken)
: this (userToken, null, WindowsAccountType.Normal, false)
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
+#if NET_4_5
+using System.Security.Claims;
+#endif
namespace System.Security.Principal {
[Serializable]
[ComVisible (true)]
- public class WindowsPrincipal : IPrincipal {
-
+ public class WindowsPrincipal :
+#if NET_4_5
+ ClaimsPrincipal
+#else
+ IPrincipal
+#endif
+ {
private WindowsIdentity _identity;
// http://groups.google.ca/groups?q=WindowsPrincipal+m_roles&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=OghXf4OgCHA.4228%40tkmsftngp08&rnum=4
private string [] m_roles;
}
// properties
-
- public virtual IIdentity Identity {
+#if NET_4_5
+ override
+#else
+ virtual
+#endif
+ public IIdentity Identity {
get { return _identity; }
}
}
}
- public virtual bool IsInRole (string role)
+#if NET_4_5
+ override
+#else
+ virtual
+#endif
+ public bool IsInRole (string role)
{
if (role == null)
return false; // ArgumentNullException
public extern static float Read (ref float location);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
+ [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
public extern static T Read<T> (ref T location) where T : class;
[MethodImplAttribute (MethodImplOptions.InternalCall)]
public extern static void Write (ref float location, float value);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
+ [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
public extern static void Write<T>(ref T location, T value) where T : class;
}
}
//
-// WindowsIdentityTest.cs - NUnit Test Cases for WindowsIdentity
-//
-// Author:
-// Sebastien Pouliot (sebastien@ximian.com)
-//
-// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
-// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
+// ClaimsIdentityTest.cs - NUnit Test Cases for System.Security.Claims.ClaimsIdentity
//
+
#if NET_4_5
+
using NUnit.Framework;
using System;
+using System.Collections.Generic;
+using System.Linq;
using System.Security.Claims;
+using System.Security.Principal;
-namespace MonoTests.System.Security.Claims {
-
+namespace MonoTests.System.Security.Claims
+{
[TestFixture]
- public class ClaimsIdentityTest {
+ public class ClaimsIdentityTest
+ {
+ #region Ctor Empty
[Test]
- public void EmptyCtorWorks () {
+ public void EmptyCtorWorks ()
+ {
var id = new ClaimsIdentity ();
Assert.IsNull (id.AuthenticationType, "#1");
-
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (0, id.Claims.Count (), "#5");
+ Assert.IsFalse (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.IsNull (id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ #endregion
+
+ #region Ctor AuthTypeOnly
+
+ [Test]
+ public void AuthTypeOnlyCtorEmptyWorks ()
+ {
+ var id = new ClaimsIdentity ("");
+ //NOTE: According to MSDN the id.AuthenticationType should be null, but it isn't on .Net 4.5
+ //Assert.IsNull (id.AuthenticationType, "#1");
+ Assert.AreEqual ("", id.AuthenticationType, "#1");
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (0, id.Claims.Count (), "#5");
+ Assert.IsFalse (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.IsNull (id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ [Test]
+ public void AuthTypeOnlyCtorNullWorks ()
+ {
+ var id = new ClaimsIdentity ((string)null);
+ Assert.IsNull (id.AuthenticationType, "#1");
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (0, id.Claims.Count (), "#5");
+ Assert.IsFalse (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.IsNull (id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ [Test]
+ public void AuthTypeOnlyCtorNotEmptyWorks ()
+ {
+ var id = new ClaimsIdentity ("auth_type");
+ Assert.AreEqual ("auth_type", id.AuthenticationType, "#1");
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (0, id.Claims.Count (), "#5");
+ Assert.IsTrue (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.IsNull (id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ #endregion
+
+ #region Ctor IEnumerable<Claim>
+
+ [Test]
+ public void EnumClaimsCtorNullWorks ()
+ {
+ var id = new ClaimsIdentity ((IEnumerable<Claim>)null);
+ Assert.IsNull (id.AuthenticationType, "#1");
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (0, id.Claims.Count (), "#5");
+ Assert.IsFalse (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.IsNull (id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ [Test]
+ public void EnumClaimsCtorEmptyWorks ()
+ {
+ var id = new ClaimsIdentity ((IEnumerable<Claim>)null);
+ Assert.IsNull (id.AuthenticationType, "#1");
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (0, id.Claims.Count (), "#5");
+ Assert.IsFalse (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.IsNull (id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ [Test]
+ public void EnumClaimsCtorWithClaimsWithNameWorks ()
+ {
+ var id = new ClaimsIdentity (
+ new [] {
+ new Claim ("claim_type", "claim_value"),
+ new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"),
+ });
+ Assert.IsNull (id.AuthenticationType, "#1");
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (2, id.Claims.Count (), "#5");
+ Assert.IsFalse (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.AreEqual ("claim_name_value", id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ [Test]
+ public void EnumClaimsCtorWithClaimsWithoutNameWorks ()
+ {
+ var id = new ClaimsIdentity (
+ new [] {
+ new Claim ("claim_type", "claim_value"),
+ new Claim (ClaimsIdentity.DefaultNameClaimType + "_x", "claim_name_value"),
+ });
+ Assert.IsNull (id.AuthenticationType, "#1");
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (2, id.Claims.Count (), "#5");
+ Assert.IsFalse (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.IsNull (id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ #endregion
+
+ #region Ctor IEnumerable<Claim>, authType, nameType, roleType
+
+ [Test]
+ public void EnumClaimsAuthNameRoleTypeCtorWorks ()
+ {
+ var id = new ClaimsIdentity (new [] {
+ new Claim ("claim_type", "claim_value"),
+ new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"),
+ new Claim ("claim_role_type", "claim_role_value"),
+ },
+ "test_auth_type", "test_name_type", "claim_role_type");
+ Assert.AreEqual ("test_auth_type", id.AuthenticationType, "#1");
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (3, id.Claims.Count (), "#5");
+ Assert.IsTrue (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.IsNull (id.Name, "#8");
+ Assert.AreEqual ("test_name_type", id.NameClaimType, "#9");
+ Assert.AreEqual ("claim_role_type", id.RoleClaimType, "#10");
+ }
+
+ [Test]
+ public void EnumClaimsAuthNameRoleTypeCtorAllArgsNullWorks ()
+ {
+ var id = new ClaimsIdentity ((IEnumerable<Claim>)null, (string)null, (string)null, (string)null);
+ Assert.IsNull (id.AuthenticationType, "#1");
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (0, id.Claims.Count (), "#5");
+ Assert.IsFalse (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.IsNull (id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ [Test]
+ public void EnumClaimsAuthNameRoleTypeCtorAllArgsEmptyWorks ()
+ {
+ var id = new ClaimsIdentity (new Claim [0], "", "", "");
+ //NOTE: According to MSDN the id.AuthenticationType should be null, but it isn't on .Net 4.5
+ //Assert.IsNull (id.AuthenticationType, "#1");
+ Assert.AreEqual ("", id.AuthenticationType, "#1");
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (0, id.Claims.Count (), "#5");
+ Assert.IsFalse (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.IsNull (id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ [Test]
+ public void EnumClaimsAuthNameRoleTypeCtorWithTwoClaimsAndTypesEmptyWorks ()
+ {
+ var id = new ClaimsIdentity (
+ new [] {
+ new Claim ("claim_type", "claim_value"),
+ new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"),
+ },
+ "", "", "");
+ //NOTE: According to MSDN the id.AuthenticationType should be null, but it isn't on .Net 4.5
+ //Assert.IsNull (id.AuthenticationType, "#1");
+ Assert.AreEqual ("", id.AuthenticationType, "#1");
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (2, id.Claims.Count (), "#5");
+ Assert.IsFalse (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.AreEqual ("claim_name_value", id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ [Test]
+ public void EnumClaimsAuthNameRoleTypeCtorWithTwoClaimsAndTypesNullWorks ()
+ {
+ var id = new ClaimsIdentity (
+ new [] {
+ new Claim ("claim_type", "claim_value"),
+ new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"),
+ },
+ (string)null, (string)null, (string)null);
+ Assert.IsNull (id.AuthenticationType, "#1");
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (2, id.Claims.Count (), "#5");
+ Assert.IsFalse (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.AreEqual ("claim_name_value", id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ #endregion
+
+ #region Ctor IIdentity, IEnumerable<Claim>, authType, nameType, roleType
+
+ [Test]
+ public void IdentityEnumClaimsAuthNameRoleTypeCtorNullsWorks ()
+ {
+ var id = new ClaimsIdentity ((IIdentity)null, (IEnumerable<Claim>)null, (string)null, (string)null, (string)null);
+ Assert.IsNull (id.AuthenticationType, "#1");
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (0, id.Claims.Count (), "#5");
+ Assert.IsFalse (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.IsNull (id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ [Test]
+ public void IdentityEnumClaimsAuthNameRoleTypeCtorIdentityNullRestEmptyWorks ()
+ {
+ var id = new ClaimsIdentity (null, new Claim [0], "", "", "");
+ //NOTE: According to MSDN the id.AuthenticationType should be null, but it isn't on .Net 4.5
+ //Assert.IsNull (id.AuthenticationType, "#1");
+ Assert.AreEqual ("", id.AuthenticationType, "#1");
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (0, id.Claims.Count (), "#5");
+ Assert.IsFalse (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.IsNull (id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ [Test]
+ public void IdentityEnumClaimsAuthNameRoleTypeCtorNullClaimsArrayEmptyTypesWorks ()
+ {
+ var id = new ClaimsIdentity (
+ null,
+ new [] {
+ new Claim ("claim_type", "claim_value"),
+ new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"),
+ },
+ "", "", "");
+ //NOTE: According to MSDN the id.AuthenticationType should be null, but it isn't on .Net 4.5
+ //Assert.IsNull (id.AuthenticationType, "#1");
+ Assert.AreEqual ("", id.AuthenticationType, "#1");
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (2, id.Claims.Count (), "#5");
+ Assert.IsFalse (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.AreEqual ("claim_name_value", id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ [Test]
+ public void IdentityEnumClaimsAuthNameRoleTypeCtorNullClaimsArrayNullsWorks ()
+ {
+ var id = new ClaimsIdentity (
+ null,
+ new [] {
+ new Claim ("claim_type", "claim_value"),
+ new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"),
+ },
+ (string)null, (string)null, (string)null);
+ Assert.IsNull (id.AuthenticationType, "#1");
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (2, id.Claims.Count (), "#5");
+ Assert.IsFalse (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.AreEqual ("claim_name_value", id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ [Test]
+ public void IdentityEnumClaimsAuthNameRoleTypeCtorNullIdentityRestFilledWorks ()
+ {
+ var id = new ClaimsIdentity (
+ null,
+ new [] {
+ new Claim ("claim_type", "claim_value"),
+ new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"),
+ new Claim ("claim_role_type", "claim_role_value"),
+ },
+ "test_auth_type", "test_name_type", "claim_role_type");
+ Assert.AreEqual ("test_auth_type", id.AuthenticationType, "#1");
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (3, id.Claims.Count (), "#5");
+ Assert.IsTrue (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.IsNull (id.Name, "#8");
+ Assert.AreEqual ("test_name_type", id.NameClaimType, "#9");
+ Assert.AreEqual ("claim_role_type", id.RoleClaimType, "#10");
+ }
+
+ [Test]
+ public void IdentityEnumClaimsAuthNameRoleTypeCtorClaimsIdentityRestFilledWorks ()
+ {
+ var baseId = new ClaimsIdentity (
+ new[] { new Claim ("base_claim_type", "base_claim_value") },
+ "base_auth_type");
+
+ baseId.Actor = new ClaimsIdentity ("base_actor");
+ baseId.BootstrapContext = "bootstrap_context";
+ baseId.Label = "base_label";
+
+ Assert.IsTrue (baseId.IsAuthenticated, "#0");
+
+ var id = new ClaimsIdentity (
+ baseId,
+ new [] {
+ new Claim ("claim_type", "claim_value"),
+ new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"),
+ new Claim ("claim_role_type", "claim_role_value"),
+ },
+ "test_auth_type", "test_name_type", "claim_role_type");
+
+ Assert.AreEqual ("test_auth_type", id.AuthenticationType, "#1");
+
+ Assert.IsNotNull (id.Actor, "#2");
+ Assert.AreEqual ("base_actor", id.Actor.AuthenticationType, "#2b");
+ Assert.AreEqual ("bootstrap_context", id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (4, id.Claims.Count (), "#5");
+ Assert.AreEqual ("base_claim_type", id.Claims.First ().Type);
+ Assert.IsTrue (id.IsAuthenticated, "#6");
+ Assert.AreEqual ("base_label", id.Label, "#7");
+ Assert.IsNull (id.Name, "#8");
+ Assert.AreEqual ("test_name_type", id.NameClaimType, "#9");
+ Assert.AreEqual ("claim_role_type", id.RoleClaimType, "#10");
+ }
+
+ [Test]
+ public void IdentityEnumClaimsAuthNameRoleTypeCtorNonClaimsIdentityRestEmptyWorks ()
+ {
+ var baseId = new TestIdentity { Name = "base_name", AuthenticationType = "TestId_AuthType" };
+
+ var id = new ClaimsIdentity (
+ baseId,
+ new [] {
+ new Claim ("claim_type", "claim_value"),
+ new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"),
+ new Claim ("claim_role_type", "claim_role_value"),
+ },
+ "", "", "");
+
+ Assert.AreEqual ("TestId_AuthType", id.AuthenticationType, "#1");
+
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (4, id.Claims.Count (), "#5");
+ Assert.AreEqual (2, id.Claims.Count (_ => _.Type == ClaimsIdentity.DefaultNameClaimType), "#5b");
+ Assert.IsTrue (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.AreEqual ("base_name", id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ #endregion
+
+ #region Ctor IIdentity, IEnumerable<Claim>
+
+ [Test]
+ public void IdentityEnumClaimsCtorClaimsIdentityClaimsWorks ()
+ {
+ var baseId = new ClaimsIdentity (
+ new [] { new Claim ("base_claim_type", "base_claim_value") },
+ "base_auth_type", "base_name_claim_type", null);
+
+ baseId.Actor = new ClaimsIdentity ("base_actor");
+ baseId.BootstrapContext = "bootstrap_context";
+ baseId.Label = "base_label";
+
+ Assert.IsTrue (baseId.IsAuthenticated, "#0");
+
+ var id = new ClaimsIdentity (
+ baseId,
+ new [] {
+ new Claim ("claim_type", "claim_value"),
+ new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"),
+ new Claim ("claim_role_type", "claim_role_value"),
+ });
+
+ Assert.AreEqual ("base_auth_type", id.AuthenticationType, "#1");
+
+ Assert.IsNotNull (id.Actor, "#2");
+ Assert.AreEqual ("base_actor", id.Actor.AuthenticationType, "#2b");
+ Assert.AreEqual ("bootstrap_context", id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (4, id.Claims.Count (), "#5");
+ Assert.AreEqual ("base_claim_type", id.Claims.First ().Type, "#5b");
+ Assert.IsTrue (id.IsAuthenticated, "#6");
+ Assert.AreEqual ("base_label", id.Label, "#7");
+ Assert.IsNull (id.Name, "#8");
+ Assert.AreEqual ("base_name_claim_type", id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ [Test]
+ public void IdentityEnumClaimsCtorNonClaimsIdentityClaimsWorks ()
+ {
+ var baseId = new TestIdentity {
+ Name = "base_name", AuthenticationType = "TestId_AuthType"
+ };
+
+ var id = new ClaimsIdentity (
+ baseId,
+ new [] {
+ new Claim ("claim_type", "claim_value"),
+ new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"),
+ new Claim ("claim_role_type", "claim_role_value"),
+ });
+
+ Assert.AreEqual ("TestId_AuthType", id.AuthenticationType, "#1");
+
+ Assert.IsNull (id.Actor, "#2");
+ Assert.IsNull (id.BootstrapContext, "#3");
+ Assert.IsNotNull (id.Claims, "#4");
+ Assert.AreEqual (4, id.Claims.Count (), "#5");
+ Assert.AreEqual (2, id.Claims.Count (_ => _.Type == ClaimsIdentity.DefaultNameClaimType), "#5b");
+ Assert.IsTrue (id.IsAuthenticated, "#6");
+ Assert.IsNull (id.Label, "#7");
+ Assert.AreEqual ("base_name", id.Name, "#8");
+ Assert.AreEqual (ClaimsIdentity.DefaultNameClaimType, id.NameClaimType, "#9");
+ Assert.AreEqual (ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType, "#10");
+ }
+
+ #endregion
+
+ [Test]
+ public void FindCaseInsensivity ()
+ {
+ var claim_type = new Claim("TYpe", "value");
+ var id = new ClaimsIdentity (
+ new[] { claim_type },
+ "base_auth_type", "base_name_claim_type", null);
+
+ var f1 = id.FindFirst ("tyPe");
+ Assert.AreEqual ("value", f1.Value, "#1");
+
+ var f2 = id.FindAll ("tyPE").First ();
+ Assert.AreEqual ("value", f2.Value, "#2");
+ }
+
+ [Test]
+ public void HasClaim_typeValue_Works()
+ {
+ var id = new ClaimsIdentity(
+ new[] {
+ new Claim ("claim_type", "claim_value"),
+ new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"),
+ new Claim ("claim_role_type", "claim_role_value"),
+ }, "test_authority");
+
+ Assert.IsTrue (id.HasClaim("claim_type", "claim_value"), "#1");
+ Assert.IsTrue (id.HasClaim("cLaIm_TyPe", "claim_value"), "#2");
+ Assert.IsFalse (id.HasClaim("claim_type", "cLaIm_VaLuE"), "#3");
+ Assert.IsFalse (id.HasClaim("Xclaim_type", "claim_value"), "#4");
+ Assert.IsFalse (id.HasClaim("claim_type", "Xclaim_value"), "#5");
+ }
+ }
+
+ class TestIdentity : IIdentity
+ {
+ public string Name {
+ get;
+ set;
+ }
+
+ public string AuthenticationType {
+ get;
+ set;
+ }
+
+ public bool IsAuthenticated {
+ get { throw new NotImplementedException (); }
}
}
}
+
#endif
--- /dev/null
+//
+//
+// ClaimsPrincipalTest.cs - NUnit Test Cases for System.Security.Claims.ClaimsPrincipal
+//
+
+#if NET_4_5
+
+using NUnit.Framework;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Security.Claims;
+using System.Security.Principal;
+
+namespace MonoTests.System.Security.Claims
+{
+ [TestFixture]
+ public class ClaimsPrincipalTest
+ {
+ #region Ctor Empty
+
+ [Test]
+ public void EmptyCtorWorks ()
+ {
+ var p = new ClaimsPrincipal ();
+ Assert.IsNotNull (p.Identities, "#1");
+ Assert.AreEqual (p.Identities.ToArray ().Length, 0, "#2");
+
+ Assert.IsNotNull (p.Claims, "#3");
+ Assert.AreEqual (p.Claims.ToArray ().Length, 0, "#4");
+
+ Assert.IsNull (p.Identity, "#5");
+ }
+
+ #endregion
+
+ #region Ctor IIdentity
+
+ [Test]
+ [ExpectedException (typeof (ArgumentNullException))]
+ public void IIdentityCtorNullThrows ()
+ {
+ var p = new ClaimsPrincipal ((IIdentity)null);
+ }
+
+ [Test]
+ public void IIdentityCtorClaimsIdentityWorks ()
+ {
+ var id = new ClaimsIdentity (
+ new List<Claim> { new Claim ("claim_type", "claim_value") },
+ "");
+ var p = new ClaimsPrincipal (id);
+
+ Assert.IsNotNull (p.Identities, "#1");
+ Assert.AreEqual (1, p.Identities.Count (), "#2");
+
+ Assert.AreEqual (id, p.Identities.First (), "#3");
+
+ Assert.AreEqual (id, p.Identity, "#4");
+
+ Assert.IsNotNull (p.Claims, "#5");
+ Assert.AreEqual (1, p.Claims.Count (), "#6");
+ Assert.IsTrue (p.Claims.Any (claim => claim.Type == "claim_type" && claim.Value == "claim_value"), "#7");
+ }
+
+ [Test]
+ public void IIdentityCtorNonClaimsIdentityWorks ()
+ {
+ var id = new TestIdentity {
+ Name = "test_name",
+ AuthenticationType = "test_auth"
+ };
+ var p = new ClaimsPrincipal (id);
+
+ Assert.IsNotNull (p.Identities, "#1");
+ Assert.AreEqual (1, p.Identities.Count (), "#2");
+
+ Assert.AreNotEqual (id, p.Identities.First (), "#3");
+ Assert.AreNotEqual (id, p.Identity, "#4");
+ Assert.AreEqual (id.Name, p.Identity.Name, "#5");
+
+ Assert.IsNotNull (p.Claims, "#6");
+ Assert.AreEqual (1, p.Claims.Count (), "#7");
+ Assert.IsTrue (p.Claims.Any (claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "test_name"), "#8");
+ }
+
+ #endregion
+
+ #region Ctor IPrincipal
+
+ [Test]
+ [ExpectedException (typeof (ArgumentNullException))]
+ public void IPrincipalCtorNullThrows ()
+ {
+ var p = new ClaimsPrincipal ((IPrincipal)null);
+ }
+
+ [Test]
+ public void IPrincipalCtorClaimsPrincipalWorks ()
+ {
+ var baseId = new ClaimsIdentity (
+ new List<Claim> { new Claim ("claim_type", "claim_value") },
+ "");
+ var basePrincipal = new ClaimsPrincipal ();
+ basePrincipal.AddIdentity (baseId);
+
+ var p = new ClaimsPrincipal (basePrincipal);
+
+ Assert.IsNotNull (p.Identities, "#1");
+ Assert.AreEqual (1, p.Identities.Count (), "#2");
+
+ Assert.AreEqual (baseId, p.Identities.First (), "#3");
+
+ Assert.AreEqual (baseId, p.Identity, "#4");
+
+ Assert.IsNotNull (p.Claims, "$5");
+ Assert.AreEqual (1, p.Claims.Count (), "#6");
+ Assert.IsTrue (p.Claims.Any (claim => claim.Type == "claim_type" && claim.Value == "claim_value"), "#7");
+ }
+
+ [Test]
+ public void IPrincipalCtorNonClaimsPrincipalWithNonClaimsIdentityWorks ()
+ {
+ var id = new TestIdentity {
+ Name = "test_name",
+ AuthenticationType = "test_auth"
+ };
+ var basePrincipal = new TestPrincipal { Identity = id };
+ var p = new ClaimsPrincipal (basePrincipal);
+
+ Assert.IsNotNull (p.Identities, "#1");
+ Assert.AreEqual (1, p.Identities.Count (), "#2");
+
+ Assert.AreNotEqual (id, p.Identities.First (), "#3");
+ Assert.AreNotEqual (id, p.Identity, "#4");
+ Assert.AreEqual (id.Name, p.Identity.Name, "#5");
+
+ Assert.IsNotNull (p.Claims, "#6");
+ Assert.AreEqual (1, p.Claims.Count (), "#7");
+ Assert.IsTrue (p.Claims.Any (claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "test_name"), "#8");
+ }
+
+ [Test]
+ public void IPrincipalCtorNonClaimsPrincipalWithoutIdentityWorks ()
+ {
+ var p = new ClaimsPrincipal (new TestPrincipal ());
+ Assert.IsNotNull (p.Identities, "#1");
+ Assert.AreEqual (p.Identities.ToArray ().Length, 1, "#2");
+
+ Assert.IsNotNull (p.Claims, "#3");
+ Assert.AreEqual (p.Claims.ToArray ().Length, 0, "#4");
+
+ Assert.IsNotNull (p.Identity, "#5");
+ Assert.IsFalse (p.Identity.IsAuthenticated, "#6");
+ }
+
+ [Test]
+ [Category ("Ctor_IPrincipal")]
+ public void IPrincipalCtorClaimsPrincipalWithoutIdentityWorks ()
+ {
+ var p = new ClaimsPrincipal (new ClaimsPrincipal ());
+ Assert.IsNotNull (p.Identities, "#1");
+ Assert.AreEqual (p.Identities.ToArray ().Length, 0, "#2");
+
+ Assert.IsNotNull (p.Claims, "#3");
+ Assert.AreEqual (p.Claims.ToArray ().Length, 0, "#4");
+
+ Assert.IsNull (p.Identity, "#5");
+ }
+
+ [Test]
+ public void IPrincipalCtorClaimsPrincipalWithMultipleIdentitiesWorks ()
+ {
+ var baseId1 = new ClaimsIdentity ("baseId1");
+ var baseId2 = new GenericIdentity ("generic_name", "baseId2");
+ var baseId3 = WindowsIdentity.GetAnonymous ();
+
+ var basePrincipal = new ClaimsPrincipal (baseId1);
+ basePrincipal.AddIdentity (baseId2);
+ basePrincipal.AddIdentity (baseId3);
+
+ var p = new ClaimsPrincipal (basePrincipal);
+ Assert.IsNotNull (p.Identities, "#1");
+ Assert.AreEqual (3, p.Identities.Count (), "#2");
+
+ Assert.IsNotNull (p.Claims, "#3");
+ Assert.AreEqual (1, p.Claims.Count (), "#4");
+
+ // The Identity property favours WindowsIdentity
+ Assert.AreEqual (baseId3, p.Identity, "#5");
+
+ Assert.IsTrue (p.Claims.Any (claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "generic_name"), "#6");
+
+ Assert.AreEqual (baseId2.Claims.First (), p.Claims.First (), "#7");
+ }
+
+ #endregion
+
+ #region Ctor IEnumerable<ClaimsIdentity>
+
+ [Test]
+ [ExpectedException (typeof (ArgumentNullException))]
+ public void IEnumClaimsIdCtorNullThrows ()
+ {
+ var p = new ClaimsPrincipal ((IEnumerable<ClaimsIdentity>)null);
+ }
+
+ [Test]
+ public void IEnumClaimsIdCtorEmptyWorks ()
+ {
+ var p = new ClaimsPrincipal (new ClaimsIdentity [0]);
+ Assert.IsNotNull (p.Identities, "#1");
+ Assert.AreEqual (p.Identities.ToArray ().Length, 0, "#2");
+ Assert.IsNotNull (p.Claims, "#3");
+ Assert.AreEqual (p.Claims.ToArray ().Length, 0, "#4");
+ Assert.IsNull (p.Identity, "#5");
+ }
+
+ [Test]
+ public void IEnumClaimsIdCtorMultipleIdentitiesWorks ()
+ {
+ var baseId1 = new ClaimsIdentity ("baseId1");
+ var baseId2 = new GenericIdentity ("generic_name2", "baseId2");
+ var baseId3 = new GenericIdentity ("generic_name3", "baseId3");
+
+ var p = new ClaimsPrincipal (new List<ClaimsIdentity> { baseId1, baseId2, baseId3 });
+ Assert.IsNotNull (p.Identities, "#1");
+ Assert.AreEqual (3, p.Identities.Count (), "#2");
+
+ Assert.IsNotNull (p.Claims, "#3");
+ Assert.AreEqual (2, p.Claims.Count (), "#4");
+
+ Assert.AreEqual (baseId1, p.Identity, "#5");
+
+ Assert.IsTrue (p.Claims.Any (claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "generic_name2"), "#6");
+ Assert.IsTrue (p.Claims.Any (claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "generic_name3"), "#7");
+
+ Assert.AreEqual (baseId2.Claims.First (), p.Claims.First (), "#7");
+ Assert.AreEqual (baseId3.Claims.Last (), p.Claims.Last (), "#8");
+ }
+
+ #endregion
+
+ internal class TestPrincipal : IPrincipal
+ {
+ public IIdentity Identity { get; set; }
+
+ public bool IsInRole (string role)
+ {
+ throw new NotImplementedException ();
+ }
+ }
+ }
+}
+
+#endif
System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs
System.Runtime.Serialization.Formatters.Binary/ObjectWriter.cs
System.Runtime.Serialization.Formatters.Binary/MessageFormatter.cs
+System.Runtime.Versioning/CompatibilitySwitch.cs
System.Runtime.Versioning/ComponentGuaranteesAttribute.cs
System.Runtime.Versioning/ComponentGuaranteesOptions.cs
System.Runtime.Versioning/ResourceConsumptionAttribute.cs
System.Security.AccessControl/RegistrySecurityTest.cs
System.Security.AccessControl/SystemAclTest.cs
System.Security.Claims/ClaimsIdentityTest.cs
+System.Security.Claims/ClaimsPrincipalTest.cs
System.Security.Cryptography/AllTests2.cs
System.Security.Cryptography/AesCfbTest.cs
System.Security.Cryptography/AsymmetricAlgorithmTest.cs
+++ /dev/null
-// CS0163: Control cannot fall through from one case label `case 1:' to another
-// Line: 14
-
-using System;
-using System.Collections.Generic;
-
-static class C
-{
- public static IEnumerable<int> Test (int key)
- {
- switch (key) {
- case 1:
- yield return 0;
- case 2:
- yield return 2;
- default:
- throw new ArgumentOutOfRangeException ("symbol:" + key);
- }
- }
-}
\ No newline at end of file
-// CS0163: Control cannot fall through from one case label `case 3:' to another
-// Line: 21
+// CS0163: Control cannot fall through from one case label `case 1:' to another
+// Line: 14
-public class Foo
+using System;
+using System.Collections.Generic;
+
+static class C
{
- public static void Main()
+ public static IEnumerable<int> Test (int key)
{
- int a=5;
- int b=10;
- int c;
-
- switch (a)
- {
- case 1: c=a+b;
- return;
-
- case 2: c=a-b;
- return;
-
- case 3: c=a*b;
+ switch (key) {
+ case 1:
+ yield return 0;
+ case 2:
+ yield return 2;
+ default:
+ throw new ArgumentOutOfRangeException ("symbol:" + key);
}
}
-}
+}
\ No newline at end of file
--- /dev/null
+// CS8070: Control cannot fall out of switch statement through final case label `case 3:'
+// Line: 20
+
+public class Foo
+{
+ public static void Main()
+ {
+ int a=5;
+ int b=10;
+ int c;
+
+ switch (a)
+ {
+ case 1: c=a+b;
+ return;
+
+ case 2: c=a-b;
+ return;
+
+ case 3: c=a*b;
+ }
+ }
+}
public string DefaultIndexerName;
public bool? CLSAttributeValue;
public TypeSpec CoClass;
+
+ static bool HasMissingType (ConstructorInfo ctor)
+ {
+#if STATIC
+ //
+ // Mimic odd csc behaviour where missing type on predefined
+ // attributes means the attribute is silently ignored. This can
+ // happen with PCL facades
+ //
+ foreach (var p in ctor.GetParameters ()) {
+ if (p.ParameterType.__ContainsMissingType)
+ return true;
+ }
+#endif
+
+ return false;
+ }
public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
{
if (dt.Namespace != "System")
continue;
+ if (HasMissingType (a.Constructor))
+ continue;
+
if (bag == null)
bag = new AttributesBag ();
if (dt.Namespace != "System.Runtime.InteropServices")
continue;
+ if (HasMissingType (a.Constructor))
+ continue;
+
if (bag == null)
bag = new AttributesBag ();
// This is used to track the Entry Point,
//
var settings = Compiler.Settings;
- if (settings.NeedsEntryPoint && MemberName.Name == "Main" && (settings.MainClass == null || settings.MainClass == Parent.TypeBuilder.FullName)) {
+ if (settings.NeedsEntryPoint && MemberName.Name == "Main" && !IsPartialDefinition && (settings.MainClass == null || settings.MainClass == Parent.TypeBuilder.FullName)) {
if (IsEntryPoint ()) {
if (Parent.DeclaringAssembly.EntryPoint == null) {
if (Parent.IsGenericOrParentIsGeneric || MemberName.IsGeneric) {
public sealed class BackingField : Field
{
readonly Property property;
+ const Modifiers DefaultModifiers = Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | Modifiers.DEBUGGER_HIDDEN;
public BackingField (Property p, bool readOnly)
- : base (p.Parent, p.type_expr,
- Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (p.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
+ : base (p.Parent, p.type_expr, DefaultModifiers | (p.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
new MemberName ("<" + p.GetFullName (p.MemberName) + ">k__BackingField", p.Location), null)
{
this.property = p;
Location)));
args.Add (new Argument (new LocalVariableReference (obj1, Location)));
- var cas = Module.PredefinedMembers.InterlockedCompareExchange_T.Resolve (Location);
+ var cas = Module.PredefinedMembers.InterlockedCompareExchange_T.Get ();
if (cas == null) {
// Workaround for cripled (e.g. microframework) mscorlib without CompareExchange
body.AddStatement (new Lock (
V_4 = 4,
V_5 = 5,
V_6 = 6,
- Future = 100,
+ Experimental = 100,
- Default = LanguageVersion.Future,
+ Default = LanguageVersion.V_6,
}
public enum RuntimeVersion
case "6":
settings.Version = LanguageVersion.V_6;
return ParseResult.Success;
- case "future":
- settings.Version = LanguageVersion.Future;
+ case "experimental":
+ settings.Version = LanguageVersion.Experimental;
return ParseResult.Success;
+ case "future":
+ report.Warning (8000, 1, "Language version `future' is no longer supported");
+ goto case "6";
}
report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', Default or value in range 1 to 6", value);
class MissingBreak : Statement
{
- SwitchLabel label;
+ readonly SwitchLabel label;
public MissingBreak (SwitchLabel sl)
{
this.loc = sl.loc;
}
+ public bool FallOut { get; set; }
+
protected override void DoEmit (EmitContext ec)
{
}
protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
{
- fc.Report.Error (163, loc, "Control cannot fall through from one case label `{0}' to another",
- label.GetSignatureForError ());
-
+ if (FallOut) {
+ fc.Report.Error (8070, loc, "Control cannot fall out of switch statement through final case label `{0}'",
+ label.GetSignatureForError ());
+ } else {
+ fc.Report.Error (163, loc, "Control cannot fall through from one case label `{0}' to another",
+ label.GetSignatureForError ());
+ }
return true;
}
}
if (!section_rc.IsUnreachable && prev_label != null) {
prev_label.SectionStart = false;
- var s = new MissingBreak (prev_label);
+ var s = new MissingBreak (prev_label) {
+ FallOut = true
+ };
+
s.MarkReachable (rc);
block.Statements.Add (s);
}
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
+using System.Diagnostics;
public class Test
{
if (!(fields.Length > 0))
return 1;
object [] field_atts = fields[0].GetCustomAttributes (false);
- if (!(field_atts.Length > 0))
+ if (field_atts.Length != 2)
return 2;
- if (field_atts[0].GetType() != typeof (CompilerGeneratedAttribute))
+ if (field_atts[0].GetType() != typeof (DebuggerBrowsableAttribute))
return 3;
+ if (field_atts[1].GetType() != typeof (CompilerGeneratedAttribute))
+ return 4;
if (fields [0].Name != "<Foo>k__BackingField")
return 10;
}
}
+.class public auto ansi beforefieldinit A2
+ extends [mscorlib]System.Attribute
+{
+
+ .custom instance void class [mscorlib]System.AttributeUsageAttribute::'.ctor'(valuetype ['missing-lib']System.AttributeTargets) = (01 00 80 00 00 00 00 00 ) // ........
+
+ .method public hidebysig specialname rtspecialname
+ instance void .ctor() cil managed
+ {
+ ldarg.0
+ call instance void [mscorlib]System.Attribute::.ctor()
+ ret
+ }
+}
+
.class public auto ansi beforefieldinit X extends [mscorlib]System.Object
{
.custom instance void A::.ctor(class [mscorlib]System.Type) = ( 01 00 44 58 58 2C 20 62 75 67 2D 31 2D 6C 69 62 // ..DXX, missing-lib
// Compilation test only for missing 2nd level dependecies
+[A2]
class Program
{
void Test ()
-// Compiler options: -langversion:future
using System;
using System.Threading;
using System.Threading.Tasks;
-// Compiler options: -langversion:future
-
using System;
using System.Threading.Tasks;
using System.Threading;
-// Compiler options: -langversion:future
-
using System;
using System.Threading.Tasks;
using System.Threading;
-// Compiler options: -langversion:future
-
using System;
using System.Threading;
using System.Threading.Tasks;
-// Compiler options: -langversion:future
-
using System;
using System.Threading;
using System.Threading.Tasks;
-// Compiler options: -langversion:future
-
using System;
using System.Threading.Tasks;
-// Compiler options: -langversion:future
-
using System;
using System.Threading.Tasks;
-// Compiler options: -langversion:future
-
using System;
using System.Threading.Tasks;
using System.Threading;
-// Compiler options: -langversion:future
-
using System;
using System.Threading;
using System.Threading.Tasks;
-// Compiler options: -langversion:future
-
using System;
using System.Threading.Tasks;
using System.Threading;
-// Compiler options: -langversion:future
-
using System;
using System.Threading.Tasks;
using System.Threading;
-// Compiler options: -langversion:future
-
using System;
using System.Threading.Tasks;
using System.Threading;
-// Compiler options: -langversion:future
using System;
using System.Threading.Tasks;
using System.Threading;
-// Compiler options: -langversion:future
-
using System;
using System.Threading;
using System.Threading.Tasks;
-// Compiler options: -langversion:future
-
using System;
using System.Threading.Tasks;
using System.Threading;
-// Compiler options: -langversion:future
using System;
using System.Threading.Tasks;
using System.Threading;
-// Compiler options: -langversion:future
using System;
using System.Threading.Tasks;
-// Compiler options: -langversion:future
-
using System;
using System.Threading;
using System.Threading.Tasks;
--- /dev/null
+partial class X
+{
+ static partial void Main ();
+
+ static partial void Main ()
+ {
+ }
+}
\ No newline at end of file
<size>8</size>\r
</method>\r
<method name="Int32 Main()" attrs="150">\r
- <size>301</size>\r
+ <size>336</size>\r
</method>\r
<method name="Void .ctor()" attrs="6278">\r
<size>7</size>\r
</method>\r
</type>\r
</test>\r
+ <test name="test-partial-33.cs">\r
+ <type name="X">\r
+ <method name="Void Main()" attrs="145">\r
+ <size>2</size>\r
+ </method>\r
+ <method name="Void .ctor()" attrs="6278">\r
+ <size>7</size>\r
+ </method>\r
+ </type>\r
+ </test>\r
<test name="test-primary-ctor-01.cs">\r
<type name="Simple">\r
<method name="Int32 get_Property()" attrs="2177">\r
ICALL(ASSEM_16, "InternalImageRuntimeVersion", ves_icall_System_Reflection_Assembly_InternalImageRuntimeVersion)
ICALL(ASSEM_17, "LoadFrom", ves_icall_System_Reflection_Assembly_LoadFrom)
ICALL(ASSEM_18, "LoadPermissions", ves_icall_System_Reflection_Assembly_LoadPermissions)
- /*
- * Private icalls for the Mono Debugger
- */
-ICALL(ASSEM_19, "MonoDebugger_GetMethodToken", ves_icall_MonoDebugger_GetMethodToken)
/* normal icalls again */
ICALL(ASSEM_20, "get_EntryPoint", ves_icall_System_Reflection_Assembly_get_EntryPoint)
*to_upper_data_high = ToUpperDataHigh;
}
-ICALL_EXPORT gint32
-ves_icall_MonoDebugger_GetMethodToken (MonoReflectionMethod *method)
-{
- return method->method->token;
-}
-
/*
* We return NULL for no modifiers so the corlib code can return Type.EmptyTypes
* and avoid useless allocations.
return mono_string_new_utf16 (domain, data, len);
}
+/**
+ * mono_string_from_utf32:
+ * @data: the UTF32 string (LPWSTR) to convert
+ *
+ * Converts a UTF32 (UCS-4)to a MonoString.
+ *
+ * Returns: a MonoString.
+ */
+MonoString *
+mono_string_from_utf32 (mono_unichar4 *data)
+{
+ MonoString* result = NULL;
+ mono_unichar2 *utf16_output = NULL;
+ GError *error = NULL;
+ glong items_written;
+ int len = 0;
+
+ if (!data)
+ return NULL;
+
+ while (data [len]) len++;
+
+ utf16_output = g_ucs4_to_utf16 (data, len, NULL, &items_written, &error);
+
+ if (error)
+ g_error_free (error);
+
+ result = mono_string_from_utf16 (utf16_output);
+ g_free (utf16_output);
+ return result;
+}
static char *
mono_string_to_utf8_internal (MonoMemPool *mp, MonoImage *image, MonoString *s, gboolean ignore_error, MonoError *error)
MONO_API MonoString *
mono_string_from_utf16 (mono_unichar2 *data);
+MONO_API MonoString *
+mono_string_from_utf32 (mono_unichar4 *data);
+
MONO_API mono_bool
mono_string_equal (MonoString *s1, MonoString *s2);
binary_protocol_thread_unregister ((gpointer)tid);
SGEN_LOG (3, "unregister thread %p (%p)", p, (gpointer)tid);
+#ifndef HAVE_KW_THREAD
+ mono_native_tls_set_value (thread_info_key, NULL);
+#else
+ sgen_thread_info = NULL;
+#endif
+
if (p->info.runtime_thread)
mono_threads_add_joinable_thread ((gpointer)tid);
mono_thread_detach_internal (thread->internal_thread);
}
+/*
+ * mono_thread_detach_if_exiting:
+ *
+ * Detach the current thread from the runtime if it is exiting, i.e. it is running pthread dtors.
+ * This should be used at the end of embedding code which calls into managed code, and which
+ * can be called from pthread dtors, like dealloc: implementations in objective-c.
+ */
+void
+mono_thread_detach_if_exiting (void)
+{
+ if (mono_thread_info_is_exiting ()) {
+ MonoInternalThread *thread;
+
+ thread = mono_thread_internal_current ();
+ if (thread) {
+ mono_thread_detach_internal (thread);
+ mono_thread_info_detach ();
+ }
+ }
+}
+
void
mono_thread_exit ()
{
MONO_API mono_bool mono_thread_is_foreign (MonoThread *thread);
+extern MONO_API void mono_thread_detach_if_exiting (void);
+
MONO_END_DECLS
#endif /* _MONO_METADATA_THREADS_H_ */
void
mono_jit_cleanup (MonoDomain *domain)
{
+ mono_thread_manage ();
+
mini_cleanup (domain);
}
TargetOptions opts;
opts.JITExceptionHandling = 1;
- EngineBuilder b (unwrap (MP));
+ std::unique_ptr<Module> Owner(unwrap(MP));
+
+#if LLVM_API_VERSION >= 2
+ StringRef cpu_name = sys::getHostCPUName ();
+
+ // EngineBuilder no longer has a copy assignment operator (?)
+ EngineBuilder b (std::move(Owner));
+ EngineBuilder &eb = b;
+#ifdef TARGET_AMD64
+ ExecutionEngine *EE = b.setJITMemoryManager (mono_mm).setTargetOptions (opts).setAllocateGVsWithCode (true).setMCPU (cpu_name).setCodeModel (CodeModel::Large).create ();
+#else
+ ExecutionEngine *EE = b.setJITMemoryManager (mono_mm).setTargetOptions (opts).setAllocateGVsWithCode (true).setMCPU (cpu_name).create ();
+#endif
+
+#else
+
+ EngineBuilder b (std::move(Owner));
EngineBuilder &eb = b;
eb = eb.setJITMemoryManager (mono_mm).setTargetOptions (opts).setAllocateGVsWithCode (true);
#if LLVM_API_VERSION >= 1
#endif
ExecutionEngine *EE = eb.create ();
+#endif
+
g_assert (EE);
mono_ee->EE = EE;
return;
mono_handle_native_sigsegv (SIGSEGV, ctx);
- if (mono_do_crash_chaining)
+ if (mono_do_crash_chaining) {
mono_chain_signal (SIG_HANDLER_PARAMS);
+ return;
+ }
}
mono_arch_handle_exception (ctx, exc);
if (!mono_do_crash_chaining && mono_chain_signal (SIG_HANDLER_PARAMS))
return;
mono_handle_native_sigsegv (SIGSEGV, ctx);
- if (mono_do_crash_chaining)
+ if (mono_do_crash_chaining) {
mono_chain_signal (SIG_HANDLER_PARAMS);
+ return;
+ }
}
ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
mono_handle_native_sigsegv (SIGSEGV, ctx);
- if (mono_do_crash_chaining)
+ if (mono_do_crash_chaining) {
mono_chain_signal (SIG_HANDLER_PARAMS);
+ return;
+ }
}
mono_arch_handle_exception (ctx, NULL);
{
return (level <= current_level && mask & current_mask);
}
+
+
+static MonoLogCallback log_callback;
+static MonoPrintfCallback printf_callback;
+
+static const char*
+log_level_get_name (GLogLevelFlags log_level)
+{
+ switch (log_level & G_LOG_LEVEL_MASK) {
+ case G_LOG_LEVEL_ERROR: return "error";
+ case G_LOG_LEVEL_CRITICAL: return "critical";
+ case G_LOG_LEVEL_WARNING: return "warning";
+ case G_LOG_LEVEL_MESSAGE: return "message";
+ case G_LOG_LEVEL_INFO: return "info";
+ case G_LOG_LEVEL_DEBUG: return "debug";
+ default: return "unknown";
+ }
+}
+
+static void
+log_adapter (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data)
+{
+ log_callback (log_domain, log_level_get_name (log_level), message, log_level & G_LOG_LEVEL_ERROR, user_data);
+}
+
+static void
+stdout_adapter (const gchar *message)
+{
+ printf_callback (message, TRUE);
+}
+
+static void
+stderr_adapter (const gchar *message)
+{
+ printf_callback (message, FALSE);
+}
+
+/**
+ * mono_trace_set_log_handler:
+ *
+ * @callback The callback that will replace the default logging handler
+ * @user_data Argument passed to @callback
+ *
+ * The log handler replaces the default runtime logger. All logging requests with be routed to it.
+ * If the fatal argument in the callback is true, the callback must abort the current process. The runtime expects that
+ * execution will not resume after a fatal error.
+ */
+void
+mono_trace_set_log_handler (MonoLogCallback callback, void *user_data)
+{
+ log_callback = callback;
+ g_log_set_default_handler (log_adapter, user_data);
+}
+
+
+/**
+ * mono_trace_set_printf_handler:
+ *
+ * @callback The callback that will replace the default runtime behavior.
+ *
+ * The printf handler replaces the default runtime output handler. This is used by free form output done by the runtime.
+ * If is_stdout is false, the callback is expected to flush the stream after writing to it.
+ *
+ */
+MONO_API void
+mono_trace_set_printf_handler (MonoPrintfCallback callback)
+{
+ printf_callback = callback;
+ g_set_print_handler (stdout_adapter);
+ g_set_printerr_handler (stderr_adapter);
+}
MONO_API void
mono_trace_set_mask_string (const char *value);
+typedef void (*MonoLogCallback) (const char *log_domain, const char *log_level, const char *message, mono_bool fatal, void *user_data);
+typedef void (*MonoPrintfCallback) (const char *string, mono_bool is_stdout);
+
+MONO_API void
+mono_trace_set_log_handler (MonoLogCallback callback, void *user_data);
+
+MONO_API void
+mono_trace_set_printf_handler (MonoPrintfCallback callback);
+
MONO_END_DECLS
#endif /* __MONO_LOGGER_H__ */
#if defined(__MACH__)
+#include <stdio.h>
#include <objc/runtime.h>
#include <objc/message.h>
#include <mono/utils/mono-compiler.h>
static size_t thread_info_size;
static MonoThreadInfoCallbacks threads_callbacks;
static MonoThreadInfoRuntimeCallbacks runtime_callbacks;
-static MonoNativeTlsKey thread_info_key, small_id_key;
+static MonoNativeTlsKey thread_info_key, thread_exited_key, small_id_key;
static MonoLinkedListSet thread_list;
static gboolean disable_new_interrupt = FALSE;
static gboolean mono_threads_inited = FALSE;
THREADS_DEBUG ("unregistering info %p\n", info);
+ mono_native_tls_set_value (thread_exited_key, GUINT_TO_POINTER (1));
+
mono_threads_core_unregister (info);
/*
mono_thread_small_id_free (small_id);
}
+static void
+thread_exited_dtor (void *arg)
+{
+#if defined(__MACH__)
+ /*
+ * Since we use pthread dtors to clean up thread data, if a thread
+ * is attached to the runtime by another pthread dtor after our dtor
+ * has ran, it will never be detached, leading to various problems
+ * since the thread ids etc. will be reused while they are still in
+ * the threads hashtables etc.
+ * Dtors are called in a loop until all user tls entries are 0,
+ * but the loop has a maximum count (4), so if we set the tls
+ * variable every time, it will remain set when system tls dtors
+ * are ran. This allows mono_thread_info_is_exiting () to detect
+ * whenever the thread is exiting, even if it is executed from a
+ * system tls dtor (i.e. obj-c dealloc methods).
+ */
+ mono_native_tls_set_value (thread_exited_key, GUINT_TO_POINTER (1));
+#endif
+}
+
/**
* Removes the current thread from the thread list.
* This must be called from the thread unregister callback and nowhere else.
}
}
+/*
+ * mono_thread_info_is_exiting:
+ *
+ * Return whenever the current thread is exiting, i.e. it is running pthread
+ * dtors.
+ */
+gboolean
+mono_thread_info_is_exiting (void)
+{
+#if defined(__MACH__)
+ if (mono_native_tls_get_value (thread_exited_key) == GUINT_TO_POINTER (1))
+ return TRUE;
+#endif
+ return FALSE;
+}
+
void
mono_threads_init (MonoThreadInfoCallbacks *callbacks, size_t info_size)
{
thread_info_size = info_size;
#ifdef HOST_WIN32
res = mono_native_tls_alloc (&thread_info_key, NULL);
+ res = mono_native_tls_alloc (&thread_exited_key, NULL);
#else
res = mono_native_tls_alloc (&thread_info_key, unregister_thread);
+ res = mono_native_tls_alloc (&thread_exited_key, thread_exited_dtor);
#endif
g_assert (res);
void
mono_thread_info_detach (void) MONO_INTERNAL;
+gboolean
+mono_thread_info_is_exiting (void) MONO_INTERNAL;
+
THREAD_INFO_TYPE *
mono_thread_info_current (void) MONO_INTERNAL;
<PreBuildEvent>\r
<Command>winsetup.bat</Command>\r
</PreBuildEvent>\r
+ <MASM>\r
+ <PreprocessorDefinitions>X64</PreprocessorDefinitions>\r
+ </MASM>\r
</ItemDefinitionGroup>\r
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />\r
<ImportGroup Label="ExtensionTargets">\r